텍스트 분류를 위한 합성곱 신경망(CNN)

PyTorch로 배우는 텍스트 딥러닝

Shubham Jain

Instructor

텍스트 분류용 CNN

  • 트윗 분류
    • 긍정
    • 부정
    • 중립
PyTorch로 배우는 텍스트 딥러닝

합성곱 연산

합성곱 연산

  • 합성곱 연산
    • 입력 위로 필터(커널)를 슬라이딩
    • 각 위치에서 요소별 계산 수행

 

  • 텍스트: 단어의 구조와 의미 학습
1 Vincent Dumoulin, Francesco Visin의 애니메이션
PyTorch로 배우는 텍스트 딥러닝

CNN의 필터와 보폭

  • 필터:
    • 입력 위를 슬라이딩하는 작은 행렬

 

  • 보폭(stride):
    • 필터가 이동하는 칸 수

필터와 보폭

1 Vincent Dumoulin, Francesco Visin의 애니메이션
PyTorch로 배우는 텍스트 딥러닝

텍스트용 CNN 아키텍처

  • 합성곱 층: 입력에 필터 적용
  • 풀링 층: 핵심 정보는 유지하며 크기 축소
  • 완전연결 층: 이전 출력으로 최종 예측 수행
PyTorch로 배우는 텍스트 딥러닝

CNN으로 텍스트 분류 모델 구현

class SentimentAnalysisCNN(nn.Module):

def __init__(self, vocab_size, embed_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.conv = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(embed_dim, 2) ...
  • __init__ 메서드가 아키텍처를 설정
  • super()로 기본 클래스 nn.Module 초기화
  • nn.Embedding: 밀집 단어 벡터 생성
  • nn.Conv1d: 1차원 데이터용
PyTorch로 배우는 텍스트 딥러닝

CNN으로 텍스트 분류 모델 구현

    ...
    def forward(self, text):
        embedded = self.embedding(text).permute(0, 2, 1)

conved = F.relu(self.conv(embedded))
conved = conved.mean(dim=2)
return self.fc(conved)
  • 임베딩 층이 텍스트를 임베딩으로 변환
  • 합성곱 입력에 맞게 텐서 차원 정렬
  • ReLU로 중요한 특징 추출
  • 불필요한 차원 제거
PyTorch로 배우는 텍스트 딥러닝

감성 분석 모델을 위한 데이터 준비

vocab = ["i", "love", "this", "book", "do", "not", "like"]
word_to_idx = {word: i for i, word in enumerate(vocab)}

vocab_size = len(word_to_ix)
embed_dim = 10
book_samples = [ ("The story was captivating and kept me hooked until the end.".split(),1), ("I found the characters shallow and the plot predictable.".split(),0) ]
model = SentimentAnalysisCNN(vocab_size, embed_dim) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.1)
PyTorch로 배우는 텍스트 딥러닝

모델 학습

for epoch in range(10):  
    for sentence, label in data:

model.zero_grad()
sentence = torch.LongTensor([word_to_idx.get(w, 0) for w in sentence]).unsqueeze(0)
outputs = model(sentence) label = torch.LongTensor([int(label)])
loss = criterion(outputs, label) loss.backward()
optimizer.step()
PyTorch로 배우는 텍스트 딥러닝

감성 분석 모델 실행

for sample in book_samples:

input_tensor = torch.tensor([word_to_idx[w] for w in sample], dtype=torch.long).unsqueeze(0)
outputs = model(input_tensor)
_, predicted_label = torch.max(outputs.data, 1)
sentiment = "Positive" if predicted_label.item() == 1 else "Negative"
print(f"Book Review: {' '.join(sample)}") print(f"Sentiment: {sentiment}\n")
Book Review: The story was captivating and kept me hooked until the end
Sentiment: Positive
Book Review: I found the characters shallow and the plot predictable
Sentiment: Negative
PyTorch로 배우는 텍스트 딥러닝

Ayo berlatih!

PyTorch로 배우는 텍스트 딥러닝

Preparing Video For Download...