使用 np.linalg.lstsq

我们使用与 polyfit 相同的数据集:

npoints = 20
slope = 2
offset = 3
x = np.arange(npoints)
y = slope * x + offset + np.random.normal(size=npoints)

现在,我们试图通过最小化| cA b | ** 2 来最小化线性方程组 A b = c 来找到解决方案

import matplotlib.pyplot as plt # So we can plot the resulting fit
A = np.vstack([x,np.ones(npoints)]).T
m, c = np.linalg.lstsq(A, y)[0] # Don't care about residuals right now
fig = plt.figure()
ax  = fig.add_subplot(111)
plt.plot(x, y, 'bo', label="Data")
plt.plot(x, m*x+c, 'r--',label="Least Squares")
plt.show()

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