使用 curve_fit 拟合列表中 2 个变量的数据

Use of curve_fit to fit data of 2 variables in a list

我是 scipy 和 curve_fit 的新手。

我有 2 个列表:

x 个值:

[0.723938224, 0.965250965, 1.206563707, 1.447876448, 1.689189189, 
1.930501931, 2.171814672]

y 值:

[2.758, 2.443, 2.142333333, 1.911, 1.817666667, 1.688333333, 1.616]

我想对这 2 个数据集执行 curve_fit,但我似乎无法弄清楚它们之间的关系。我大致知道将它们放在一起的方程式:

我知道有一个方程式可以将它们组合在一起:

0.74/((9.81*(x/100))^(1/2))

但是我如何通过 python 曲线拟合来证明方程就是上面的方程。如果我在 excel 中做类似的事情,它会自动给我方程式。它在 python 中如何运作?

我不确定如何执行 curve_fit 和绘制趋势线。有人可以帮忙吗?谢谢。

首先,让我们定义曲线拟合函数。你说 Excel 告诉你函数的形式是 a/(b*(x/c)**d)。我告诉你,Excel 除了自动填充,什么都不会;这个等式很容易转化为((a*c**d)/b)/x**d,所以我们实际要考虑的函数是a/x**b的形式。 现在到实际的 curve fitting with scipy:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

x = [0.723938224, 0.965250965, 1.206563707, 1.447876448, 1.689189189, 1.930501931, 2.171814672]
y = [2.758, 2.443, 2.142333333, 1.911, 1.817666667, 1.688333333, 1.616]

def func(x, a, b):
    return a/(x**b)

#start values, not really necessary here but good to know the concept
p0 = [2, 0.5]
#the actual curve fitting, returns the parameters in popt and the covariance matrix in pcov
popt, pcov = curve_fit(func, np.asarray(x), np.asarray(y), p0)
#print out the parameters a, b
print(*popt)
#a=2.357411406488454, b=0.5027391574181408

#plot the function to see, if the fit is any good
#first the raw data
plt.scatter(x, y, marker="x", color="red", label="raw data")
#then the fitted curve
x_fit = np.linspace(0.9*min(x), 1.1*max(x), 1000)
y_fit = func(x_fit, *popt)
plt.plot(x_fit, y_fit, color="blue", label="fitted data")

plt.legend()
plt.show()

输出:

我觉得不错。如果你问我,不应该让 Excel 靠近任何统计数据。