用Python写一段lstm算法预测公交到站时间
时间: 2023-05-12 08:03:04 浏览: 119
Python实现ALO-LSTM蚁狮算法优化长短期记忆神经网络时间序列预测(完整源码和数据)
好的,以下是一段用 Python 编写的 LSTM 算法预测公交到站时间的代码:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载数据集
data = pd.read_csv('bus_data.csv')
# 数据预处理
data['time'] = pd.to_datetime(data['time'])
data['hour'] = data['time'].dt.hour
data['minute'] = data['time'].dt.minute
data['second'] = data['time'].dt.second
data['time_diff'] = data['time'].diff().dt.seconds.fillna(0)
data['time_diff'] = data['time_diff'].apply(lambda x: x if x < 600 else 0)
data['time_diff'] = data['time_diff'].rolling(window=5).mean().fillna(0)
data = data[['hour', 'minute', 'second', 'time_diff']].values
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data, test_data = data[:train_size], data[train_size:]
# 数据归一化
mean = train_data.mean(axis=0)
std = train_data.std(axis=0)
train_data = (train_data - mean) / std
test_data = (test_data - mean) / std
# 构建训练集和测试集
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset) - look_back):
X.append(dataset[i:(i + look_back)])
Y.append(dataset[i + look_back])
return np.array(X), np.array(Y)
look_back = 5
train_X, train_Y = create_dataset(train_data, look_back)
test_X, test_Y = create_dataset(test_data, look_back)
# 构建 LSTM 模型
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 4)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=64, verbose=2)
# 预测测试集
test_predict = model.predict(test_X)
test_predict = test_predict * std[3] + mean[3]
test_Y = test_Y * std[3] + mean[3]
# 计算误差
rmse = np.sqrt(np.mean(np.square(test_predict - test_Y)))
print('Test RMSE: %.3f' % rmse)
```
这段代码使用 LSTM 算法对公交到站时间进行预测,数据集来自于 `bus_data.csv` 文件。首先对数据进行预处理,然后划分训练集和测试集,并进行数据归一化。接着构建 LSTM 模型,训练模型并预测测试集,最后计算误差。
阅读全文