Bootstrap

LSTM+Transformer模型交通流量预测(Python代码,GRU/LSTM/CNN_LSTM作为对比模型

当使用LSTM和Transformer模型进行交通流量预测时,可以使用Python中的深度学习库例如TensorFlow或PyTorch来实现这些模型。下面是一个示例代码,其中包含LSTM、GRU和CNN-LSTM作为对比模型的实现。

首先,我们需要导入所需的库和模块:

python
复制
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Conv1D, MaxPooling1D, Flatten, Dropout, Transformer
接下来,我们可以定义一些辅助函数来准备数据和评估模型:

python
复制
def prepare_data(data, n_features):
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)

X, y = [], []
for i in range(len(data) - n_features - 1):
    X.append(scaled_data[i:(i + n_features)])
    y.append(scaled_data[i + n_features])
X, y = np.array(X), np.array(y)
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
return X, y, scaler

def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred = scaler.inverse_transform(y_pred)
y_test = scaler.inverse_transform(y_test)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
return rmse
接下来,我们可以加载数据集并进行预处理。假设我们有一个名为traffic_data.csv的CSV文件,其中包含交通流量数据。

python
复制

Load and preprocess the data

data = pd.read_csv(‘traffic_data.csv’)
data = data[‘traffic_volume’].values.reshape(-1, 1)

Split the data into train and test sets

train_data, test_data = train_test_split(data, test_size=0.2, shuffle=False)

Prepare the train and test data

n_features = 24 # Number of lag observations as features
X_train, y_train, scaler = prepare_data(train_data, n_features)
X_test, y_test, _ = prepare_data(test_data, n_features)
现在我们可以开始构建并训练模型了。首先是LSTM模型:

python
复制

Build and train the LSTM model

lstm_model = Sequential()
lstm_model.add(LSTM(50, activation=‘relu’, input_shape=(n_features, 1)))
lstm_model.add(Dense(1))
lstm_model.compile(optimizer=‘adam’, loss=‘mse’)
lstm_model.fit(X_train, y_train, epochs=50, batch_size=32)
接下来是GRU模型:

python
复制

Build and train the GRU model

gru_model = Sequential()
gru_model.add(GRU(50, activation=‘relu’, input_shape=(n_features, 1)))
gru_model.add(Dense(1))
gru_model.compile(optimizer=‘adam’, loss=‘mse’)
gru_model.fit(X_train, y_train, epochs=50, batch_size=32)
最后是CNN-LSTM模型:

python
复制

Build and train the CNN-LSTM model

cnn_lstm_model = Sequential()
cnn_lstm_model.add(Conv1D(filters=64, kernel_size=3, activation=‘relu’, input_shape=(n_features, 1)))
cnn_lstm_model.add(MaxPooling1D(pool_size=2))
cnn_lstm_model.add(Flatten())
cnn_lstm_model.add(LSTM(50, activation=‘relu’))
cnn_lstm_model.add(Dense(1))
cnn_lstm_model.compile(optimizer=‘adam’, loss=‘mse’)
cnn_lstm_model.fit(X_train, y_train, epochs=50, batch_size=32)
至此,我们已经完成了LSTM、GRU和CNN-LSTM模型的训练。可以使用这些模型进行预测并评估其性能:

python
复制

Evaluate the models

lstm_rmse = evaluate_model(lstm_model, X_test, y_test, scaler)
gru_rmse = evaluate_model(gru_model, X_test, y_test, scaler)
cnn_lstm_rmse = evaluate_model(cnn_lstm_model, X_test, y_test, scaler)

print(‘LSTM RMSE:’, lstm_rmse)
print(‘GRU RMSE:’, gru_rmse)
print('下面是一个完整的Python代码示例,展示了如何使用LSTM、GRU和CNN-LSTM作为对比模型来进行交通流量预测:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Conv1D, MaxPooling1D, Flatten, Dropout, Transformer

def prepare_data(data, n_features):
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data)

    X, y = [], []
    for i in range(len(data) - n_features - 1):
        X.append(scaled_data[i:(i + n_features)])
        y.append(scaled_data[i + n_features])
    X, y = np.array(X), np.array(y)
    X = np.reshape(X, (X.shape[0], X.shape[1], 1))
    return X, y, scaler

def evaluate_model(model, X_test, y_test, scaler):
    y_pred = model.predict(X_test)
    y_pred = scaler.inverse_transform(y_pred)
    y_test = scaler.inverse_transform(y_test)
    mse = mean_squared_error(y_test, y_pred)
    rmse = np.sqrt(mse)
    return rmse

# Load and preprocess the data
data = pd.read_csv('traffic_data.csv')
data = data['traffic_volume'].values.reshape(-1, 1)

# Split the data into train and test sets
train_data, test_data = train_test_split(data, test_size=0.2, shuffle=False)

# Prepare the train and test data
n_features = 24  # Number of lag observations as features
X_train, y_train, scaler = prepare_data(train_data, n_features)
X_test, y_test, _ = prepare_data(test_data, n_features)

# Build and train the LSTM model
lstm_model = Sequential()
lstm_model.add(LSTM(50, activation='relu', input_shape=(n_features, 1)))
lstm_model.add(Dense(1))
lstm_model.compile(optimizer='adam', loss='mse')
lstm_model.fit(X_train, y_train, epochs=50, batch_size=32)

# Build and train the GRU model
gru_model = Sequential()
gru_model.add(GRU(50, activation='relu', input_shape=(n_features, 1)))
gru_model.add(Dense(1))
gru_model.compile(optimizer='adam', loss='mse')
gru_model.fit(X_train, y_train, epochs=50, batch_size=32)

# Build and train the CNN-LSTM model
cnn_lstm_model = Sequential()
cnn_lstm_model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_features, 1)))
cnn_lstm_model.add(MaxPooling1D(pool_size=2))
cnn_lstm_model.add(Flatten())
cnn_lstm_model.add(LSTM(50, activation='relu'))
cnn_lstm_model.add(Dense(1))
cnn_lstm_model.compile(optimizer='adam', loss='mse')
cnn_lstm_model.fit(X_train, y_train, epochs=50, batch_size=32)

# Evaluate the models
lstm_rmse = evaluate_model(lstm_model, X_test, y_test, scaler)
gru_rmse = evaluate_model(gru_model, X_test, y_test, scaler)
cnn_lstm_rmse = evaluate_model(cnn_lstm_model, X_test, y_test, scaler)

print('LSTM RMSE:', lstm_rmse)
print('GRU RMSE:', gru_rmse)
print('CNN-LSTM RMSE:', cnn_lstm_rmse)
;