我试图最小化一个简单的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
。
Traceback (most recent call last):
File "<ipython-input-300-8809d7df9a20>", line 31, in <module>
TSLS = minimize(GMM_criterion, coeff, args=(df, dep, exog, endog, instr),
method='SLSQP')
File "C:\Users\Igor\Anaconda3\lib\site-
packages\scipy\optimize\_minimize.py", line 611, in minimize
constraints, callback=callback, **options)
File "C:\Users\Igor\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py",
line 379, in _minimize_slsqp
fx = func(x)
File "C:\Users\Igor\Anaconda3\lib\site-
packages\scipy\optimize\optimize.py",
line 293, in function_wrapper
return function(*(wrapper_args + args))
File "<ipython-input-300-8809d7df9a20>", line 25, in GMM_criterion
GMM = float(GMM)
TypeError: only size-1 arrays can be converted to Python scalars`
您对如何解决此问题有任何建议吗? 谢谢