如何使用“scipy.optimize.curve\u fit曲线拟合"?

2024-04-20 12:06:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我真希望有一条平滑的曲线。有人能解释一下我做错了什么吗?你知道吗


Tags: importasnpfigpltscipyaxfloat
1条回答
网友
1楼 · 发布于 2024-04-20 12:06:15

您只绘制与通话中原始数据相同的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

相关问题 更多 >