使用 np.polyfit

我们创建一个数据集,然后我们用直线$ f(x)= mx + c $拟合。

npoints = 20
slope = 2
offset = 3
x = np.arange(npoints)
y = slope * x + offset + np.random.normal(size=npoints)
p = np.polyfit(x,y,1)           # Last argument is degree of polynomial

看看我们做了什么:

import matplotlib.pyplot as plt
f = np.poly1d(p)                # So we can call f(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
plt.plot(x, y, 'bo', label="Data")
plt.plot(x,f(x), 'b-',label="Polyfit")
plt.show()

注意:此示例非常接近 https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html 上的 numpy 文档。