Transformer 모델 학습과 테스트
TransformerEncoder 모델이 준비되었으니, 다음 단계로 PyBooks에서 샘플 리뷰로 모델을 학습시키고 성능을 평가해 보겠습니다. 이러한 샘플 리뷰로 학습하면 방대한 자료에서 감성의 흐름을 파악하는 데 도움이 됩니다. 모델의 성능이 충분히 높아지면, PyBooks는 감성 분석을 자동화하여 독자들에게 더 깊이 있는 추천과 피드백을 제공할 수 있어요.
다음 패키지는 이미 임포트되어 있습니다: torch, nn, optim.
TransformerEncoder 클래스의 model 인스턴스, token_embeddings, 그리고 train_sentences, train_labels, test_sentences, test_labels가 미리 로드되어 있어요.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
- 학습 루프에서 문장을 토큰으로 분할한 뒤 임베딩을 스택으로 쌓으세요.
- 경사를 0으로 초기화하고 역전파를 수행하세요.
predict함수에서는 경사 계산을 비활성화한 다음 감성 예측 값을 구하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
for epoch in range(5):
for sentence, label in zip(train_sentences, train_labels):
# Split the sentences into tokens and stack the embeddings
tokens = ____
data = torch.____([token_embeddings[token] for token in ____], dim=1)
output = model(data)
loss = criterion(output, torch.tensor([label]))
# Zero the gradients and perform a backward pass
optimizer.____()
loss.____()
optimizer.step()
print(f"Epoch {epoch}, Loss: {loss.item()}")
def predict(sentence):
model.eval()
# Deactivate the gradient computations and get the sentiment prediction.
with torch.____():
tokens = sentence.split()
data = torch.stack([token_embeddings.get(token, torch.rand((1, 512))) for token in tokens], dim=1)
output = model(data)
predicted = torch.____(output, dim=1)
return "Positive" if predicted.item() == 1 else "Negative"
sample_sentence = "This product can be better"
print(f"'{sample_sentence}' is {predict(sample_sentence)}")