動態類別指派
動態類別指派可讓模型將文字分類到預先定義的類別中,即使這些類別並未事先針對模型進行訓練。
使用 Hugging Face 的 pipeline() 執行 zero-shot-classification 任務,提供文字與預先定義的類別,以找出最適合的匹配。
建立一個分類器,為輸入的 text(已替你載入的新聞標題)預測標籤。
transformers 函式庫中的 pipelines 已預先載入,方便你使用。
注意:我們使用的是經過自訂的 pipeline,幫助你學會如何使用這些函式,而不需要下載模型。
本練習屬於課程
善用 Hugging Face
練習說明
- 建立 pipeline 並儲存為
classifier。 - 建立一個標籤清單──
"politics"、"science"、"sports"──並儲存為categories。 - 使用分類器與預先定義的類別,為
text預測標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
text = "AI-powered robots assist in complex brain surgeries with precision."
# Create the pipeline
____ = pipeline(____="zero-shot-classification", ____="facebook/bart-large-mnli")
# Create the categories list
categories = ["politics", "____", "____"]
# Predict the output
output = ____(____, ____)
# Print the top label and its score
print(f"Top Label: {output['labels'][0]} with score: {output['scores'][0]}")