🤖 AI/ML

LSTM

Long Short-Term Memory

An RNN variant. Learns long-term dependencies. Controls information flow with gating mechanisms.

📖 Detailed Explanation

LSTM (Long Short-Term Memory) is a variant of the RNN, an architecture proposed in 1997 by Hochreiter & Schmidhuber to solve the long-term dependency problem. Conventional RNNs suffered from vanishing gradients as sequences grew longer, so they could not learn information from the distant past.

Core structure: It consists of a Cell State (long-term memory) and three Gates (Forget/Input/Output). The Forget Gate decides what information to discard, the Input Gate decides what new information to store, and the Output Gate decides what information to output. The Cell State carries information with almost no loss, like a conveyor belt.

Formulas: f_t = sigmoid(W_f[h_{t-1}, x_t]), i_t = sigmoid(W_i[h_{t-1}, x_t]), C_t = f_t*C_{t-1} + i_t*tanh(W_c[h_{t-1}, x_t]). This gating mechanism makes it possible to learn long-term dependencies spanning hundreds of steps.

Current situation: Although the Transformer has replaced LSTM in most NLP tasks, LSTM is still actively used in fields where real-time/low-latency performance matters, such as time-series forecasting, sensor data, and speech processing. Parameter efficiency is also an advantage.

💻 Code Example

import torch
import torch.nn as nn

# 1. 기본 LSTM 사용
lstm = nn.LSTM(
    input_size=128,    # 입력 특성 차원
    hidden_size=256,   # 은닉 상태 차원
    num_layers=2,      # LSTM 레이어 수
    batch_first=True,  # 입력: (batch, seq, feature)
    dropout=0.2,       # 레이어 간 드롭아웃
    bidirectional=True # 양방향 LSTM
)

# 입력: (batch_size, seq_length, input_size)
x = torch.randn(32, 100, 128)  # 32개 샘플, 100 스텝, 128 특성
output, (h_n, c_n) = lstm(x)
# output: (32, 100, 512) - 양방향이라 hidden*2
# h_n: (4, 32, 256) - num_layers*2, batch, hidden

# 2. 시계열 예측 모델 (주가 예측 예시)
class StockPredictor(nn.Module):
    def __init__(self, input_dim=5, hidden_dim=128, num_layers=2):
        super().__init__()
        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers,
                           batch_first=True, dropout=0.2)
        self.fc = nn.Linear(hidden_dim, 1)  # 다음 가격 예측

    def forward(self, x):
        # x: (batch, seq_len, features) - OHLCV 데이터
        lstm_out, _ = self.lstm(x)
        # 마지막 타임스텝만 사용
        last_hidden = lstm_out[:, -1, :]
        return self.fc(last_hidden)

model = StockPredictor()
prices = torch.randn(16, 60, 5)  # 60일 OHLCV
pred = model(prices)  # (16, 1) - 다음날 종가 예측

# 3. GRU와 비교 (더 간단한 구조)
gru = nn.GRU(input_size=128, hidden_size=256, num_layers=2)
# LSTM: 3 gates, GRU: 2 gates - 더 빠르지만 표현력은 LSTM이 높음

🗣️ Say It Like This in Practice

💬 In a Meeting
"A Transformer is overkill for real-time sensor anomaly detection. A 2-layer LSTM can run inference within 100ms, and it even runs on edge devices. An accuracy of 97% is good enough."
💬 In an Interview
"We used a Bidirectional LSTM for stock price prediction, but there was a data leakage problem where future information leaked into training. For time series, a unidirectional LSTM is correct, and bidirectional is suitable for complete sequences such as sentence classification."
💬 In a Technical Discussion
"Comparing LSTM vs GRU, LSTM has higher expressive power but 1.5 times more parameters. In our experiments, the performance difference on our dataset was under 1%, so we went with GRU. Training speed became 30% faster."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Using Bidirectional LSTM on time series

Future information is reflected in training, causing overfitting. For prediction tasks, use unidirectional only.

❌
Setting hidden_size too large

The number of LSTM parameters grows as 4*hidden^2. With hidden=512, that is over 1 million parameters. Risk of overfitting.

✅
The right way

Adjust hidden_size to the sequence length (usually 64~256). Gradient Clipping (max_norm=1.0) is essential. For long sequences, consider a Transformer.

🔗 Related Terms

📚 Learn More