机器学习模型是否应删除共线性特征?线性回归实验验证探讨
关于共线性特征处理的疑问与验证实验
我了解到删除存在共线性的输入特征(仅保留其中一个)是常见做法。但在学习线性回归模型为不同特征分配不同权重的课程后,我认为让模型为非必要特征分配低权重,而非直接删除,可能效果更好。
为验证这一疑问,我创建了一个近似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)
生成的数据集如下:
| x | x_2 | y |
|---|---|---|
| -3 | 9 | 10 |
| -2 | 4 | 3 |
| -1 | 1 | 1.5 |
| 0 | 0 | 0.5 |
| 1 | 1 | 1 |
| 2 | 4 | 5 |
| 3 | 9 | 8 |
模型构建与可视化代码
# 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.
相关产品推荐
相关产品推荐

