LSTM模型预测客流代码
时间: 2023-10-05 21:07:07 浏览: 98
下面是一个使用LSTM模型进行客流预测的简单代码示例:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
# 读取数据
data = pd.read_csv('data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size, :]
test_data = scaled_data[train_size:, :]
# 构建训练集数据
X_train, y_train = [], []
for i in range(60, len(train_data)):
X_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
# 调整输入数据的维度
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 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=10, batch_size=32)
# 对测试集进行预测
inputs = data[len(data) - len(test_data) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = scaler.transform(inputs)
X_test = []
for i in range(60, inputs.shape[0]):
X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_values = model.predict(X_test)
predicted_values = scaler.inverse_transform(predicted_values)
# 可视化预测结果
plt.plot(data[len(data)-len(test_data):].index, test_data, color='blue', label='Actual')
plt.plot(data[len(data)-len(test_data):].index, predicted_values, color='red', label='Predicted')
plt.title('客流预测')
plt.xlabel('日期')
plt.ylabel('客流量')
plt.legend()
plt.show()
```
请注意,此代码仅为一个简单的示例,实际应用中可能需要根据具体情况进行调整和优化。另外,还需要准备相应的数据集,并将其保存为"data.csv"文件。
阅读全文