我试图最小化一个简单的GMM标准,从Pandas数据帧调用变量。每个列名表示数据帧中的一列(492个观测值)。在第一个块中,我从数据帧定义矩阵和向量,在第二部分中,我计算了一个矩量方法准则,通过设置正确的系数coeffs
将其最小化。这些对象对于矩阵乘法是一致的,如果我使用coeff
的初始值一步一步地做,我最终得到一个标量。但是,如果它不起作用,当我把函数传递给最小值时。在
import numpy as np
import pandas as pd
from numpy.linalg import inv
from scipy.optimize import fsolve, minimize, fmin_bfgs
df = pd.read_csv('data.csv')
dep = ['dep'] # A column name in my dataframe
exog = ['exog1', 'exog2', 'exog3'] # A list of columns
endog = ['endog']
instr = ['instr']
coeff = np.array([[0,0,0,0]]).T
def GMM_criterion(coeff, df, dep, exog, endog, instr):
# Set up variables
x = endog + exog
z = exog + instr
n = df.shape[0]
x = df[x].values # A (492 x 4) matrix
z = df[z].values # A (492 x 4) matrix
y = df[dep].values # A (492 x 1) vector
y_hat = x @ coeff # A (492 x 1) vector of predicted values
resid = y - y_hat # A (492 x 1) vector of residuals
# Compute GMM criterion
W = 1/n * inv(z.T @ z) # A (4x4) weighting matrix
g = 1/n * z.T @ resid # A (4x1) vector
GMM = n * g.T @ W @ g # Becomes a (1x1) numpy.ndarray
GMM = GMM.flatten()
GMM = float(GMM)
return GMM
GMM = minimize(GMM_criterion, coeff, args=(df, dep, exog, endog, instr),
method='SLSQP')
我得到这个错误only size-1 arrays can be converted to Python scalars
。在
你对如何解决这个问题有什么建议吗? 谢谢
目前没有回答
相关问题 更多 >
编程相关推荐