采用Keras序列模型,实现波士顿房价预测问题的建模与训练
时间: 2024-02-13 21:03:23 浏览: 82
深度学习-基于Keras的Python项目开发实战_波士顿房价预测_编程案例实例教程.pdf
5星 · 资源好评率100%
好的,下面是使用Keras序列模型实现波士顿房价预测问题的建模与训练的步骤:
1. 导入必要的库和数据集
```python
import numpy as np
import pandas as pd
import tensorflow as tf
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
```
2. 数据预处理
```python
# 将数据集划分为训练集和测试集
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)
# 将标签转换为独热编码
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)
```
3. 建立模型
```python
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(2, activation='softmax')
])
```
4. 编译模型
```python
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
```
5. 训练模型
```python
history = model.fit(X_train, y_train,
epochs=100,
batch_size=32,
validation_data=(X_test, y_test))
```
6. 模型评估
```python
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
以上就是使用Keras序列模型实现波士顿房价预测问题的建模与训练的步骤。
阅读全文