分散推定

このノートブックでは、distributed_estimation の使い方を示すためにいくつかのサンプルを紹介します。 DistributedModel クラスと exog および endog ジェネレーターをインポートします。

[1]:
import numpy as np
from scipy.stats.distributions import norm
from statsmodels.base.distributed_estimation import DistributedModel


def _exog_gen(exog, partitions):
    """partitions exog data"""

    n_exog = exog.shape[0]
    n_part = np.ceil(n_exog / partitions)

    ii = 0
    while ii < n_exog:
        jj = int(min(ii + n_part, n_exog))
        yield exog[ii:jj, :]
        ii += int(n_part)


def _endog_gen(endog, partitions):
    """partitions endog data"""

    n_endog = endog.shape[0]
    n_part = np.ceil(n_endog / partitions)

    ii = 0
    while ii < n_endog:
        jj = int(min(ii + n_part, n_endog))
        yield endog[ii:jj]
        ii += int(n_part)

次に、サンプルとしていくつかのランダムデータを生成します。

[2]:
X = np.random.normal(size=(1000, 25))
beta = np.random.normal(size=25)
beta *= np.random.randint(0, 2, size=25)
y = norm.rvs(loc=X.dot(beta))
m = 5

これは最も基本的なフィットであり、モデルクラスとデバイアス除去手順として OLS を使用するというすべてのデフォルトの設定を示しています。

[3]:
debiased_OLS_mod = DistributedModel(m)
debiased_OLS_fit = debiased_OLS_mod.fit(
    zip(_endog_gen(y, m), _exog_gen(X, m)), fit_kwds={"alpha": 0.2}
)

次に、GLM モデルクラスを使用する少し複雑なサンプルを実行します。

[4]:
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Gaussian

debiased_GLM_mod = DistributedModel(
    m, model_class=GLM, init_kwds={"family": Gaussian()}
)
debiased_GLM_fit = debiased_GLM_mod.fit(
    zip(_endog_gen(y, m), _exog_gen(X, m)), fit_kwds={"alpha": 0.2}
)

estimation_methodjoin_method を変更することもできます。以下のサンプルは、標準の OLS ケースでこれがどのように機能するかを示しています。ここでは、デバイアス除去手順の代わりに単純な平均化手法を使用しています。

[5]:
from statsmodels.base.distributed_estimation import _est_regularized_naive, _join_naive


naive_OLS_reg_mod = DistributedModel(
    m, estimation_method=_est_regularized_naive, join_method=_join_naive
)
naive_OLS_reg_params = naive_OLS_reg_mod.fit(
    zip(_endog_gen(y, m), _exog_gen(X, m)), fit_kwds={"alpha": 0.2}
)

最後に、使用する results_class を変更することもできます。次のサンプルは、正規化されていないモデルとシンプルな平均化を使用した簡単なケースでこれがどのように機能するかを示しています。

[6]:
from statsmodels.base.distributed_estimation import (
    _est_unregularized_naive,
    DistributedResults,
)


naive_OLS_unreg_mod = DistributedModel(
    m,
    estimation_method=_est_unregularized_naive,
    join_method=_join_naive,
    results_class=DistributedResults,
)
naive_OLS_unreg_params = naive_OLS_unreg_mod.fit(
    zip(_endog_gen(y, m), _exog_gen(X, m)), fit_kwds={"alpha": 0.2}
)

最終更新: 2024 年 10 月 3 日