[R] Error: Gradient function might be wrong - check it! for system of equations using Optimx
Olufemi Bolarinwa
dafemlions at yahoo.co.uk
Thu May 14 21:45:01 CEST 2015
Hello,I am estimating a system of 3 equations using a nonlinear GMM.The first and second equations consists of a linear part and a nonlinear part. The nonlinear parts is specified as a logit and the logit as a whole has a coefficient attached to it. For the first two equations, it is specified as follows:The whole equation: (a1*x1 + a2*x2 +a3*x3 + a4*x4 + a5*x5 + a22*(exp(a6*x6 + a7*x7 + a8*x9 + a9*x10 + a10*x11 + a11*x12 + a14*x16)/(1+exp(a6*x6 + a7*x7 + a8*x9 + a9*x10 + a10*x11 + a11*x12 + a14*x16))))
The linear portion of the equation: a1*x1 + a2*x2 +a3*x3 + a4*x4 + a5*x5The nonlinear portion of the equation: a22*(exp(a6*x6 + a7*x7 + a8*x9 + a9*x10 + a10*x11 + a11*x12 + a14*x16)/(1+exp(a6*x6 + a7*x7 + a8*x9 + a9*x10 + a10*x11 + a11*x12 + a14*x16)))The third equation is a logit with seven independent variables.The first and the second equation have 12 variables while the third equation have 7 variables. I did calculate my gradient from the moment conditions which led to a 12 by 12 matrix for the first equation, a 12 by 12 matrix for the second equation and a 7 by 7 matrix for the third equation because I have 12, 12, and 7 instruments for the three equations respectively.Since it is estimated as a system of equations, I made it into a block diagonal matrix which is a 31 by 31 matrix.
This is the matrix that I used in my optimx routine which gave me the error message
Maximizing -- use negfn and neggrError: Gradient function might be wrong - check it! In addition: Warning message:In gn - ga : longer object length is not a multiple of shorter object length
When I used optim routine, I got a similar error messageError in optim(parm, fn = obj, gr = gradient, method = "BFGS", hessian = TRUE) : gradient in optim evaluated to length 1023 not 35
I used the numDeriv to compare my gradient with the numerical gradient and I have the following error> require(numDeriv)> mygrad = gradient(parm)> numgrad = jacobian(obj, parm)> cbind(mygrad,numgrad)Error in cbind(mygrad, numgrad) : number of rows of matrices must match (see arg 2)> all.equal(mygrad,numgrad)[1] "Attributes: < Length mismatch: comparison on first 1 components >" "Attributes: < Component “dim”: Mean relative difference: 0.5625 >"[3] "Numeric: lengths (1023, 35) differ"
A way forward will be appreciated.
[[alternative HTML version deleted]]
More information about the R-help
mailing list