import numpy as np
from scipy.optimize import curve_fit
x = b #1D array for X Axis
y = c #1D array for Y Axis
def func(x, a, b,c):
return ((a*(x**2)) + b*x + c)
iniguess = [0,0.038,13.99]
param, pcov = curve_fit(func, x, y, p0=iniguess)
print (param[0],param[1],param[2])
import matplotlib.pyplot as plt
plt.plot(x,y,'bo ')
xfit = b
yfit = func(xfit, param[0], param[1], param[3])
plt.plot(xfit,yfit,'r-')
plt.legend(['data','fit'],loc='best')
当我尝试计算预测的Y值时,这给我一个错误代码。错误是“ 索引3超出轴3的大小3的范围”
答案 0 :(得分:1)
正如@ Ben.T所指出的那样,问题在于代码中的param[3]
应该是param[2]
。当您有一个像param
这样的参数列表要依次传递给一个函数(即func(..., param[0], param[1], param[2], ...)
)时,可以使用{{1} }。前导asterix *foo
is a shortcut in the python syntax使您可以一次传递多个参数,而不必一次传递一个。使用这些快捷方式可以使您的代码更易于阅读,并且不易出错,因为您不必再为*param
的各个索引而烦恼了。
这是您代码的完整工作版本。注意在创建param
的行中使用*param
:
yfit
输出:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return ((a*(x**2)) + b*x + c)
iniguess = [2,0.038,13.99]
# make some fake example data
N = 1000
x = np.linspace(0, 10, N)
y = func(x, *iniguess)
# add some noise to make this a non-trivial curve fitting
y += np.random.normal(size=N)
param, pcov = curve_fit(func, x, y, p0=iniguess)
print(param)
plt.plot(x,y,'bo ')
yfit = func(x, *param)
plt.plot(x,yfit,'r-')
plt.legend(['data','fit'],loc='best')