You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scikit-learn Linear Regression预测逻辑疑问及计算异常排查

Scikit-learn LinearRegression 预测逻辑与手动计算异常原因解析

一、Scikit-learn LinearRegression 的核心预测机制

LinearRegression 的预测逻辑分两种情况,取决于是否设置拟合截距:

  • 默认模式(fit_intercept=True):模型会自动单独拟合一个截距项(intercept_),此时预测公式为:
    y_pred = 特征矩阵 @ coef_ + intercept_
    
    其中 coef_ 的长度等于原始特征的数量,intercept_ 是一个独立的标量值,不需要手动给特征矩阵添加全1的偏置列。
  • 无截距模式(fit_intercept=False):模型不会自动拟合截距,此时需要手动给特征矩阵添加全1的偏置列,预测公式变为:
    y_pred = 带偏置列的特征矩阵 @ coef_
    
    这时 coef_ 的长度等于原始特征数+1,包含了偏置列对应的系数。

二、你的手动计算异常原因

你手动给特征矩阵添加了偏置列,但没有修改模型的默认参数(fit_intercept=True),这会导致模型重复处理截距项:
模型会同时把你手动添加的全1列当作普通特征拟合系数,再额外拟合一个独立的 intercept_。这种冗余会破坏特征与系数的对应关系,导致系数计算出现异常偏移,最终出现预测值巧合等于里程特征的情况。

三、修正方案

方案1:使用默认截距拟合(推荐)

不需要手动添加偏置列,直接用原始特征矩阵训练:

import numpy as np
from sklearn.linear_model import LinearRegression

# 提取原始特征和因变量
X = dataFrame.drop(['Sell Price($)'], axis='columns').to_numpy()
y = dataFrame['Sell Price($)'].to_numpy()

# 初始化默认模型(fit_intercept=True)
model = LinearRegression()
model.fit(X, y)

# 手动计算预测值,与模型predict结果一致
y_pred_manual = X @ model.coef_ + model.intercept_
y_pred_model = model.predict(X)
print(np.allclose(y_pred_manual, y_pred_model))  # 输出True

方案2:手动添加偏置列并关闭自动截距拟合

如果一定要手动加偏置列,需设置 fit_intercept=False:

import numpy as np
from sklearn.linear_model import LinearRegression

# 手动添加偏置列
feature_matrix = dataFrame.drop(['Sell Price($)'], axis='columns').to_numpy()
bias_column = np.array([[1] for _ in range(len(feature_matrix))])
X_with_bias = np.concatenate([bias_column, feature_matrix], axis=1)
y = dataFrame['Sell Price($)'].to_numpy()

# 关闭自动截距拟合
model = LinearRegression(fit_intercept=False)
model.fit(X_with_bias, y)

# 手动计算预测值,与模型predict结果一致
y_pred_manual = X_with_bias @ model.coef_
y_pred_model = model.predict(X_with_bias)
print(np.allclose(y_pred_manual, y_pred_model))  # 输出True

内容的提问来源于stack exchange,提问作者Saptarshi Dey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:16:09