简体   繁体   中英

Scipy Least Squares 2 squares desired // Error: Result from function call is not a proper array of floats

Current I'm attempting to use scipy's least squares, or any of their minimization functions to minimize a function with 5 parameters.

What I would like scipy to do is minimize some function using a standard least squares.

My code is below:

 fitfunc1 = lambda p, xx, yy, zz: -(50000*(xx + (p[0] + p[1])*yy +  
 p[3]))/(1.67*(-p[2]*yy + zz + p[4]))

 errfunc1 = lambda p,x11, xx, yy, zz: fitfunc1(p, xx, yy, zz) - x11
 x0 = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1], dtype = float)

res3 = leastsq(errfunc1, x0[:], args=(x1, x, y, z))

where x1, x, y, z are all column numpy arrays of the same length about 90x1

I'm currently getting an error that says ' Error: Result from function call is not a proper array of floats', I've attempted many possibilities, and tried to rewrite this the way it is described in examples, but doesn't seem to work.

In addition: I actually would like to solve the problem:

min sum (f - x1)**2 + (g - x2)**2 where f = f(p, x, y, z) and g = g(p, x, y, z) and x, y, z, x1, y1 are all data, but attempting to find the parameters, p (6 of them).

Is this currently possible in least squares? I have attempted using scipy.minimize, but when this is done using the Nedler's Mead method, it doesn't seem to work either.

Here is my current code:

def f(phi, psi, theta, xnot, ynot, znot):
  return sum(abs(   (-50000*(x[:]+ (psi + phi)*y[:] + xnot)/(1.67*(-
   theta*y[:] + z[:] + znot))) - x1[:]) //
  + abs(   (-50000*(-x[:]*(psi + phi) + y[:] + theta*(z[:]) + ynot)/(1.67*(-
  theta*y[:] + z[:] + znot))) - y1[:]))

  x0 = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1], dtype = float)
  res3 = leastsq(f, x0[:], args=(x1, y1, x, y, z))

I feel as if I am making some mistake that may be obvious to someone more familiar, but this is my first time using scipy. All help would be much appreciated.

I believe your problem is with the shape of the variables:

where x1, x, y, z are all column numpy arrays of the same length about 90x1

It causes your fitfunc1 and errfunc1 functions to return 2d arrays (of shape (90,1)), where the scipy optimization function expects a 1d array. Try reshaping your arrays, eg,

x1 = x1.reshape((90,)) ,

and similarly for the rest of your input variables. This should fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM