gru模型交通量预测MAE代码
时间: 2023-06-25 08:06:46 浏览: 75
以下是一个简单的GRU模型交通量预测的MAE代码示例,供参考:
```python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, GRU
# 读取数据
data = pd.read_csv('traffic_volume.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
data['scaled_traffic_volume'] = scaler.fit_transform(data[['traffic_volume']])
train_size = int(len(data) * 0.8)
train_data = data.iloc[:train_size,:]
test_data = data.iloc[train_size:,:]
# 准备数据
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
v = X.iloc[i:(i + time_steps)].values
Xs.append(v)
ys.append(y.iloc[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 24
X_train, y_train = create_dataset(train_data[['scaled_traffic_volume']],
train_data['scaled_traffic_volume'],
time_steps)
X_test, y_test = create_dataset(test_data[['scaled_traffic_volume']],
test_data['scaled_traffic_volume'],
time_steps)
# 建立GRU模型
model = Sequential()
model.add(GRU(32, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mae')
# 训练模型
model.fit(X_train, y_train, epochs=50, batch_size=16, validation_split=0.1, shuffle=False)
# 预测
y_pred = model.predict(X_test)
# 反向缩放结果
y_pred_inv = scaler.inverse_transform(y_pred.reshape(-1, 1))
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
# 计算MAE
mae = np.mean(np.abs(y_pred_inv - y_test_inv))
print('MAE:', mae)
```
其中,`traffic_volume.csv` 是包含交通量数据的csv文件。在这个示例代码中,我们使用了一个包含一个GRU层和一个全连接层的简单模型,使用MAE作为损失函数进行训练和评估。最后,我们使用反向缩放将预测结果转换回原始单位并计算MAE。
阅读全文