πŸ€– AI/ML

RNN

Recurrent Neural Network

Recurrent neural network. Specialized for processing sequence data. LSTM and GRU are typical. The mainstream of NLP before Transformers.

πŸ“– Detailed Explanation

RNN (Recurrent Neural Network) is a neural network architecture designed to process sequence data. It is characterized by a recurrent structure that "remembers" information from previous time steps and uses it in the output at the current time step, and it is widely used in natural language processing, speech recognition, time series forecasting, and more.

RNN was proposed by David Rumelhart in 1986, and became practical with the emergence of LSTM in the 1990s. Conventional feedforward networks could only process fixed-length inputs, but RNN can process variable-length sequences, bringing innovation to the fields of natural language and time series.

The core principle of RNN is the recurrence of the "Hidden State." At each time step, the input and the previous hidden state are combined to compute a new hidden state. However, the vanishing/exploding gradient problem occurs in long sequences, and LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit), which solved this, have become the standard.

Since the emergence of the Transformer in 2017, the use of RNN in the NLP field has declined, but it is still used in environments where memory efficiency is important, such as real-time streaming data and edge devices. The recurrent concept of RNN is also influencing modern State Space Models (such as Mamba).

πŸ’» Code Example

This is an example of LSTM-based sequence classification using PyTorch.

import torch
import torch.nn as nn

class LSTMClassifier(nn.Module):
    """LSTM 기반 ν…μŠ€νŠΈ λΆ„λ₯˜ λͺ¨λΈ"""

    def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_dim)
        self.lstm = nn.LSTM(
            embed_dim,
            hidden_dim,
            num_layers=2,
            batch_first=True,
            dropout=0.3,
            bidirectional=True  # μ–‘λ°©ν–₯ LSTM
        )
        self.fc = nn.Linear(hidden_dim * 2, num_classes)  # μ–‘λ°©ν–₯μ΄λ―€λ‘œ *2

    def forward(self, x):
        # x: (batch, seq_len)
        embedded = self.embedding(x)  # (batch, seq_len, embed_dim)
        lstm_out, (hidden, cell) = self.lstm(embedded)

        # λ§ˆμ§€λ§‰ μ‹œμ μ˜ 은닉 μƒνƒœ μ‚¬μš© (μ–‘λ°©ν–₯ κ²°ν•©)
        hidden = torch.cat((hidden[-2], hidden[-1]), dim=1)
        output = self.fc(hidden)
        return output

# λͺ¨λΈ μ΄ˆκΈ°ν™”
model = LSTMClassifier(vocab_size=10000, embed_dim=128, hidden_dim=256, num_classes=3)

# μ˜ˆμ‹œ μž…λ ₯
x = torch.randint(0, 10000, (32, 50))  # (batch=32, seq_len=50)
output = model(x)
print(f"좜λ ₯ shape: {output.shape}")  # (32, 3)

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"LSTM is suitable for real-time sensor data analysis. It is more memory-efficient than Transformer, so it can run even on edge devices."
πŸ’¬ In an Interview
"LSTM solves RNN's vanishing gradient problem with the Cell State and Gate mechanism. The Forget Gate is the key to learning long-term dependencies."
πŸ’¬ In a Technical Discussion
"GRU has fewer parameters than LSTM, so it trains faster and delivers similar performance on most tasks. If you have resource constraints, try GRU first."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Using Vanilla RNN: A basic RNN cannot learn long sequences because of vanishing gradients. Always use LSTM or GRU.
❌
Inadequate padding handling: If you do not ignore padding in variable-length sequences, performance degrades. Use pack_padded_sequence.
βœ…
Apply Gradient Clipping: RNN-family models are vulnerable to exploding gradients. Limit the gradients with torch.nn.utils.clip_grad_norm_.

πŸ”— Related Terms

πŸ“š Learn More