감성 분석 CNN 모델 테스트하기
모델을 학습했으니, PyBooks에서 새로운 도서 리뷰로 성능을 확인하려고 합니다.
각 리뷰의 감성이 긍정인지 부정인지 판별해야 합니다.
다음 패키지가 이미 임포트되어 있습니다:
torch, torch.nn은 nn으로, torch.nn.functional은 F로, torch.optim은 optim으로.
또한 vocab_size와 embed_dim을 인수로 하는 TextClassificationCNN() 인스턴스가 로드되어 model로 저장되어 있습니다.
이 연습은 강의의 일부입니다
PyTorch로 배우는 텍스트 딥러닝
연습 안내
book_reviews리스트를 순회하며, 각 리뷰의 단어들을 텐서로 변환하세요.- 각
input_tensor에 대해 모델의 출력을 구하세요. outputs.data에서 가장 가능성이 높은 감성 범주의 인덱스를 찾으세요.predicted_label항목을 추출해 변환하고,1이면 "Positive" 레이블의 감성 문자열로 바꾸세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
book_reviews = [
"I love this book".split(),
"I do not like this book".split()
]
for review in book_reviews:
# Convert the review words into tensor form
input_tensor = ____.____([word_to_ix[w] for w in review], dtype=torch.long).unsqueeze(0)
# Get the model's output
outputs = model(____)
# Find the index of the most likely sentiment category
_, predicted_label = ____.____(outputs.data, 1)
# Convert the predicted label into a sentiment string
sentiment = "Positive" if ____ else "Negative"
print(f"Book Review: {' '.join(review)}")
print(f"Sentiment: {sentiment}\n")