I am trying to minimize a simple GMM criterion, calling variables from a Pandas dataframe. Each column name present a column in the dataframe (492 observations). In the first block I define matrices and vector from the dataframe, in the second part I compute a method of moments criterion that should be minimized by setting the right coefficients coeffs
. The objects are conformable for matrix multiplication, and if I do it step by step using the initial value for coeff
I finally get a scalar. However, if it does not work when I pass the function to the minimizer.
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')
I get this error 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`
Do you have any suggestion on how to fix this? Thanks