RNN
Recurrent Neural Network
Recurrent neural network. Specialized for processing sequence data. LSTM and GRU are typical. The mainstream of NLP before Transformers.
Recurrent Neural Network
Recurrent neural network. Specialized for processing sequence data. LSTM and GRU are typical. The mainstream of NLP before Transformers.
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).
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)
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free