GRU模型交通量预测实例及代码
时间: 2023-06-24 07:05:59 浏览: 92
以下是使用GRU模型进行交通量预测的代码示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, GRU
from keras.optimizers import Adam
# 读取数据
data = pd.read_csv('traffic_volume.csv')
# 选择特征列
feature_cols = ['temp', 'rain_1h', 'snow_1h', 'clouds_all', 'weather_main', 'holiday', 'weekday', 'hour']
# 分离训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data.iloc[:train_size]
test_data = data.iloc[train_size:]
# 对特征进行归一化处理
scaler = MinMaxScaler()
train_data[feature_cols] = scaler.fit_transform(train_data[feature_cols])
test_data[feature_cols] = scaler.transform(test_data[feature_cols])
# 构建特征序列
def create_sequences(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
time_steps = 24
X_train, y_train = create_sequences(train_data[feature_cols], train_data['traffic_volume'], time_steps)
X_test, y_test = create_sequences(test_data[feature_cols], test_data['traffic_volume'], time_steps)
# 构建GRU模型
model = Sequential()
model.add(GRU(units=64, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
# 训练模型
history = model.fit(X_train, y_train, epochs=50, batch_size=64, validation_split=0.1, shuffle=False)
# 绘制损失函数曲线
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='validation')
plt.legend()
plt.show()
# 预测测试集
y_pred = model.predict(X_test)
# 将预测结果反归一化
y_pred = scaler.inverse_transform(y_pred)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))
# 绘制预测结果与真实结果的对比图
plt.plot(y_test, label='true')
plt.plot(y_pred, label='predicted')
plt.legend()
plt.show()
```
代码中使用了一个名为`traffic_volume.csv`的数据集,其中包含多个特征和交通量的历史数据。在数据预处理阶段,对特征进行了归一化处理。接着,将归一化后的特征序列和交通量序列转换为训练集和测试集,然后使用`create_sequences`函数构建特征序列。接着,使用Keras构建了一个GRU模型,并使用Adam优化器和均方误差作为损失函数进行模型训练。最后,使用训练好的模型对测试集进行预测,并将预测结果反归一化,最终绘制了真实值和预测值的对比图表。
阅读全文