I am trying to do a GMM(Generalized Method of Moments) by NMinimize
, it comes up with the warning 'The objective function is not a scalar', here's what I have tried:
- I adjusted the function step by step and found that the problem is about the minus e=y-y`Pred, after I delete the minus, it worked.But I really can't understand why.
- When I use the functions directly, it gives a scalar. I think this is the evidence that my dimension of vector and matrix is right, which I have checked also.
I am new with the matrix calculate, I think this problem must be somehow stupid, but I can't fix it.Sorry :(
ClearAll[data`x, data`y, Winv, params, gmmObjective, beta]
(*Setting*)
data`x = {{1, 2, 3}, {4, 5, 6}};
data`y = {1, 2};
Winv = IdentityMatrix[3];
(*Original function*)
gmmObjective[params_, y_, x_, Matr_] :=
Module[{y`Pred, e, moments, avgMoment, ju`value},
y`Pred = x . params;
e = y - y`Pred;
moments = e . x;
ju`value = moments . Matr . Transpose[moments];
Return[ju`value];
]
NMinimize[{gmmObjective[beta, data`y, data`x, Winv],
Element[beta, Vectors[3, Reals]]}, beta]
(*Adjusted function*)
gmmObjective[params_, y_, x_, Matr_] :=
Module[{y`Pred, e, moments, avgMoment, ju`value},
y`Pred = x . params;
e = y`Pred;
moments = e . x;
ju`value = moments . Matr . Transpose[moments];
Return[ju`value];
]
NMinimize[{gmmObjective[beta, data`y, data`x, Winv],
Element[beta, Vectors[3, Reals]]}, beta]