首页 > 解决方案 > 拟合实验数据并获得2个参数

问题描述

我正在尝试为一些实验数据拟合一个凌乱的表达式。该公式有 2 个自由参数(在由“a”和“b”表示的代码中),我需要找到 a 和 b 的值。我尝试使用 scipy 模块,但在编译curve_fit过程时不断出现错误。我试图找到有关该错误的内容,但找不到任何可以解决该问题的内容。

错误截图:

这里

请记住,我对 python 的体验不是很好(基本上我刚刚开始为这个拟合过程学习它)。如果可以使代码更容易,代码片段就在这里:

def fun1(x,a,b):
    result=tsd1(x,17,6.5,a,b)
    return result
params, extras = curve_fit(fun1,mydata.spin,mydata.energy)
print(params)

tsd1是另一个函数,它依赖于某个参数(tsd1 函数的完整表达式可以在这里看到),mydata是具有自旋和能量的 2 个数组,由数据文件中的第一列和第二列表示。完整的输入数据在这里

我想知道我的验配过程有什么问题以及如何解决这个问题。

标签: pythonscipycurve-fitting

解决方案


您遇到的问题是您使用math模块的函数(它们适用于标量)而不是numpy旨在适用于数组的函数。您的问题的简化版本(我懒得通过您声明的所有功能)将是:

from math import cos
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd

#works perfectly fine with the numpy arrays from the pandas data frame
def fun1(x, a, b, c, d):
    return a * np.cos(b * x / 1000 + c) + d

#this version doesn't work because math works only on scalars
#def fun1(x, a, b, c, d):
#    return a * cos(b * x / 1000 + c) + d

#read data from file you provided
mydata = pd.read_csv("test.txt", names = ["spin", "energy"])

#curve fit
params, extras = curve_fit(fun1,mydata.spin,mydata.energy)
print(params)

#generation of the fitting curve
x_fit = np.linspace(np.min(mydata.spin), np.max(mydata.spin), 1000)
y_fit = fun1(x_fit, *params)

#plotting of raw data and fit function
plt.plot(mydata.spin, mydata.energy, "ro", label = "data")
plt.plot(x_fit, y_fit, "b", label = "fit")
plt.legend()
plt.show()

因此,解决方案是在脚本中找到所有数学函数,如sin, cossqrt并将它们替换为它们的 numpy 等价物。幸运的是,它们通常是简单的np.sin等等。


推荐阅读