keras波士顿房价预测可视化
时间: 2023-07-09 07:20:03 浏览: 188
下面是使用Keras库进行波士顿房价预测的可视化示例代码,其中包含了实际房价和预测房价之间的散点图和残差图:
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
# 加载波士顿房价数据集
boston = load_boston()
# 准备数据
X = boston.data
y = boston.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型
model = Sequential()
model.add(Dense(50, input_dim=X.shape[1], activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1))
# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_test, y_test))
# 对测试集进行预测
y_pred = model.predict(X_test)
# 绘制实际房价和预测房价之间的散点图
plt.scatter(y_test, y_pred)
plt.xlabel('Actual Prices')
plt.ylabel('Predicted Prices')
plt.title('Actual vs. Predicted Prices')
plt.show()
# 绘制残差图
residuals = y_test - y_pred.flatten()
plt.scatter(y_test, residuals)
plt.xlabel('Actual Prices')
plt.ylabel('Residuals')
plt.title('Residual Plot')
plt.show()
# 输出模型评估指标
print('MSE:', mean_squared_error(y_test, y_pred))
print('MAE:', mean_absolute_error(y_test, y_pred))
```
运行上述代码后,可以得到实际房价和预测房价之间的散点图和残差图,以及模型的评估指标。
阅读全文