如何使用“scipy.optimize.curve_fit”顺利拟合我的数据点?

问题描述 投票:3回答:1

我想使用scipy.optimize.curve_fit来拟合一些数据点。不幸的是,我得到一个不稳定的适合,我不知道为什么。

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

M = np.array([730,910,1066,1088,1150], dtype=float)
V = np.array([95.71581923, 146.18564513, 164.46723727, 288.49796413, 370.98703941], dtype=float)

def func(x, a, b, c):
    return a * np.exp(b * x) + c

popt, pcov = curve_fit(func, M, V, [0,0,1], maxfev=100000000)
print(*popt)

fig, ax = plt.subplots()
fig.dpi = 80

ax.plot(M, V, 'go', label='data')
ax.plot(M, func(M, *popt), '-', label='fit')

plt.xlabel("M")
plt.ylabel("V")
plt.grid()
plt.legend()
plt.show()

enter image description here

我实际上期待某种平滑的曲线。有人可以解释我在这里做错了什么吗?

python scipy curve-fitting
1个回答
3
投票

您只是在呼叫中绘制与原始数据相同的x点:

ax.plot(M, V, 'go', label='data')
ax.plot(M, func(M, *popt), '-', label='fit')

要解决这个问题,您可以使用更广泛的范围 - 这里我们使用700到1200之间的所有值:

toplot = np.arange(700,1200)
ax.plot(toplot, func(toplot, *popt), '-', label='fit')

smooth

© www.soinside.com 2019 - 2024. All rights reserved.