lstm 交通流预测代码
时间: 2024-05-07 19:14:06 浏览: 187
LSTM-交通预测 代码
LSTM(长短期记忆网络)是一种用于时间序列预测的强大工具,可以用于交通流量预测。下面是一个使用LSTM模型进行交通流量预测的代码示例[^1]:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 读取数据
data = pd.read_csv('traffic_data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['traffic_volume'].values.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size, :]
test_data = scaled_data[train_size:, :]
# 创建训练集和测试集
def create_dataset(dataset, time_steps=1):
X, Y = [], []
for i in range(len(dataset) - time_steps):
X.append(dataset[i:(i + time_steps), 0])
Y.append(dataset[i + time_steps, 0])
return np.array(X), np.array(Y)
time_steps = 10
X_train, Y_train = create_dataset(train_data, time_steps)
X_test, Y_test = create_dataset(test_data, time_steps)
# 调整输入数据的形状
X_train = np.reshape(X_train, (X_train.shape, X_train.shape, 1))
X_test = np.reshape(X_test, (X_test.shape, X_test.shape, 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape, 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
# 编译和训练模型
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, Y_train, epochs=50, batch_size=32)
# 预测交通流量
predicted_traffic = model.predict(X_test)
predicted_traffic = scaler.inverse_transform(predicted_traffic)
# 输出预测结果
print(predicted_traffic)
```
请注意,上述代码仅为示例,实际使用时需要根据数据集的特点进行适当的调整和优化。另外,还可以根据需要添加其他特征来提高预测的准确性。
阅读全文