线性回归过度拟合

时间:2017-03-27 11:40:58

标签: pandas scikit-learn

我正在修读关于线性回归课程的课程2(https://www.coursera.org/specializations/machine-learning

我已经使用graphlab解决了这个问题,但是想尝试一下sklearn来体验和学习。我正在使用sklearn和pandas。

模型过度拟合数据。我怎样才能解决这个问题?这是代码。

这些是我得到的系数。

[-3.33628603e-13 1.00000000e + 00]

poly1_data = polynomial_dataframe(sales["sqft_living"], 1)
poly1_data["price"] = sales["price"]
model1 = LinearRegression()
model1.fit(poly1_data, sales["price"])
print(model1.coef_)
plt.plot(poly1_data['power_1'], poly1_data['price'], '.',poly1_data['power_1'], model1.predict(poly1_data),'-')
plt.show()

绘制的线条是这样的。如您所见,它连接每个数据点。 enter image description here 这是输入数据的图 enter image description here

1 个答案:

答案 0 :(得分:2)

我甚至不会称之为过度装备。我说你做的不是你认为你应该做的事情。特别是,您忘记在设计矩阵X中添加1列。例如:

# generate some univariate data
x = np.arange(100)
y = 2*x + x*np.random.normal(0,1,100)
df = pd.DataFrame([x,y]).T
df.columns = ['x','y']

您正在执行以下操作:

model1 = LinearRegression()
X = df["x"].values.reshape(1,-1)[0]  # reshaping data
y = df["y"].values.reshape(1,-1)[0]
model1.fit(X,y)

导致:

plt.plot(df['x'].values, df['y'].values,'.')
plt.plot(X[0], model1.predict(X)[0],'-')
plt.show()

enter image description here

相反,您想要在设计矩阵(X)中添加1列的列:

X = np.column_stack([np.ones(len(df['x'])),df["x"].values.reshape(1,-1)[0]])
y = df["y"].values.reshape(1,-1)
model1.fit(X,y)

并且(经过一些重塑)你得到:

plt.plot(df['x'].values, df['y'].values,'.')
plt.plot(df['x'].values, model1.predict(X),'-')
plt.show()

enter image description here

相关问题