python多项式回归预测波士顿房价 可视化
时间: 2023-11-09 21:02:04 浏览: 117
好的,以下是代码实现和可视化的步骤:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = load_boston()
X = boston.data[:, 5].reshape(-1, 1) # 只使用房间数量这个特征
y = boston.target.reshape(-1, 1)
# 多项式回归预处理
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
# 拟合模型
model = LinearRegression()
model.fit(X_poly, y)
# 预测结果
y_pred = model.predict(X_poly)
# 计算均方误差
mse = mean_squared_error(y, y_pred)
print("Mean Squared Error:", mse)
# 可视化结果
plt.scatter(X, y, s=10)
plt.plot(X, y_pred, color='r')
plt.show()
```
阅读全文