我需要将函数拟合到数据数组并获得该函数方程的最佳系数.我使用 scipy 库中的 curve_fit 方法.它基于最小二乘法.
I need to fit function to array of data and get optimal coefficients of an equation of this function. I use curve_fit method from scipy library. It is based on least squares method.
import numpy as np from scipy.optimize import curve_fit #This is my function from which i need to get optimal coefficients 'a' and 'b' def func(x, a, b): return a*x**(b*x) #the arrays of input data x = [1,2,3,4,5] y =[6,7,8,9,10] #default (guess) coefficients p0 = [1, 1] popt, pcov = curve_fit(func, x, y, p0) print popt它返回以下错误
类型错误:不支持 ** 或 pow() 的操作数类型:'list' 和 'list'
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'list'
但是当我使用另一个更简单的功能而无需电源操作时它可以工作
But when I use the other, more simple function with no power operation it works
def func(x, a, b): return a*x + b它必须尝试将数字组合为整个输入数据数组的幂
It must be trying to bulid number to a power of an entire array of input data
怎么办?请帮助...
推荐答案看起来你在追求元素级的力量提升?
It looks like you're after element-wise power-raising?
喜欢 a*x[i]**(b*x[i]) 对于每个 i?
Like a*x[i]**(b*x[i]) for each i?
在这种情况下,您必须使用 np.power 函数:
In that case, you have to use the np.power function:
def func(x,a,b): return a*np.power(x,b*x)然后就可以了.
(顺便说一句,将 x 和 y 从列表转换为 numpy 数组可能是值得的:np.array(x)).
(As an aside, it may be worthwhile to convert x and y from lists to numpy arrays: np.array(x)).
更多推荐
Python scipy:** 或 pow() 不支持的操作数类型:“list"和“list"
发布评论