【发布时间】:2016-01-18 09:39:50
【问题描述】:
我是编程方面的菜鸟,尤其是曲线拟合方面的菜鸟。但我尝试将模型曲线拟合到我使用 Python 和 Numpy 进行的一些测量中。
我成功地将“拟合”曲线绘制到一组数据中。好吧,它似乎做到了。事实证明,该函数仅使用初始猜测,并没有尝试实际拟合曲线。我通过对不同数据集使用相同的初始猜测来测试这一点。结果是这样的:
fitParams 的输出是fitCovariances(这似乎是很奇怪的值):
[ 540. 2.5 2. ]
[[ inf inf inf]
[ inf inf inf]
[ inf inf inf]]
def fitFunc() 的输出只是重复的初始猜测值。
我首先为第 5 个数据集尝试了我的脚本,这似乎还不错。但你可以看到,每条“拟合曲线”都是完全相同的,只是使用了最初的猜测。
这是脚本:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy
import math
import csv
import matplotlib as mpl
mpl.rcParams['text.usetex']=True
mpl.rcParams['text.latex.unicode']=True
#model
def fitFunc(P_max, x, x_0, w_z):
print P_max
print x_0
print w_z
return 0.5 * P_max * (1 - scipy.special.erf((scipy.sqrt(2) * (x - x_0)) / w_z))
fig = plt.figure()
#for-loop to read and curve fit for all data sets
for n in range (1,7):
x_model = np.linspace(-1,6,5000)
y_model = []
x = []
P = []
name = 'data_' + str(n)
with open(name + '.csv', 'rb') as f:
data = csv.reader(f, delimiter = ';')
for row in data:
x.append(float(row[1]))
P.append(float(row[2]))
fitParams, fitCovariances = curve_fit(fitFunc, np.array(x), np.array(P), [540, 2.5, 2])
print fitParams
print fitCovariances
for i in range(0, len(x_model)):
y_model.append(fitFunc(fitParams[0], x_model[i], fitParams[1], fitParams[2]))
ax = fig.add_subplot(2,3,n, axisbg='white')
ax.scatter(x,P)
ax.plot(x_model,y_model)
ax.set_xlim([0, 6])
ax.set_ylim([0, 600])
ax.set_xlabel(r'\Delta x')
ax.set_ylabel(r'P (\mu W)')
plt.tight_layout()
plt.show()
我真的找不到我做错了什么。我希望你们能帮助我。谢谢:)
注意:您可以下载数据文件here来尝试使用相同数据的脚本。
【问题讨论】:
-
显示脚本打印的输出。特别是,您从
fitCovariances得到什么? -
我已将其添加到问题中。
fitCovariances都是无限的,这对我来说似乎很奇怪。 -
你确定
fitFunc中的这个变量顺序没问题吗?help(curve_fit)告诉我The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.。
标签: python numpy matplotlib scipy curve-fitting