본문 바로가기
카테고리 없음

Transformer 기반 변수 중요도 추출

by fisherman1 2025. 5. 30.

개요 : 이 문서는 Transformer를 사용하여 X-Y 관계에서 각 X 인자에 대한 Attention Score를 출력하는 방법과, 학습(Training)과 추론(Inference) 관점의 코드 예제, Transformer 모델 종류별 특징을 포함한 설명을 제공합니다. 로컬 PC 환경에서 실행 가능한 Python 코드로 작성되었습니다.

1. Transformer의 Attention Score 출력: X-Y 관계 설명

Transformer는 입력(X)과 출력(Y) 간의 관계를 학습하며, 각 입력 단어(X)가 출력(Y)에 어떻게 영향을 주는지를 Attention Score로 나타냅니다. 이를 통해 모델이 어떤 부분에 집중하는지 해석할 수 있습니다.

2. Transformer Training 코드: Attention Score 출력

Training 단계에서는 모델이 학습 중 각 X 인자에 얼마만큼 집중하는지(Attention Score)를 확인할 수 있습니다.

from transformers import BertTokenizer, BertModel
import torch, matplotlib.pyplot as plt, seaborn as sns

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased', output_attentions=True)
model.train()

sentence = "The quick brown fox jumps over the lazy dog"
inputs = tokenizer(sentence, return_tensors='pt')
outputs = model(**inputs)

attentions = outputs.attentions  # (num_layers, batch_size, num_heads, seq_len, seq_len)
attention = attentions[0][0][0].detach().numpy()  # 첫 레이어, 첫 헤드

tokens = tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])
plt.figure(figsize=(10,8))
sns.heatmap(attention, xticklabels=tokens, yticklabels=tokens, cmap='viridis')
plt.title("Training Attention Scores")
plt.show()
  

3. Transformer Inference 코드: Attention Score 출력

추론(Inference) 단계에서는 학습된 모델로 새로운 입력에 대한 Attention Score를 추출합니다.

model.eval()
with torch.no_grad():
    outputs = model(**inputs)
    attentions = outputs.attentions

attention = attentions[0][0][0].numpy()  # 첫 레이어, 첫 헤드
# 시각화 코드는 동일
  

4. Transformer 종류별 설명

모델구조학습 방식특징주요 활용
BERT Encoder-only Masked Language Modeling + Next Sentence Prediction 양방향 문맥 학습에 강점 분류, NER, QA
GPT Decoder-only Autoregressive Language Modeling 생성 작업에 강점 텍스트 생성, 챗봇
T5 Encoder-Decoder Text-to-Text 방식 모든 작업을 텍스트 변환 문제로 접근 번역, 요약, QA
RoBERTa Encoder-only Masked LM (BERT 개선) 더 많은 데이터와 긴 학습으로 성능 향상 분류, NER, QA
XLNet Permutation-based 순열 학습 문맥 이해 향상, BERT 대체 모델 QA, 문서 분류

5. 요약

  • Transformer 모델은 X-Y 관계에서 Attention Score를 통해 입력(X)의 중요도를 추출 가능
  • Training 단계에서는 학습 중의 집중 영역 확인, Inference 단계에서는 새로운 입력에 대한 집중 영역 분석
  • BERT, GPT, T5, RoBERTa, XLNet 등 다양한 Transformer 모델의 특징과 활용 분야 파악