top of page

[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 All

[Python] Conditionally fitting

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


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page