拟合实验数据,得到2个参数



我正试图将一个混乱的表达式与一些实验数据相匹配。该公式有两个自由参数(在代码中用"a"one_answers"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为两个具有自旋和能量的数组,由数据文件中的第一列和第二列表示。此处的完整输入数据

我想知道我的试衣程序出了什么问题,以及如何解决这个问题。

您遇到的问题是使用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()

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

最新更新