我正在尝试f(x) = ?为一组随机的x,y坐标找到最佳拟合线。
具有多项式特征的线性回归适用于大约 10 种不同的多项式,但超过 10 的 r 平方实际上开始下降!
如果新特征对线性回归没有用,我会假设它们的系数为 0,因此添加特征不应损害整体 r 平方。
在创建大量交互特征时,我在房价预测时重现了这个问题。
我的python代码如下:
创建随机数据
import numpy as np
import matplotlib.pyplot as plt
def pol(x):
return x * np.cos(x)
x = np.linspace(0, 12, 100)
rng = np.random.RandomState(1234)
rng.shuffle(x)
x = np.sort(x[:25])
y = pol(x) + np.random.randn(25)*2
plt.scatter(x, y, color='green', s=50, marker='.')
plt.show()
回归并检查每个 R 平方
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
for p in range(1,30):
plot_range = [i/10 for i in range(0,120)]
poly = PolynomialFeatures(p)
X_fin = poly.fit_transform([[samp] for samp in x])
X_fin_plot = poly.fit_transform([[samp] for samp in plot_range])
reg = LinearRegression().fit(X_fin, y)
from sklearn.metrics import mean_squared_error, r2_score
print(p,r2_score(y, reg.predict(X_fin)))
显示最后的回归线
plt.scatter(x, y, color='green', s=50, marker='.')
plt.plot(plot_range,reg.predict(X_fin_plot))
plt.show()


