我试图将一个混乱的表达方式与一些实验数据相吻合。公式有两个空闲参数(在代码中以"a“和”b“表示),我需要找到a和b的值。我尝试使用but模块,但是在编译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是两个具有自旋和能量的数组,由数据文件中的第一列和第二列表示。全输入数据这里
我想知道我的拟合程序有什么问题,以及如何解决这个问题。
发布于 2018-07-29 17:26:03
您遇到的问题是,您使用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、cos、sqrt,并用它们的numpy等价物代替它们。幸运的是,它们通常只是简单的np.sin等等。
https://stackoverflow.com/questions/51581025
复制相似问题