텍스트용 CNN 모델 구축하기
PyBooks는 도서 추천 엔진을 성공적으로 구축했습니다. 다음 과제로는 사용자 리뷰를 이해하고 도서 선호도를 파악하기 위해 감성 분석 모델을 구현하려고 해요.
이 연습에서는 Convolutional Neural Network(CNN) 모델을 사용해 텍스트 데이터(도서 리뷰)를 감성에 따라 분류해 보겠습니다.
torch, torch.nn은 nn으로, torch.nn.functional은 F로 미리 불러와 두었어요.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
__init__()메서드에서 임베딩 레이어를 초기화하세요.forward()메서드에서embedded텍스트에 합성곱 레이어self.conv를 적용하세요.forward()메서드에서 이 레이어에 ReLU 활성화를 적용하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
class TextClassificationCNN(nn.Module):
def __init__(self, vocab_size, embed_dim):
super(TextClassificationCNN, self).__init__()
# Initialize the embedding layer
self.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)
def forward(self, text):
embedded = self.embedding(text).permute(0, 2, 1)
# Pass the embedded text through the convolutional layer and apply a ReLU
conved = ____.____(self.conv(____))
conved = conved.mean(dim=2)
return self.fc(conved)