02. RNN, LSTM, GRU with Time Series Data
02. RNN, LSTM, GRU with Time Series Data
RNN with Time Series Data and PyTorch
1. Overall Pipeline of Model Implementation
1-1. Device Setup
1
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- Use GPU if available, otherwise CPU
1
2
print(torch.cuda.is_available())
print(torch.cuda.device_count())
2. Dataset
We generate synthetic time-series data:
- Normal signal → sine wave + small noise
- Anomaly signal → sine wave + spike + noise
1
def generate_data(num_samples=1000, seq_len=50):
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
import numpy as np
def generate_data(num_samples=1000, seq_len=50):
X = []
y = []
for _ in range(num_samples):
t = np.linspace(0, 10, seq_len)
if np.random.rand() > 0.5:
signal = np.sin(t) + np.random.normal(0, 0.1, seq_len)
label = 0 # normal
else:
signal = np.sin(t)
spike = np.random.randint(10, seq_len-10)
signal[spike:spike+3] += np.random.normal(3, 0.5, 3)
signal += np.random.normal(0, 0.3, seq_len)
label = 1 # anomaly
X.append(signal)
y.append(label)
return np.array(X), np.array(y)
seq_len = 50
X, y = generate_data(2000, seq_len)
Check Data
1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
normal_idx = np.where(y == 0)[0][0]
plt.plot(X[normal_idx])
plt.title("Normal Signal")
plt.show()
anomaly_idx = np.where(y == 1)[0][0]
plt.plot(X[anomaly_idx])
plt.title("Anomaly Signal")
plt.show()
Data Structure
After preprocessing:
1
X_train.shape = (batch, seq_len, input_size)
1
(1600, 50, 1)
- batch = number of samples
- seq_len = time steps
- input_size = feature per time step
Data Convert
1
X_train = torch.FloatTensor(X_train).unsqueeze(-1)
Converts:
1
(1600, 50) → (1600, 50, 1)
Required for RNN input format
Divide Train/Test
1
2
3
4
5
6
7
8
9
split = int(len(X) * 0.8)
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
X_train = torch.FloatTensor(X_train).unsqueeze(-1).to(device)
X_test = torch.FloatTensor(X_test).unsqueeze(-1).to(device)
y_train = torch.LongTensor(y_train).to(device)
y_test = torch.LongTensor(y_test).to(device)
3. RNN
1
2
3
4
5
6
7
8
9
10
11
self.rnn = nn.RNN(
input_size,
hidden_size,
num_layers=1,
nonlinearity='tanh',
bias=True,
batch_first=False,
dropout=0.0,
bidirectional=False
)
input_size
1
input_size = feature size per time step
1
( batch, seq_len, 1 ) → input_size = 1
hidden_size
1
hidden_size = number of features in hidden state
Controls model capacity
- small → fast but weak
- large → powerful but heavy
num_layers
1
num_layers = stacked RNN layers
nonlinearity
1
nonlinearity = 'tanh' or 'relu'
Options
| Type | features |
|---|---|
| tanh | default, stable |
| relu | faster, less stable |
bias
1
bias=True
Adds bias term:
1
h = Wx + Uh + b
batch_first
1
batch_first=True or False
False (default)
1
(seq_len, batch, input_size)
True (recommended)
1
(batch, seq_len, input_size)
dropout
1
dropout=0.0
Applies dropout between RNN layers
Important
1
only works when num_layers > 1
bidirectional
1
bidirectional=True
runs RNN in both directions:
1
forward + backward
Example
1
2
x₁ → x₂ → x₃ → x₄
x₄ → x₃ → x₂ → x₁
Output size changes
1
hidden_size → hidden_size * 2
Output
Output Shape
Input
1
(batch, seq_len, input_size)
Output
1
(batch, seq_len, hidden_size)
if bidirectional:
1
hidden_size * 2
Hidden State
1
h0 = torch.zeros(num_layers, batch, hidden_size)
shape depends on:
- num_layers
- bidirectional
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class RNNModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1):
super(RNNModel, self).__init__()
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, 2)
def forward(self,x):
h0 = torch.zeros(1, x.size(0), 64).to(x.device)
out, _ = self.rnn(x,h0)
out = out[:,-1,:]
out = self.fc(out)
return out
model = RNNModel().to(device)
4. LSTM
1
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, proj_size=0, device=None, dtype=None)
1
h0, c0 = hidden state + cell state
LSTM has memory cell
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
class LSTMModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1, num_classes=2):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True
)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
out, (hn, cn) = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
model = LSTMModel().to(device)
Forward
1
2
out, (hn, cn) = self.lstm(x, (h0, c0))
out = out[:, -1, :] # (batch_size, seq_len, hidden_dim) -> (batch_size, hidden_dim), last hidden state
5. GRU
1
2
self.gru = nn.GRU(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, device=None, dtype=None)
Forward
1
2
out, hn = self.gru(x, h0)
out = out[:, -1, :]
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
class GRUModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1, num_classes=2):
super(GRUModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.gru = nn.GRU(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True
)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
out, hn = self.gru(x, h0)
out = out[:, -1, :] # 마지막 시점
out = self.fc(out)
return out
model = GRUModel().to(device)
6. Training Loop
1
2
3
4
5
6
outputs = model(X_train)
loss = criterion(outputs, y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
Standard PyTorch pipeline
Loss
1
criterion = nn.CrossEntropyLoss()
Multi-class classification (normal vs anomaly)
Evaluation
1
2
_, predicted = torch.max(outputs, 1)
accuracy = (predicted == y_test).sum().item() / len(y_test)
Why Last Time Step?
1
out = out[:, -1, :]
The model compresses the entire sequence into:
1
last hidden state
This acts like a summary of the sequence
Visualization
The code visualizes predictions:
1
2
plt.plot(X_test_cpu[i])
plt.title(f"True: {true_label}, Pred: {pred_label}")
Helps understand model behavior
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import torch
print("cuda available:", torch.cuda.is_available())
print("device count:", torch.cuda.device_count())
if torch.cuda.is_available():
print("device name:", torch.cuda.get_device_name(0))
import numpy as np
def generate_data(num_samples=1000, seq_len=50):
X = []
y = []
for _ in range(num_samples):
t = np.linspace(0, 10, seq_len)
if np.random.rand() > 0.5:
signal = np.sin(t) + np.random.normal(0, 0.1, seq_len)
label = 0 # normal
else:
signal = np.sin(t)
spike = np.random.randint(10, seq_len-10)
signal[spike:spike+3] += np.random.normal(3, 0.5, 3)
signal += np.random.normal(0, 0.3, seq_len)
label = 1 # anomaly
X.append(signal)
y.append(label)
return np.array(X), np.array(y)
seq_len = 50
X, y = generate_data(2000, seq_len)
normal_idx = np.where(y == 0)[0][0]
plt.plot(X[normal_idx])
plt.title("Normal Signal")
plt.show()
anomaly_idx = np.where(y == 1)[0][0]
plt.plot(X[anomaly_idx])
plt.title("Anomaly Signal")
plt.show()
split = int(len(X) * 0.8)
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
X_train = torch.FloatTensor(X_train).unsqueeze(-1).to(device)
X_test = torch.FloatTensor(X_test).unsqueeze(-1).to(device)
y_train = torch.LongTensor(y_train).to(device)
y_test = torch.LongTensor(y_test).to(device)
class RNNModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1):
super(RNNModel, self).__init__()
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, 2)
def forward(self,x):
h0 = torch.zeros(1, x.size(0), 64).to(x.device)
out, _ = self.rnn(x,h0)
out = out[:,-1,:]
out = self.fc(out)
return out
model = RNNModel().to(device)
class LSTMModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1, num_classes=2):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True
)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
out, (hn, cn) = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
model = LSTMModel().to(device)
class GRUModel(nn.Module):
def __init__(self, input_size=1, hidden_size=64, num_layers=1, num_classes=2):
super(GRUModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.gru = nn.GRU(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True
)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
out, hn = self.gru(x, h0)
out = out[:, -1, :]
out = self.fc(out)
return out
model = GRUModel().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
epochs = 100
for epoch in range(epochs):
model.train()
outputs = model(X_train)
loss = criterion(outputs, y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch:[{epoch+1}/{epochs}], Loss: {loss.item(): 4f}")
import matplotlib.pyplot as plt
model.eval()
with torch.no_grad():
outputs = model(X_test)
_, predicted = torch.max(outputs, 1)
X_test_cpu = X_test.cpu().squeeze(-1).numpy()
y_test_cpu = y_test.cpu().numpy()
predicted_cpu = predicted.cpu().numpy()
num_samples = 8
plt.figure(figsize=(14, 10))
for i in range(num_samples):
plt.subplot(4, 2, i + 1)
plt.plot(X_test_cpu[i])
true_label = y_test_cpu[i]
pred_label = predicted_cpu[i]
result = "Correct" if true_label == pred_label else "Wrong"
plt.title(f"True: {true_label}, Pred: {pred_label} ({result})")
plt.tight_layout()
plt.show()
This post is licensed under CC BY 4.0 by the author.