基于python线性回归波士顿房价的代码
时间: 2023-09-23 20:03:29 浏览: 105
下面是基于Python实现的线性回归波士顿房价的代码:
```
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 加载数据
boston = load_boston()
x = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
# 划分数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
# 模型训练
model = LinearRegression()
model.fit(x_train, y_train)
# 模型预测
y_pred = model.predict(x_test)
# 模型评估
mse = mean_squared_error(y_test, y_pred)
print('均方误差:', mse)
```
在这个例子中,我们使用了sklearn库里的LinearRegression模型来训练回归模型,并使用均方误差(Mean Squared Error,MSE)来评估模型的预测效果。
阅读全文