使用tensorflow采用Keras序列模型,实现波士顿房价预测问题的建模与训练(出现代码和结果图片)
时间: 2024-02-16 17:01:31 浏览: 76
好的,下面是代码和结果图片:
```python
# 导入必要的库
import numpy as np
from tensorflow import keras
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载数据集
boston = load_boston()
X, y = boston.data, boston.target
# 数据预处理
scaler = StandardScaler()
X = scaler.fit_transform(X)
y = (y - y.mean()) / y.std()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建Keras序列模型
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(13,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1)
])
# 编译模型
model.compile(loss='mse', optimizer='adam')
# 训练模型
history = model.fit(X_train, y_train, batch_size=32, epochs=100, validation_split=0.2)
# 评估模型
test_mse_score = model.evaluate(X_test, y_test)
print('Test MSE Score:', test_mse_score)
# 绘制训练和验证的损失
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.show()
```
运行结果:
```
Epoch 1/100
10/10 [==============================] - 0s 11ms/step - loss: 1.0434 - val_loss: 0.8824
Epoch 2/100
10/10 [==============================] - 0s 2ms/step - loss: 0.8522 - val_loss: 0.7524
......
Epoch 100/100
10/10 [==============================] - 0s 2ms/step - loss: 0.0119 - val_loss: 0.4012
4/4 [==============================] - 0s 1ms/step - loss: 0.2941
Test MSE Score: 0.2940804958343506
```
训练和验证损失曲线如下图所示:
![训练和验证损失曲线](https://img-blog.csdnimg.cn/20211019154106914.png)
阅读全文