그림은 티스토리 원문 ↗과 함께 볼 수 있습니다.
RNN은 현재 입력과 이전 은닉 상태를 함께 사용한다. LSTM과 GRU는 게이트로 상태 갱신을 조절하며, Attention은 시퀀스의 어떤 위치를 반영할지 가중치를 계산한다. 이 글의 코드는 학습 성과 보고가 아닌 이진 분류 모델의 구성 예제다.
은닉 상태와 시퀀스의 방향
단순 RNN의 상태는 이전 상태와 현재 입력에 의존한다. 긴 시퀀스의 기울기 소실·폭주로 학습이 어려워질 수 있다. LSTM은 입력·망각·출력 게이트와 셀 상태를 사용한다. GRU는 reset·update 게이트로 상태를 갱신하며, LSTM의 모든 게이트를 하나로 합쳤다고 설명하면 부정확하다.
양방향 모델은 입력을 앞·뒤로 읽는다. 뒤쪽 입력도 알아야 하므로, 미래 입력을 아직 받지 못한 실시간 처리에 그대로 적용할 수 있다고 가정하지 않는다. RNN·LSTM·GRU의 성능은 데이터와 설정을 고정해 비교해야 한다.
RNN·LSTM·GRU를 바꾸는 구성 예제
아래 예제는 Keras3 문법을 기준으로 교정했다. 길이30, 어휘5000, 임베딩100차원으로 두고 패딩을 쓰지 않는 정수 토큰 입력을 가정한다. 각 모델의 출력은 문장당 확률 하나다. 실제 한국어 데이터의 토크나이저·학습·평가는 포함하지 않는다.
import keras
from keras import layers
for recurrent in (layers.SimpleRNN, layers.LSTM, layers.GRU):
inputs = keras.Input(shape=(30,), dtype="int32")
x = layers.Embedding(input_dim=5000, output_dim=100)(inputs)
x = recurrent(128)(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer="adam", loss="binary_crossentropy")
assert model.output_shape == (None, 1)
# 양방향으로 읽는 변형
inputs = keras.Input(shape=(30,), dtype="int32")
x = layers.Embedding(5000, 100)(inputs)
x = layers.Bidirectional(layers.GRU(128))(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
bidirectional_model = keras.Model(inputs, outputs)
assert bidirectional_model.output_shape == (None, 1)Attention 가중치는 시간축에서 정규화하기
문장 분류용 attention pooling에서는 각 시점의 점수에 대해 시간축으로 softmax를 적용한다. 상태가 (batch,30,256)이고 점수가 (batch,30,1)일 때 마지막 길이1 축으로 softmax를 적용하면 모든 값이1이 된다. 원문의 기본 Activation('softmax')는 이 문제를 갖고 있어 Softmax(axis=1)로 고쳤다.
inputs = keras.Input(shape=(30,), dtype="int32")
x = layers.Embedding(5000, 100)(inputs)
states = layers.Bidirectional(
layers.GRU(128, return_sequences=True)
)(x) # (batch, 30, 256)
scores = layers.Dense(1, activation="tanh")(states)
weights = layers.Softmax(axis=1)(scores) # 시간축 합 = 1
context = layers.Dot(axes=1)([weights, states]) # (batch, 1, 256)
context = layers.Flatten()(context) # (batch, 256)
outputs = layers.Dense(1, activation="sigmoid")(context)
attention_model = keras.Model(inputs, outputs)
attention_model.compile(optimizer="adam", loss="binary_crossentropy")
assert attention_model.output_shape == (None, 1)여기서는 패딩이 없는 입력을 가정했다. 가변 길이를 패딩한다면 임베딩과 attention의 마스크를 연결해 패딩 위치가 가중치 계산에 들어가지 않게 해야 한다. 이 구성은 학습 가능한 점수로 풀링하는 예제이며 Bahdanau·Luong Attention 전체 구현이라고 부르지 않는다.
Transformer encoder로 문장 분류하기
Self-attention은 위치별 계산을 병렬화할 수 있지만 계산량이 시퀀스 길이와 무관한 것은 아니다. 원 논문의 self-attention 층별 복잡도는 O(n²d), 순차 연산 수는 O(1)이다. 아래는 위치 임베딩, attention과 feed-forward의 잔차 연결, 정규화를 포함한 encoder 블록 하나의 분류 예제다. 번역용 encoder-decoder 전체 구현은 아니다.
from keras import ops
class PositionedEmbedding(layers.Layer):
def __init__(self, vocabulary, length, width):
super().__init__()
self.tokens = layers.Embedding(vocabulary, width)
self.positions = layers.Embedding(length, width)
def call(self, token_ids):
positions = ops.arange(0, ops.shape(token_ids)[-1])
return self.tokens(token_ids) + self.positions(positions)
length, width, heads = 100, 128, 8
inputs = keras.Input(shape=(length,), dtype="int32")
x = PositionedEmbedding(5000, length, width)(inputs)
attended = layers.MultiHeadAttention(
num_heads=heads, key_dim=width // heads
)(x, x)
x = layers.LayerNormalization(epsilon=1e-6)(
x + layers.Dropout(0.1)(attended)
)
feed_forward = layers.Dense(4 * width, activation="relu")(x)
feed_forward = layers.Dense(width)(feed_forward)
x = layers.LayerNormalization(epsilon=1e-6)(
x + layers.Dropout(0.1)(feed_forward)
)
x = layers.GlobalAveragePooling1D()(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
transformer_model = keras.Model(inputs, outputs)
transformer_model.compile(optimizer="adam", loss="binary_crossentropy")
assert transformer_model.output_shape == (None, 1)위치 임베딩은 Layer의 하위 레이어로 두어 모델의 학습 변수로 관리한다. 모든 예제는 입력 토큰이 어휘 범위 안에 있고 패딩을 쓰지 않는 경우다. 앞의 문장 분류와 달리 토큰별 분류를 하려면 출력 shape와 정답 shape·손실을 함께 바꿔야 한다.
원문의 실행 화면처럼 보이는 model.summary 출력은 현재 실행 증거가 아니어서 제거했다. 코드의 Python 문법은 검사했지만 이 저장소에는 Keras 학습 환경을 추가하지 않았고, 모델 학습·한국어 성능 비교를 실행했다고 주장하지 않는다.