시작하기무료로 시작하기

트랜스포머 모델 만들기

PyBooks에서 여러분이 작업 중인 추천 엔진은 사용자 리뷰의 감정을 더 정교하게 이해할 수 있어야 해요. 최신 아키텍처인 트랜스포머를 사용하면 이를 달성하는 데 도움이 될 거라고 판단했습니다. 프로젝트를 시작하기 위해 리뷰의 감정을 인코딩하는 트랜스포머 모델을 만들기로 했어요.

다음 패키지는 미리 임포트되어 있습니다: torch, nn, optim.

입력 데이터에는 "I love this product", "This is terrible", "Could be better" 같은 문장과 각각에 대응하는 이진 감성 레이블 1, 0, 0, ... 이 포함되어 있어요.

입력 데이터는 다음 변수로 분할되고 임베딩으로 변환되어 있습니다: train_sentences, train_labels, test_sentences, test_labels, token_embeddings

이 연습은 강의의 일부입니다

PyTorch로 배우는 텍스트 딥러닝

강의 보기

연습 안내

  • 트랜스포머 인코더를 초기화하세요.
  • 감성 클래스 개수에 맞춰 완전 연결 계층을 정의하세요.
  • forward 메서드에서 입력을 트랜스포머 인코더에 통과시킨 뒤 선형 계층에 연결하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

class TransformerEncoder(nn.Module):
    def __init__(self, embed_size, heads, num_layers, dropout):
        super(TransformerEncoder, self).__init__()
        # Initialize the encoder 
        self.encoder = nn.____(
            nn.____(d_model=embed_size, nhead=heads),
            num_layers=num_layers)
        # Define the fully connected layer
        self.fc = nn.Linear(embed_size, ____)

    def forward(self, x):
        # Pass the input through the transformer encoder 
        x = self.____(x)
        x = x.mean(dim=1) 
        return self.fc(x)

model = TransformerEncoder(embed_size=512, heads=8, num_layers=3, dropout=0.5)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
코드 편집 및 실행