GRU模型交通量预测实例及代码
时间: 2023-06-25 08:02:03 浏览: 76
以下是使用GRU模型进行交通量预测的示例代码。本示例使用的是Python和Keras库。
首先,导入所需的库:
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, GRU
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
```
接着,读取并处理数据,将其转换为适合输入模型的形式:
```python
# 读取数据
data = pd.read_csv('traffic_volume.csv')
# 将时间列转换为日期时间格式
data['date_time'] = pd.to_datetime(data['date_time'])
# 将日期时间列设置为索引
data.set_index('date_time', inplace=True)
# 只保留流量列
data = data[['traffic_volume']]
# 将数据划分为训练集和测试集
train_size = int(len(data) * 0.7)
train = data.iloc[:train_size, :]
test = data.iloc[train_size:, :]
# 对训练集和测试集进行缩放
scaler = MinMaxScaler()
train_scaled = scaler.fit_transform(train)
test_scaled = scaler.transform(test)
# 将数据转换为3D数组(样本数,时间步数,特征数)
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X[i:i + time_steps])
ys.append(y[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 24
X_train, y_train = create_dataset(train_scaled, train_scaled[:, 0], time_steps)
X_test, y_test = create_dataset(test_scaled, test_scaled[:, 0], time_steps)
```
然后,创建GRU模型并进行训练:
```python
model = Sequential()
model.add(GRU(64, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=16,
validation_split=0.1,
verbose=1,
shuffle=False
)
```
最后,使用测试集进行预测,并将结果可视化:
```python
y_pred = model.predict(X_test)
# 反向缩放预测值和实际值
y_pred_inv = scaler.inverse_transform(y_pred)
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
# 绘制预测结果和实际值的图表
plt.plot(y_test_inv, label='Actual')
plt.plot(y_pred_inv, label='Predicted')
plt.xlabel('Time')
plt.ylabel('Traffic Volume')
plt.legend()
plt.show()
```
完整代码如下所示:
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, GRU
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('traffic_volume.csv')
# 将时间列转换为日期时间格式
data['date_time'] = pd.to_datetime(data['date_time'])
# 将日期时间列设置为索引
data.set_index('date_time', inplace=True)
# 只保留流量列
data = data[['traffic_volume']]
# 将数据划分为训练集和测试集
train_size = int(len(data) * 0.7)
train = data.iloc[:train_size, :]
test = data.iloc[train_size:, :]
# 对训练集和测试集进行缩放
scaler = MinMaxScaler()
train_scaled = scaler.fit_transform(train)
test_scaled = scaler.transform(test)
# 将数据转换为3D数组(样本数,时间步数,特征数)
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X[i:i + time_steps])
ys.append(y[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 24
X_train, y_train = create_dataset(train_scaled, train_scaled[:, 0], time_steps)
X_test, y_test = create_dataset(test_scaled, test_scaled[:, 0], time_steps)
# 创建GRU模型并进行训练
model = Sequential()
model.add(GRU(64, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=16,
validation_split=0.1,
verbose=1,
shuffle=False
)
# 使用测试集进行预测,并将结果可视化
y_pred = model.predict(X_test)
# 反向缩放预测值和实际值
y_pred_inv = scaler.inverse_transform(y_pred)
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
# 绘制预测结果和实际值的图表
plt.plot(y_test_inv, label='Actual')
plt.plot(y_pred_inv, label='Predicted')
plt.xlabel('Time')
plt.ylabel('Traffic Volume')
plt.legend()
plt.show()
```
阅读全文