我在 scipy.optimize 中查看了函数逼近方法并在阅读函数说明后发现(可能是错误的)它们仅近似于非线性函数。
例如,如果我在 x 和 y 的 zip() 函数之后输出样本
[(1,1),(4,2),(6,4),(8,6),(10,11)]
如您所见,非线性函数的近似值要好得多,但出于我的目的,我需要线性函数。
我承认可能在所提供的功能文档中遗漏了某些内容,因此如果问题可以以“阅读文档”的方式回答,我深表歉意。
请您参考如下方法:
除了 @user2589273 建议的 np.polyfit 和 scipy.stats.linregress 之外,进行线性回归的一种低级方法是求解矩阵使用 np.linalg.lstsq 的系数。虽然这种方法比使用其中一个预打包函数进行线性回归要多一些工作,但了解它在基本层面上的工作原理非常有用,尤其是当您开始处理多变量数据时。
例如:
import numpy as np
# a simple linear relationship: y = mx + c with m=0.5 and c=2
x = np.arange(50)
y = x * 0.5 + 2
y += np.random.randn(50) * 5 # add some noise
# we can rewrite the line equation as y = Ap, where A=[[x, 1]] and p=[[m], [c]]
A = np.c_[x, np.ones(50)]
# solving for p gives us the slope and intercept
p, residuals, rank, svals = np.linalg.lstsq(A, y)
绘制拟合:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(x, y, 'ob', label='data')
ax.plot(x, A.dot(p), '-k', lw=2, label='linear fit')
ax.legend()
