python波士顿机器学习代码
时间: 2023-09-12 10:11:26 浏览: 57
以下是一个简单的波士顿房价预测的机器学习代码,使用了Python的Scikit-learn机器学习库:
```python
# 导入必要的库
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 加载波士顿房价数据集
boston = load_boston()
# 将数据集转化为DataFrame格式,方便处理
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
# 添加目标变量MEDV(房屋价格中位数)
boston_df['MEDV'] = boston.target
# 分割数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(boston_df[boston.feature_names], boston_df['MEDV'], test_size=0.2, random_state=42)
# 实例化线性回归模型并拟合训练集
lr = LinearRegression()
lr.fit(X_train, y_train)
# 使用模型进行预测
y_pred = lr.predict(X_test)
# 计算均方误差(MSE)和均方根误差(RMSE)
mse = mean_squared_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
print('均方误差:', mse)
print('均方根误差:', rmse)
```
以上代码将波士顿房价数据集加载到DataFrame中,分割数据集为训练集和测试集,实例化线性回归模型并拟合训练集,最后使用模型进行预测并计算均方误差和均方根误差。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)