首页 > 解决方案 > 在 python 中使用 statsmodels.sandbox.regression.gmm.GMM 的问题

问题描述

我有一个因果中介分析案例,我想使用 gmm(广义矩量法)估计治疗效果。所以,我引用了这段代码。https://github.com/josef-pkt/misc/blob/master/notebooks/ex_gmm_gamma.ipynb 和这个问题使用 statsmodels.sandbox.regression.gmm.GMM 的问题

以下是我的代码。

from statsmodels.sandbox.regression.gmm import GMM

class GMMAB(GMM):

    def __init__(self, *args, **kwds):
        # set appropriate counts for moment conditions and parameters
        kwds.setdefault('k_moms', 6)
        kwds.setdefault('k_params', 6)
        super(GMMAB, self).__init__(*args, **kwds)


    def momcond(self, params):
        c = params
        y,m = self.endog.T #[y,m]
        x = self.exog.squeeze() # x
        #inst = self.instrument   
        
        g1 = m - c[1] - c[0]*x
        g2 = x*(m - c[1] - c[0]*x)
        g3 = y - c[2] - c[3]*x - c[4]*m- c[5]*m*x
        g4 = x*(y - c[2] - c[3]*x - c[4]*m- c[5]*m*x)
        g5 = m*(y - c[2] - c[3]*x - c[4]*m- c[5]*m*x)
        g6 = m*x*(y - c[2] - c[3]*x - c[4]*m- c[5]*m*x)
        g = np.column_stack((g1, g2, g3, g4, g5, g6))
        return g

beta0 = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
dta = pd.read_csv('mediation_data.csv')
y = np.array(dta.y) # y,m,x shape: [100000, 1] 
m = np.array(dta.m)
s = np.array(dta[['y','m']])
x = np.array(dta.x)
model = GMMAB(endog = s, exog = x, instrument = x, k_moms=6, k_params=6)

beta0 = np.array([0.1,0.1,0.1,0.1,0.1,0.1])
model.fit(beta0, maxiter=2, weights_method='hac', optim_method='nm')

我尝试在 jupyter 笔记本中运行此代码(没有例外),笔记本崩溃。我有 >100,000 个观察值,每个单元 i 都有 y_i、m_i、x_i。所以 y, m, x 都是至少 100,000-1 维的数组。

我不知道我是否以错误的方式实现 GMM 方法,或者我的笔记本内存不足(内存>3G)。

你能给我一些建议吗?

标签: pythonstatisticscrashstatsmodelsgmm

解决方案


推荐阅读