基于convlstm的地铁客流预测模型python代码
时间: 2024-01-26 11:02:21 浏览: 64
以下是基于convlstm的地铁客流预测模型的Python代码示例:
```python
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, ConvLSTM2D, Dropout
# 读取数据
df = pd.read_csv('data.csv')
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# 数据预处理
X = np.reshape(X, (X.shape[0], 1, X.shape[1], 1)) # 调整数据形状
y = np.reshape(y, (y.shape[0], 1, y.shape[1]))
# 划分训练集和测试集
train_size = int(len(X) * 0.8)
X_train, y_train = X[:train_size], y[:train_size]
X_test, y_test = X[train_size:], y[train_size:]
# 定义模型
model = Sequential()
model.add(ConvLSTM2D(filters=64, kernel_size=(1,3), activation='relu', input_shape=(1, X.shape[2], 1), return_sequences=True))
model.add(Dropout(0.2))
model.add(ConvLSTM2D(filters=32, kernel_size=(1,3), activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(ConvLSTM2D(filters=16, kernel_size=(1,3), activation='relu', return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=1))
# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_test, y_test))
# 测试模型
y_pred = model.predict(X_test)
# 计算误差
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y_test, y_pred)
print(f'MSE: {mse}')
```
在这个示例中,我们使用ConvLSTM2D层来构建模型。该模型包含三个ConvLSTM2D层和一个Dense层。我们使用Dropout来避免过拟合。在训练模型之后,我们使用测试集来评估模型,并计算均方误差(MSE)来评估模型的性能。
阅读全文