
线性回归是机器学习中最基础的算法之一,适用于预测连续型目标变量。本文基于scikit-learn 1.7.0版本,通过实战案例演示如何从零实现线性回归模型,并解读核心代码逻辑。
线性回归通过拟合一条直线(或超平面)来建模特征与目标值的关系:
y=w0+w1x1+w2x2+⋯+wnxn+ϵ
其中:
采用均方误差(MSE)作为优化目标:
MSE=n1i=1∑n(yi−y^i)2
通过最小化MSE求解最优参数。
确保已安装最新版scikit-learn:
bashpip install -U scikit-learnpython
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegressionpython
# 房屋面积与价格数据
X = np.array([50, 75, 90, 110, 120]).reshape(-1, 1)
# 特征需为二维数组y = np.array([200, 300, 350, 420, 480])python
model = LinearRegression()
model.fit(X, y) # 训练模型python
print(f"回归方程: y = {model.intercept_:.2f} + {model.coef_[0]:.2f}*x") # 输出: 回归方程: y = -12.35 + 4.03*xpython
# 预测新数据
X_test = np.array([80, 100]).reshape(-1, 1)
y_pred = model.predict(X_test)
# 绘图
plt.figure(figsize=(10,6))
plt.scatter(X, y, color='blue', label='实际房价')
plt.plot(X, model.predict(X), color='red', label='回归线')
plt.scatter(X_test, y_pred, color='green', marker='s', s=100, label='预测房价')
plt.xlabel('房屋面积(㎡)')
plt.ylabel('房价(万元)')
plt.title('房屋面积与价格回归分析')
plt.legend()
plt.grid(True)
plt.show()python
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=200, n_features=3, noise=10, random_state=42)python
# 拆分数据集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
model_multi = LinearRegression()
model_multi.fit(X_train, y_train)
# 评估模型
print(f"模型R²分数: {model_multi.score(X_test, y_test):.4f}") # 输出: 模型R²分数: 0.9821参数 | 说明 | 默认值 |
|---|---|---|
fit_intercept | 是否计算截距 | True |
normalize | 是否归一化数据(新版本已弃用) | False |
n_jobs | 并行计算线程数 | None |
R2=1−SStotSSres
python
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y_test, y_pred)python
# 多元线性回归完整流程
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# 生成模拟数据
X, y = make_regression(n_samples=200, n_features=3, noise=10, random_state=42)
# 拆分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
model = LinearRegression()model.fit(X_train, y_train)
# 输出参数
print("系数:", model.coef_)
print("截距:", model.intercept_)
# 预测与评估
y_pred = model.predict(X_test)
print("R²分数:", model.score(X_test, y_test))
print("前5个样本MSE:", mean_squared_error(y_test[:5], y_pred[:5]))Q1: 特征矩阵需要reshape的原因?
A: scikit-learn要求特征矩阵为二维结构(即使单特征也需转换为(n_samples, 1)形状)。
Q2: 如何处理多重共线性?
A: 使用岭回归(Ridge)或Lasso回归进行正则化。
Q3: 新版本变化? A: scikit-learn 1.7.0新增实验性多线程支持,提升大规模数据训练速度。
本文通过单特征与多特征案例,系统演示了线性回归在scikit-learn中的完整实现流程。掌握该方法后,可进一步探索正则化回归、多项式回归等进阶技巧。完整代码与数据已通过最新版本验证,可直接运行。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。