Python上的LMFIT:TypeError:只能将size-1数组转换为Python标量
作者:互联网
我正在尝试在python(Anaconda)上使用LMFIT创建曲线拟合程序,但是我一直收到相同的错误消息:TypeError:只有大小为1的数组可以转换为Python标量.我只能使用一个函数来执行优化,但是当我尝试优化调用其他用户定义函数的函数时,出现此错误.
import numpy as np
from matplotlib import pyplot
import scipy.special as sp
from scipy import integrate
import lmfit as lm
#Defining the first function.
def function1(alpha,q,s,l):
Intensity = alpha**2 + q -s*alpha / (5*l)
return Intensity
#Defining a second function that will perform a integration over the first function.
def integrate_function(q,s,l):
func_parameters = {
'q':q,
's':s,
'l':l,
}
to_be_integrated = lambda alpha: function1(alpha, **func_parameters)
result, error = integrate.quad(to_be_integrated, 0, 10)
return result
#Setting up the LMFIT model. Here I also provide the initial guess for the parameters.
integrate_function_model = lm.Model(integrate_function, independent_vars=['q'])
integrate_function_model.set_param_hint('s', value=2, min=-10.0, max=20.0, vary=True)
integrate_function_model.set_param_hint('l', value=3, min=1.0, max=10.0, vary=True)
initial_params = integrate_function_model.make_params()
#Creating data to be fitted (I also add some noise)
#Here I set s=1.5 and l=5.0 and I want the optimization routine to be able to find out these numbers.
x_data = np.linspace(0, 10, 100)
y_data = np.zeros(len(x_data))
for i in range(len(x_data)):
y_data[i] = integrate_function(x_data[i],1.5,5.0) + 5.0*np.random.random()
#Fitting the data.
fitting = integrate_function_model.fit(y_data, initial_params, q=x_data, method='leastsq')
#Printing original data and fitted model.
pyplot.plot(x_data, y_data, color='green', lw=2)
pyplot.plot(x_data, fitting.best_fit, color='blue', lw=2)
pyplot.show()
解决方法:
使用np.array作为q的参数调用函数integration_function时,会发生错误:
>>> integrate_function(1,1,1)
333.33333333333337
>>> integrate_function(np.array([1,2]),1,1)
TypeError: only size-1 arrays can be converted to Python scalars
这发生在output.fit期间,其中调用了tegral.quad. Quad无法处理矢量化输入,这种情况正在您的情况下发生.
解决此问题的一种方法是更改integrate_function以处理q相应地为数组的情况,例如,通过手动包括对q中所有值的循环:
def integrate_function(q,s,l):
# Make q iterable if it is only a float/int
if not hasattr(q, '__iter__'):
q = np.array([q])
result = []
for q0 in q:
func_parameters = {
'q':q0,
's':s,
'l':l,
}
to_be_integrated = lambda alpha: function1(alpha, **func_parameters)
result.append(integrate.quad(to_be_integrated, 0, 10)[0])
return np.array(result)
然后使用修改后的tegral_function执行代码,将产生以下图:
标签:curve-fitting,scientific-computing,python,lmfit 来源: https://codeday.me/bug/20191108/2008548.html