如何使用“scipy.optimize.curve_fit”获得数据点的平滑拟合?

4

我想使用 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

1个回答

5

在您的调用中,您只绘制了与原始数据相同的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


谢谢你的回答。我已经困惑了很长时间了。非常感谢! - rainman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接