Search
[Python] Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
- M.R

- Oct 17, 2021
- 1 min read
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 resultx=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)





Comments