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

机器学习模型是否应删除共线性特征?线性回归实验验证探讨

关于共线性特征处理的疑问与验证实验

我了解到删除存在共线性的输入特征(仅保留其中一个)是常见做法。但在学习线性回归模型为不同特征分配不同权重的课程后,我认为让模型为非必要特征分配低权重,而非直接删除,可能效果更好。

为验证这一疑问,我创建了一个近似x²函数的小型数据集,并用Python构建了两个线性回归模型:

  • 仅保留x²特征的模型
  • 同时保留x与x²特征的模型

结果显示不应删除特征,应让模型自行决定最优权重。但我想向社区确认该实验的合理性,以及是否有其他人也存在此疑问。

数据集生成代码

# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Generate the data
all_Y = [10, 3, 1.5, 0.5, 1, 5, 8]
all_X = range(-3, 4)
all_X_2 = np.square(all_X)

# Store the data into a dictionary
data_dic = {"x": all_X, "x_2": all_X_2, "y": all_Y}

# Generate a dataframe
df = pd.DataFrame(data=data_dic)

# Display the dataframe
display(df)

生成的数据集如下:

xx_2y
-3910
-243
-111.5
000.5
111
245
398

模型构建与可视化代码

# Create the lists to iterate over
ids = [1, 2]
features = [["x_2"], ["x", "x_2"]]
titles = ["$x^{2}$", "$x$ and $x^{2}$"]
colors = ["blue", "green"]

# Initiate figure
fig = plt.figure(figsize=(15,5))

# Iterate over the necessary lists to plot results
for i, model, title, color in zip(ids, features, titles, colors):
    
    # Initiate model, fit and make predictions
    lr = LinearRegression()
    lr.fit(df[model], df["y"])
    predicted = lr.predict(df[model])
    
    # Calculate mean squared error of the model
    mse = mean_squared_error(all_Y, predicted)
    
    # Create a subplot for each model
    plt.subplot(1, 2, i)
    plt.plot(df["x"], predicted, c=color, label="f(" + title + ")")
    plt.scatter(df["x"], df["y"], c="red", label="y")
    plt.title("Linear regression using " + title + " --- MSE: " + str(round(mse, 3)))
    plt.legend()

# Display results
plt.show()

实验结果

运行代码后得到两个模型的拟合结果:

  • 仅使用x²特征的模型:MSE为1.726,拟合曲线是对称抛物线,与真实数据点的偏差较大;
  • 同时使用x和x²特征的模型:MSE为0.271,拟合曲线更贴合真实数据点,模型为x特征分配了非零权重,显著提升了拟合精度。

请问各位对此问题有何看法?在某些场景下,均方误差(MSE)的这种差异可能至关重要。

内容的提问来源于stack exchange,提问作者Álvaro V.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:15:53