数据:shenzhen_housing.csv深圳房价预测并完成以下作业:Numpy数组数据;Pandas数据分析 ;Matplotlib可视化;sklearn机器学习算法;结果总结分析。写出代码
时间: 2023-11-22 07:54:17 浏览: 173
以下是解决这个问题的代码:
```python
# 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 读取数据
df = pd.read_csv('shenzhen_housing.csv')
print(df.head())
# 数据预处理
df.dropna(inplace=True) # 处理缺失值
df.drop_duplicates(inplace=True) # 处理重复值
# 特征工程
# 将区域、装修、朝向等分类变量转换成数值变量
df['region'] = pd.Categorical(df['region']).codes
df['decoration'] = pd.Categorical(df['decoration']).codes
df['orientation'] = pd.Categorical(df['orientation']).codes
# 划分数据集
X = df.drop('price', axis=1)
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建模型
model = LinearRegression()
model.fit(X_train, y_train)
# 预测结果
y_pred = model.predict(X_test)
# 评估模型
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print('RMSE:', rmse)
# 可视化结果
plt.scatter(y_test, y_pred)
plt.plot([0, 500], [0, 500], 'r')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.show()
```
说明:
- 首先,我们使用 Pandas 库读取深圳房价数据集,并使用 `head()` 方法查看前几行数据。
- 接下来,我们进行数据预处理,包括处理缺失值和重复值。
- 然后,我们进行特征工程,将分类变量转换成数值变量。
- 接着,我们使用 `train_test_split()` 方法将数据集划分为训练集和测试集。
- 然后,我们使用 `LinearRegression()` 方法构建线性回归模型,并使用训练集拟合该模型。
- 接着,我们使用训练好的模型对测试集进行预测,并计算预测结果与真实结果的均方误差(RMSE)。
- 最后,我们使用 Matplotlib 库可视化预测结果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)