最小二乘法是一种用于拟合数据的线性回归技术,它通过最小化残差平方和来找到最佳拟合线。通常用于估计线性关系,但也可以扩展到多元回归和非线性关系中。Python 提供了多种方式来实现最小二乘法,包括使用 NumPy
、SciPy
和 scikit-learn
。
案例分析:使用 NumPy 实现最小二乘法
我们可以使用 NumPy
的线性代数功能 np.linalg.lstsq()
来直接求解线性方程组。这个函数使用最小二乘法求解线性方程 y=β0+β1x。
Python 实现:
import numpy as np
import matplotlib.pyplot as plt
# 生成示例数据
np.random.seed(0)
X = 2.5 * np.random.randn(100) + 1.5 # 生成100个随机数作为X
Y = 2 * X + np.random.randn(100) * 0.5 + 0.8 # 生成Y
# 将数据转换为矩阵形式
X_mat = np.vstack([X, np.ones(len(X))]).T
# 使用 NumPy 的 lstsq 求解最小二乘法方程
coefficients, residuals, rank, s = np.linalg.lstsq(X_mat, Y, rcond=None)
slope, intercept = coefficients
# 打印回归系数
print(f"Intercept: {intercept:.3f}")
print(f"Slope: {slope:.3f}")
# 绘制结果
plt.scatter(X, Y, label='Data points')
plt.plot(X, slope * X + intercept, color='red', label='Fitted line')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Linear Regression using Least Squares")
plt.legend()
plt.show()
案例分析:使用 SciPy 实现最小二乘法
SciPy
提供了 scipy.optimize.curve_fit
函数来拟合非线性模型。我们可以定义线性模型,然后使用该函数进行拟合。
Python 实现:
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
# 生成示例数据
np.random.seed(0)
X = 2.5 * np.random.randn(100) + 1.5
Y = 2 * X + np.random.randn(100) * 0.5 + 0.8
# 定义线性模型
def linear_model(x, a, b):
return a * x + b
# 使用 curve_fit 进行拟合
params, covariance = curve_fit(linear_model, X, Y)
slope, intercept = params
# 打印回归系数
print(f"Intercept: {intercept:.3f}")
print(f"Slope: {slope:.3f}")
# 绘制结果
plt.scatter(X, Y, label='Data points')
plt.plot(X, slope * X + intercept, color='red', label='Fitted line')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Linear Regression using SciPy")
plt.legend()
plt.show()