Python中如何调用库函数实现点集的最小二乘直线拟合?
有多个常用的Python科学计算库都提供了开箱即用的线性最小二乘拟合实现,以下是几种最简便的方案:
- 方案1:使用numpy内置的
polyfit函数(最贴合你期望的调用形式,无需额外安装依赖,numpy是绝大多数科学计算环境的默认预装库)
import numpy as np x = np.array([1, 2, 3, 4]) y = np.array([23, 31, 42, 43 ]) # deg=1表示拟合一次多项式(即直线),返回值第一个是斜率,第二个是截距 slope, intercept = np.polyfit(x, y, deg=1)
- 方案2:使用scipy的
linregress函数,除了斜率和截距外还会返回相关系数、p值、标准误差等统计量,适合需要做统计检验的场景
import numpy as np from scipy.stats import linregress x = np.array([1, 2, 3, 4]) y = np.array([23, 31, 42, 43 ]) res = linregress(x, y) slope = res.slope intercept = res.intercept
- 方案3:如果你的项目已经在使用scikit-learn框架,也可以用线性回归模块实现:
import numpy as np from sklearn.linear_model import LinearRegression x = np.array([1, 2, 3, 4]) y = np.array([23, 31, 42, 43 ]) # scikit-learn要求输入特征为二维数组,因此需要对x做维度调整 model = LinearRegression().fit(x.reshape(-1, 1), y) slope = model.coef_[0] intercept = model.intercept_
如果你不想引入额外依赖,也可以直接手写极简实现,核心逻辑如下:
import numpy as np def leastSquares(x, y): x_mean = x.mean() y_mean = y.mean() slope = ((x - x_mean) * (y - y_mean)).sum() / ((x - x_mean) ** 2).sum() intercept = y_mean - slope * x_mean return slope, intercept
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

