【发布时间】:2021-12-04 11:40:43
【问题描述】:
我想在 python 中曲线拟合一些数据。我的程序如下所示:
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
def lin(x, a, b,c):
return a*x+b
def exp(x, a, b, c):
return a*np.exp(b*x)+c
def ln(x, a, b, c):
return a*np.log(b+x)+c
x_dummy = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
y_dummy = np.array([9.2, 9.9, 10.0, 11.2, 10.2, 12.6, 10.0, 11.6, 12.2])
popt, _ = curve_fit(lin, x_dummy[:-2], y_dummy[:-1])
y_approx = lin(x_dummy, popt[0], popt[1], popt[2])
print(y_approx[-1])
print(popt)
print(mean_squared_error(y_dummy[:-1], y_approx[:-2]))
plt.plot(x_dummy[:-1], y_dummy, color='blue')
plt.plot(x_dummy, y_approx, color='green')
plt.show()
我现在的目标是一个通用函数,称为 fn,它可以有一些参数,例如从某种意义上说,作为字符串,调用
popt, _ = curve_fit(fn('lin' or 'exp' or 'ln'), x_dummy[:-2], y_dummy[:-1])
意思相同
popt, _ = curve_fit(lin or exp or ln, x_dummy[:-2], y_dummy[:-1])
背景:我想生成一些数组 = ['lin', 'exp', 'ln'] 并遍历所有三种可能的曲线拟合并计算再现平方误差的最小值。
【问题讨论】:
标签: python curve-fitting scipy-optimize