시작하기무료로 시작하기

어텐션을 적용한 RNN 모델 학습과 테스트

PyBooks 팀은 이전에 어텐션 메커니즘 없이 단어 예측을 위한 RNN 모델을 구축했습니다. 이 초기 모델은 rnn_model로 부르며 이미 학습이 완료되었고 인스턴스가 미리 로드돼 있습니다. 이제 여러분의 과제는 새 RNNWithAttentionModel을 학습한 뒤, 이전 rnn_model의 예측과 비교하는 것입니다.

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

  • inputs: 텐서 형태의 입력 시퀀스 목록
  • targets: 각 입력 시퀀스의 타깃 단어를 담은 텐서
  • optimizer: Adam 옵티마이저 함수
  • criterion: CrossEntropyLoss 함수
  • pad_sequences: 배치를 위해 입력 시퀀스를 패딩하는 함수
  • attention_model: 이전 연습 문제에서 정의한 모델 클래스
  • rnn_model: PyBooks 팀이 학습한 RNN 모델

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

PyTorch로 배우는 텍스트 딥러닝

강의 보기

연습 안내

  • 테스트 데이터로 평가하기 전에 RNN 모델을 평가 모드로 설정하세요.
  • 적절한 입력을 RNN 모델에 전달해 RNN 출력을 얻으세요.
  • RNN 출력에서 예측 점수가 가장 높은 단어를 추출하세요.
  • 어텐션 모델도 같은 방식으로, 어텐션 출력에서 예측 점수가 가장 높은 단어를 추출하세요.

실습형 인터랙티브 연습

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

for epoch in range(epochs):
    attention_model.train()
    optimizer.zero_grad()
    padded_inputs = pad_sequences(inputs)
    outputs = attention_model(padded_inputs)
    loss = criterion(outputs, targets)
    loss.backward()
    optimizer.step()

for input_seq, target in zip(input_data, target_data):
    input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)
   	
    #  Set the RNN model to evaluation mode
    rnn_model.____()
    # Get the RNN output by passing the appropriate input 
    rnn_output = ____(____)
    # Extract the word with the highest prediction score 
    rnn_prediction = ix_to_word[torch.____(____).item()]

    attention_model.eval()
    attention_output = attention_model(input_test)
    # Extract the word with the highest prediction score
    attention_prediction = ix_to_word[torch.____(____).item()]

    print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}")
    print(f"Target: {ix_to_word[target]}")
    print(f"RNN prediction: {rnn_prediction}")
    print(f"RNN with Attention prediction: {attention_prediction}")
코드 편집 및 실행