시작하기무료로 시작하기

어텐션이 포함된 RNN 모델 만들기

PyBooks 팀은 다양한 딥러닝 아키텍처를 탐색하고 있어요. 조사를 거친 뒤, 문장 속 다음 단어를 예측하기 위해 어텐션 메커니즘이 포함된 RNN을 구현하기로 했습니다. 문장으로 이루어진 데이터셋과 그로부터 만들어진 vocabulary가 제공됩니다.

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

다음 항목이 미리 로드되어 있습니다:

  • vocabvocab_size: vocabulary 집합과 그 크기
  • word_to_ixix_to_word: 단어-인덱스, 인덱스-단어 매핑을 위한 딕셔너리
  • input_datatarget_data: 입력-출력 쌍으로 변환된 데이터셋
  • embedding_dimhidden_dim: 임베딩과 RNN hidden state의 차원

예시 문장을 보려면 콘솔에서 data 변수를 확인해 보세요.

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

PyTorch로 배우는 텍스트 딥러닝

강의 보기

연습 안내

  • 주어진 embedding_dim으로 vocabulary용 임베딩 레이어를 만드세요.
  • RNN 시퀀스 출력을 선형 변환해 어텐션 스코어를 구하세요.
  • 스코어로부터 어텐션 가중치를 구하세요.
  • RNN 출력과 어텐션 가중치의 가중합으로 컨텍스트 벡터를 계산하세요.

실습형 인터랙티브 연습

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

class RNNWithAttentionModel(nn.Module):
    def __init__(self):
        super(RNNWithAttentionModel, self).__init__()
        # Create an embedding layer for the vocabulary
        self.embeddings = nn.____(vocab_size, embedding_dim)
        self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
        # Apply a linear transformation to get the attention scores
        self.attention = nn.____(____, 1)
        self.fc = nn.____(hidden_dim, vocab_size)
    def forward(self, x):
        x = self.embeddings(x)
        out, _ = self.rnn(x)
        #  Get the attention weights
        attn_weights = torch.nn.functional.____(self.____(out).____(2), dim=1)
        # Compute the context vector 
        context = torch.sum(____.____(2) * out, dim=1)
        out = self.fc(context)
        return out
      
attention_model = RNNWithAttentionModel()
optimizer = torch.optim.Adam(attention_model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
print("Model Instantiated")
코드 편집 및 실행