【问题标题】:Scipy Curve_fit function uses initial guess values instead of actually fittingScipy Curve_fit 函数使用初始猜测值而不是实际拟合
【发布时间】: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


【解决方案1】:

您唯一的问题是fitFunc 的定义。来自help(curve_fit)

Parameters
----------
f : callable
    The model function, f(x, ...).  It must take the independent
    variable as the first argument and the parameters to fit as
    separate remaining arguments.

这意味着您必须移动 x 输入以成为函数的第一个参数。这只会影响 2 行:您对 fitFunc 的定义,

#def fitFunc(P_max, x, x_0, w_z): #original
def fitFunc(x, P_max, 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))

以及在绘图时对fitFunc 的显式调用:

for i in range(0, len(x_model)):
    y_model.append(fitFunc(x_model[i], fitParams[0], fitParams[1], fitParams[2]))

结果:

我认为你和 scipy 都做得很好:)

效率说明:

我看不出您的 fitFunc 不能与向量值 x 输入一起使用的原因(确实如此)。这意味着您可以在绘制拟合模型时跳过i 的循环,您可以说

 y_model = fitFunc(x_model, fitParams[0], fitParams[1], fitParams[2])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2017-04-11
    • 1970-01-01
    • 2014-02-04
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多