評估 BERT 模型
你已經使用 BERT 的 tokenizer 處理過範例評論,現在要用 PyBooks 的這些樣本來評估 BERT 模型。此外,你也會在新資料上評估模型的情感預測。
以下內容已為你匯入:BertTokenizer、BertForSequenceClassification、torch。
訓練好的 model 實例也已預先載入。接下來我們會用一筆新的資料樣本來測試。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 先將要評估的文字做分詞並回傳 PyTorch 張量,作為模型的輸入。
- 將輸出的 logits 轉換為 0 到 1 之間的機率。
- 根據機率顯示情感標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
text = "I had an awesome day!"
# Tokenize the text and return PyTorch tensors
input_eval = tokenizer(____, return_tensors=____, truncation=True, padding=True, max_length=32)
outputs_eval = model(**input_eval)
# Convert the output logits to probabilities
predictions = torch.nn.functional.____(outputs_eval.____, dim=-1)
# Display the sentiments
predicted_label = ____ if torch.____(predictions) > 0 else ____
print(f"Text: {text}\nSentiment: {predicted_label}")