【发布时间】:2015-11-23 02:49:27
【问题描述】:
我正在尝试遵循并重复使用由名为@ThePredator 的人建议的一段代码(使用我自己的数据)(我无法评论该线程,因为我目前没有所需的 50 声望)。完整代码如下:
import numpy as np # This is the Numpy module
from scipy.optimize import curve_fit # The module that contains the curve_fit routine
import matplotlib.pyplot as plt # This is the matplotlib module which we use for plotting the result
""" Below is the function that returns the final y according to the conditions """
def fitfunc(x,a1,a2):
y1 = (x**(a1) )[x<xc]
y2 = (x**(a1-a2) )[x>xc]
y3 = (0)[x==xc]
y = np.concatenate((y1,y2,y3))
return y
x = array([0.001, 0.524, 0.625, 0.670, 0.790, 0.910, 1.240, 1.640, 2.180, 35460])
y = array([7.435e-13, 3.374e-14, 1.953e-14, 3.848e-14, 4.510e-14, 5.702e-14, 5.176e-14, 6.0e-14,3.049e-14,1.12e-17])
""" In the above code, we have imported 3 modules, namely Numpy, Scipy and matplotlib """
popt,pcov = curve_fit(fitfunc,x,y,p0=(10.0,1.0)) #here we provide random initial parameters a1,a2
a1 = popt[0]
a2 = popt[1]
residuals = y - fitfunc(x,a1,a2)
chi-sq = sum( (residuals**2)/fitfunc(x,a1,a2) ) # This is the chi-square for your fitted curve
""" Now if you need to plot, perform the code below """
curvey = fitfunc(x,a1,a2) # This is your y axis fit-line
plt.plot(x, curvey, 'red', label='The best-fit line')
plt.scatter(x,y, c='b',label='The data points')
plt.legend(loc='best')
plt.show()
我在运行这段代码时遇到了一些问题,我得到的错误如下:
y3 = (0)[x==xc]
TypeError: 'int' 对象没有属性 'getitem'
还有:
xc 未定义
我没有看到代码中缺少任何内容(不应该定义 xc 吗?)。
能否请作者 (@ThePredator) 或其他对此有所了解的人帮助我确定我没有看到的内容。
-
新版代码:
import numpy as np # This is the Numpy module from scipy.optimize import curve_fit import matplotlib.pyplot as plt def fitfunc(x, a1, a2, xc): if x.all() < xc: y = x**a1 elif x.all() > xc: y = x**(a1 - a2) * x**a2 else: y = 0 return y xc = 2 x = np.array([0.001, 0.524, 0.625, 0.670, 0.790, 0.910, 1.240, 1.640, 2.180, 35460]) y = np.array([7.435e-13, 3.374e-14, 1.953e-14, 3.848e-14, 4.510e-14, 5.702e-14, 5.176e-14, 6.0e-14,3.049e-14,1.12e-17]) popt,pcov = curve_fit(fitfunc,x,y,p0=(1.0,1.0)) a1 = popt[0] a2 = popt[1] residuals = y - fitfunc(x, a1, a2, xc) chisq = sum((residuals**2)/fitfunc(x, a1, a2, xc)) curvey = [fitfunc(val, a1, a2, xc) for val in x] # y-axis fit-line plt.plot(x, curvey, 'red', label='The best-fit line') plt.scatter(x,y, c='b',label='The data points') plt.legend(loc='best') plt.show()
【问题讨论】:
-
如果你引用它的值,你确实需要定义
xc(就像你在fitfunc中使用的比较一样。)y3 = (0)[x==xc]这一行不是有效的Python语法:@987654326 @ 是一个整数对象,不能使用 NumPy 样式的布尔索引进行索引,[x==xc]。 -
chi-sq是无效的变量名,请改用下划线。 -
谢谢大家。理解了 y3 = (0)[x==xc]、chi-sq 和数组中的错误。关于变量xc,我应该用一个初始值来定义它,提供给拟合函数吗?
-
在答案的 cmets 中,您已经更改了代码,但没有在您的问题中更新它。您现在声称在生成的代码中有另一个未指定的错误。我还是不明白你是怎么从@ThePredator 明显的
if(x==xc) y = 0;变成y3 = (0)[x==xc]的。 -
@ThePredator python 代码已经有
y3 = (0)[x==xc]它实际上是提问者提到if(x==xc) y = 0;作为一段原始代码的原始问题。