I'm trying to fit a set of data (x,y,z) to obtained a best fit of the resulting surface through curve_fit. In particular z array has to be NxM "matrix". To show you an example I'll share you the code I wrote:
from scipy.optimize import curve_fit
import numpy as np
#Generate random 3D data points
x = np.random.random(10)
y = np.random.random(10)
X,Y = np.meshgrid(x,y)
z = np.sin(X * Y)
def func(xy, a, b, c, d, e, f):
x, y = xy
return a + b*x + c*y + d*x**2 + e*y**2 + f*x*y
#Perform curve fitting
popt, pcov = curve_fit(func, (X, Y), z)
#Print optimized parameters
print(popt)
When I launch the code I get the following error
ValueError: object too deep for desired array
Traceback (most recent call last):
File "C:\Users\..\PycharmProjects\GSP_Speed\prova.py", line 21, in <module>
popt, pcov = curve_fit(func, (X, Y), z)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\..\PycharmProjects\GSP_Speed\venv\Lib\site-packages\scipy\optimize\_minpack_py.py", line 963, in curve_fit
res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\..\PycharmProjects\GSP_Speed\venv\Lib\site-packages\scipy\optimize\_minpack_py.py", line 428, in leastsq
retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_minpack.error: Result from function call is not a proper array of floats.`
Can someone help me to get sort out the problem? Thank you very much
I tried to use both x,y and X,Y as inputs in the curve_fit
function but it doesn't work
I tried already to use both x,y and X,Y as inputs for curve_fit
but didn't work
The function curve_fit
expects an array-like training input. The result for provided (x,y)
-dataset is [-0.04166698 0.13532234 0.12139508 -0.0873608 -0.07659318 0.83186632]
. Check it out your self!
from scipy.optimize import curve_fit
import numpy as np
# Generate random 3D data points
x = np.random.random(10)
y = np.random.random(10)
X, Y = np.meshgrid(x, y)
z = np.sin(X * Y)
def func(xy, a, b, c, d, e, f):
x, y = xy
return a + b * x + c * y + d * x**2 + e * y**2 + f * x * y
# Flatten X and Y arrays
X_flat = X.flatten()
Y_flat = Y.flatten()
# Perform curve fitting
popt, pcov = curve_fit(func, (X_flat, Y_flat), z.flatten())
# Print optimized parameters
print(popt)