我在使用 scipy 优化包拟合曲线时遇到了一些麻烦。我的代码是:import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fitdef Function_EXD_2(x, d, e): return d*np.exp(-x/e)x = np.array([135, 126, 120, 100, 90, 85, 80, 70, 65, 60])y = np.array([207, 263, 401, 460, 531, 576, 1350, 2317, 2340, 2834])popt, pcov = curve_fit(Function_EXD_2, x, y)print(popt, pcov)我得到 popt = [1,1],所以优化不起作用。我已经在 R 中完成了“相同”,我正在执行 popt = [44237.53, 22.21] aprox。有人可以帮我吗?
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
有两个问题:
功能定义
x 数组需要从
0
我已经翻转了您的数据值并为拟合算法添加了界限
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.array([135, 126, 120, 100, 90, 85, 80, 70, 65, 60])
y = np.array([207, 263, 401, 460, 531, 576, 1350, 2317, 2340, 2834])
# flip array values
x = x[::-1] - np.amin(x)
y = y[::-1]
# fit function
popt, pcov = curve_fit(func, x, y, bounds=(-10**6, 10**6))
# plot data
x_data = np.linspace(1, 80, 100)
plt.plot(x, y, '.')
plt.plot(x_data, func(x_data, popt[0], popt[1], popt[2]))
plt.show()
输出:
添加回答
举报
0/150
提交
取消