텍스트용 CNN 모델 학습
TextClassificationCNN 클래스를 잘 정의하셨어요. 이제 PyBooks에서 모델을 학습해 도서 리뷰의 감성 분석 정확도를 높이려고 해요.
다음 패키지는 미리 임포트되어 있어요:
torch, torch.nn은 nn으로, torch.nn.functional은 F로, torch.optim은 optim으로.
또한 vocab_size와 embed_dim을 인수로 하는 TextClassificationCNN() 인스턴스를 로드해 model로 저장해 두었어요.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
- 이진 분류에 사용하는 손실 함수를 정의하고
criterion으로 저장하세요. - 학습 루프 시작 시 그래디언트를 0으로 초기화하세요.
- 루프 끝에서 파라미터를 업데이트하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Define the loss function
criterion = nn.____()
optimizer = optim.SGD(model.parameters(), lr=0.1)
for epoch in range(10):
for sentence, label in data:
# Clear the gradients
model.____()
sentence = torch.LongTensor([word_to_ix.get(w, 0) for w in sentence]).unsqueeze(0)
label = torch.LongTensor([int(label)])
outputs = model(sentence)
loss = criterion(outputs, label)
loss.backward()
# Update the parameters
____.____()
print('Training complete!')