python多项式回归预测波士顿房价
时间: 2023-08-31 16:12:55 浏览: 100
好的,首先我们需要准备数据集。波士顿房价数据集可以在sklearn中直接导入,代码如下:
``` python
from sklearn.datasets import load_boston
import pandas as pd
boston = load_boston()
data = pd.DataFrame(boston.data, columns=boston.feature_names)
data['PRICE'] = boston.target
```
接下来,我们需要对数据进行预处理,包括将数据集分为训练集和测试集,以及进行归一化处理。代码如下:
``` python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
sc_X = StandardScaler()
sc_y = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
y_train = sc_y.fit_transform(y_train.reshape(-1, 1)).reshape(-1)
y_test = sc_y.transform(y_test.reshape(-1, 1)).reshape(-1)
```
接下来,我们可以使用多项式回归模型对数据进行拟合和预测。代码如下:
``` python
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=2)
X_poly_train = poly_reg.fit_transform(X_train)
X_poly_test = poly_reg.transform(X_test)
lin_reg = LinearRegression()
lin_reg.fit(X_poly_train, y_train)
y_pred = lin_reg.predict(X_poly_test)
```
最后,我们可以使用RMSE指标来评估模型的性能。代码如下:
``` python
from sklearn.metrics import mean_squared_error
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print('RMSE:', rmse)
```
完整代码如下:
``` python
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
boston = load_boston()
data = pd.DataFrame(boston.data, columns=boston.feature_names)
data['PRICE'] = boston.target
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
sc_X = StandardScaler()
sc_y = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
y_train = sc_y.fit_transform(y_train.reshape(-1, 1)).reshape(-1)
y_test = sc_y.transform(y_test.reshape(-1, 1)).reshape(-1)
poly_reg = PolynomialFeatures(degree=2)
X_poly_train = poly_reg.fit_transform(X_train)
X_poly_test = poly_reg.transform(X_test)
lin_reg = LinearRegression()
lin_reg.fit(X_poly_train, y_train)
y_pred = lin_reg.predict(X_poly_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print('RMSE:', rmse)
```
阅读全文