[Python] Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
Phenomenon
A title error occurs when trying to fit with the least squares method in the leastsq of spicy.optimize.
from scipy import optimize
import numpy as np
def internalFunc1(x, plist):
a=plist[0]
b=plist[1]
return a*x**2+b
def myFunc(x, param):
a=param[0]
b=param[1]
return a*x+internalFunc1(x, b)
def fit(param, x, y):
def residual(param, x, y):
return y-myFunc(x, param)
result=optimize.leastsq(residual, param, args=(x, y))
return result
x=np.linspace(0, 10, 101)
y=np.random.randint(0, 10, 101)
param0=[1, [2, 3]]
fit(param0, x, y)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
Cause and Solution
List is included in the parameter of leastsq. The error disappeared when I corrected it as follows.
def myFunc(x, param):
a=param[0]
b=param[1:]
return a*x+internalFunc1(x, b)
x=np.linspace(0, 10, 101)
y=np.random.randint(0, 10, 101)
param0=[1, 2, 3]
fit(param0, x, y)
Recent Posts
See AllSummary Data analysis is performed using python. The analysis itself is performed using pandas, and the final results are stored in...
Phenomenon I get a title error when trying to import firestore with raspberry pi. from from firebase_admin import firestore ImportError:...
Overview If you want to do fitting, you can do it with scipy.optimize.leastsq etc. in python. However, when doing fitting, there are many...
Comments