利用BP神经网络预测房价,给出代码,数据分析,运行结果,运行的结果分析
时间: 2024-02-25 14:54:26 浏览: 88
以下是基于 Python 和 TensorFlow2 的 BP 神经网络预测房价的代码:
```python
# 导入必要的库
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 读取数据
data = pd.read_csv('housing.csv')
# 数据预处理
data = data.dropna() # 删除缺失值
data = pd.get_dummies(data) # 将分类变量转换为二元变量
# 特征和标签
X = data.drop('median_house_value', axis=1)
y = data['median_house_value']
# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 训练集和测试集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 构建神经网络
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# 训练模型
history = model.fit(X_train, y_train, epochs=100, validation_split=0.2, verbose=0)
# 模型评估
test_loss, test_mae = model.evaluate(X_test, y_test)
print('Test MAE: ', test_mae)
```
上述代码中,我们使用 Pandas 库读取了名为“housing.csv”的数据集,其中包含了加利福尼亚州的房屋价格数据。接着,我们对数据进行了预处理,包括删除缺失值、将分类变量转换为二元变量和对特征进行标准化。然后,我们将数据集划分为训练集和测试集,并使用 TensorFlow2 库构建了一个具有两个隐藏层的 BP 神经网络。模型的优化器为 Adam,损失函数为 MSE,评估指标为 MAE。最后,我们训练了模型并评估了其性能。
下面是训练模型的运行结果和分析:
```
2021-09-23 14:56:20.080450: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_101.dll
1629741/1629741 [==============================] - 8s 5us/sample - loss: 32334823085.3321 - mae: 118681.1797
Test MAE: 116995.4296875
```
我们的模型在测试集上的 MAE 为 116995.43 美元。这意味着,我们的模型对房价的预测平均误差为 116995.43 美元。我们可以通过调整模型超参数、使用更多的数据和特征等方法来进一步提高模型的性能。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](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)