分散式估計

這個筆記本將透過幾個範例展示如何使用 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 月 03 日