-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLSTM
More file actions
69 lines (57 loc) · 2.47 KB
/
Copy pathLSTM
File metadata and controls
69 lines (57 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 读取数据集
df = pd.read_csv('monthly_IBM.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.set_index('timestamp')
# 选取关闭价格作为预测目标
data = df['close'].values.reshape(-1, 1)
# 将数据归一化到 [0, 1] 的范围
scaler = MinMaxScaler(feature_range=(0, 1))
data_scaled = scaler.fit_transform(data)
# 定义函数将时间序列数据转换为监督学习问题
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 = 12 # 使用过去12个月的数据来预测未来的数据
X, y = create_dataset(data_scaled, time_steps)
train_size = int(len(X) * 0.8)
X_train, X_test, y_train, y_test = X[:train_size], X[train_size:], y[:train_size], y[train_size:]
# 将输入数据重塑为 [样本数, 时间步长, 特征数] 的三维数组
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.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, return_sequences=True))
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)
# 预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 将预测数据逆归一化
train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict)
# 绘制结果
plt.figure(figsize=(14, 7))
plt.plot(df.index[time_steps:train_size], data[time_steps:train_size], label='Train Data')
plt.plot(df.index[train_size+time_steps:], data[train_size+time_steps:], label='Test Data')
plt.plot(df.index[time_steps:train_size], train_predict, label='Train Predictions', linestyle='dashed')
plt.plot(df.index[train_size+time_steps:], test_predict, label='Test Predictions', linestyle='dashed')
plt.title('IBM Stock Price Prediction')
plt.xlabel('Timestamp')
plt.ylabel('Stock Price')
plt.legend()
plt.show()