参数为PTRATIO,RAD,ZN,CRIM写一个波士顿房价预测神经网络python代码并将数据可视化
时间: 2024-05-16 10:14:35 浏览: 104
好的,我可以帮你写一个简单的基于多层感知器(MLP)的波士顿房价预测神经网络python代码。首先需要导入必要的库和数据集:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
# 加载波士顿房价数据集
boston = load_boston()
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
```
接下来,我们选择使用的特征和标签,将数据集进行划分和标准化处理:
```python
# 选择特征和标签
X = boston_df[['PTRATIO', 'RAD', 'ZN', 'CRIM']]
y = boston_df['PRICE']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 对特征进行标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
然后,我们可以使用MLPRegressor模型来训练神经网络并进行预测:
```python
# 创建并训练MLP模型
mlp = MLPRegressor(hidden_layer_sizes=(100, 50), activation='relu', solver='adam', max_iter=1000, verbose=False)
mlp.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = mlp.predict(X_test)
```
最后,我们可以将预测结果与真实值进行可视化比较:
```python
# 绘制预测结果和真实值的散点图
plt.scatter(y_test, y_pred)
plt.plot([0, 50], [0, 50], '--k')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.show()
```
完整代码如下所示:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
# 加载波士顿房价数据集
boston = load_boston()
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
# 选择特征和标签
X = boston_df[['PTRATIO', 'RAD', 'ZN', 'CRIM']]
y = boston_df['PRICE']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 对特征进行标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 创建并训练MLP模型
mlp = MLPRegressor(hidden_layer_sizes=(100, 50), activation='relu', solver='adam', max_iter=1000, verbose=False)
mlp.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = mlp.predict(X_test)
# 绘制预测结果和真实值的散点图
plt.scatter(y_test, y_pred)
plt.plot([0, 50], [0, 50], '--k')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.show()
```
希望这个代码对你有帮助!
阅读全文