GRU模型交通量预测实例及代码
时间: 2024-01-26 21:01:43 浏览: 142
基于Python的交通流模拟预测案例
以下是一个基于GRU模型的交通量预测实例和代码,使用的是Python和TensorFlow:
数据集:METR-LA数据集,包含在UCLA的Github上。
步骤1:导入必要的库
``` python
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
```
步骤2:读取数据集并进行预处理
``` python
# 读取数据集
df = pd.read_csv('data/METR-LA.csv')
# 选取需要用到的列
cols = ['speed', 'time', 'weekday', 'hour']
df = df[cols]
# 对时间进行处理
df['time'] = pd.to_datetime(df['time'], format='%Y-%m-%d %H:%M:%S')
df['weekday'] = df['time'].dt.weekday
df['hour'] = df['time'].dt.hour
# 对速度进行归一化
scaler = MinMaxScaler()
df['speed'] = scaler.fit_transform(df['speed'].values.reshape(-1, 1))
# 将数据集分为训练集和测试集
train_size = int(len(df) * 0.8)
train_df = df[:train_size]
test_df = df[train_size:]
```
步骤3:定义模型并进行训练
``` python
# 定义超参数
BATCH_SIZE = 64
BUFFER_SIZE = 10000
EPOCHS = 10
STEPS_PER_EPOCH = 200
# 定义训练集和测试集
train_data = tf.data.Dataset.from_tensor_slices((train_df[['speed', 'weekday', 'hour']].values, train_df['speed'].values))
train_data = train_data.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()
test_data = tf.data.Dataset.from_tensor_slices((test_df[['speed', 'weekday', 'hour']].values, test_df['speed'].values))
test_data = test_data.batch(BATCH_SIZE).repeat()
# 定义模型
model = tf.keras.models.Sequential([
tf.keras.layers.GRU(64, input_shape=(None, 3)),
tf.keras.layers.Dense(1)
])
# 编译模型
model.compile(optimizer='adam', loss='mse')
# 训练模型
model.fit(train_data, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH)
```
步骤4:进行预测并计算误差
``` python
# 进行预测
y_pred = model.predict(test_data)
# 对速度进行反归一化
y_pred = scaler.inverse_transform(y_pred)
y_true = test_df['speed'].values.reshape(-1, 1)
y_true = scaler.inverse_transform(y_true)
# 计算误差
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
print(f'RMSE: {rmse:.2f}')
```
这样就完成了基于GRU模型的交通量预测实例和代码。
阅读全文