python - Python 上的 LMFIT : TypeError: only size-1 arrays can be converted to Python scalars

标签 python curve-fitting scientific-computing lmfit

我正在尝试在 Python (Anaconda) 上使用 LMFIT 创建曲线拟合程序,但我一直收到相同的错误消息:TypeError: only size-1 arrays can be converted to Python scalars。我能够仅使用一个函数执行优化,但是当我尝试优化调用其他用户定义函数的函数时,出现此错误。

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()

最佳答案

错误发生在你的函数integrate_functionnp.array 调用作为 q 的参数:

>>> 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 期间其中 integrate.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)

使用修改后的 integrate_function 执行您的代码然后产生以下情节:

enter image description here

关于python - Python 上的 LMFIT : TypeError: only size-1 arrays can be converted to Python scalars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52609263/

相关文章:

python - 将 HTML 下拉列表中的值发送到 Flask app.route

python - 如何在 Django 管理站点中显示 django-simple-history 的历史表?

python - Pandas 从数据框中提取不存在于另一个数据框中的列

python - scipy curve_fit 提高 "OptimizeWarning: Covariance of the parameters could not be estimated"

python curve_fit不适用于刚性模型

python - SciPy 全局最小曲线拟合

python - OpenCV Python - 修复损坏的文本

python - 我对 Scipy curve_fit 的使用似乎效果不佳

c++ - 显式链接 intel icpc openmp

numpy - 涉及 Scitools、NumPy 和 SciPy 的推荐设置