python - 拟合实验数据并获得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 个数组,由数据文件中的第一列和第二列表示。完整的输入数据在这里
我想知道我的验配过程有什么问题以及如何解决这个问题。
解决方案
您遇到的问题是您使用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
等等。
推荐阅读
- authentication - 为什么我不能使用 Auth::id() 将登录的用户数据发送到 vue?
- python - Python视频分析——检测颜色变化和时间戳
- java - 从android中的加速度计读取后一行代码正在循环
- r - R:根据一个值设置PCA自动绘图的数据点大小
- kendo-ui - 当我登陆页面时,grid.hasChanges 总是返回 true
- python - 如何在 Excel 文件中使用带有 DataFrame 的 If 语句?
- git - 在多个过滤的提交中更改作者
- ios - SwiftUI:表达式类型不明确,没有更多上下文,在视图之间传递 ObservableObject 时
- html - 如何在输入按钮上使用 Material Design Lite
- php - PHP:如何在字符串中连接 foreach?