開始使用免費開始

使用預訓練 PyTorch 模型進行語言翻譯

你在 PyBooks 的團隊正在進行一個需要把文字從一種語言翻成另一種語言的 AI 專案。他們想善用預訓練模型來完成這項任務,這能大幅節省訓練時間與資源。本練習的任務是從 HuggingFace 的 Transformers 函式庫設定一個翻譯模型,使用 T5(Text-To-Text Transfer Transformer)模型,將英文片語翻譯成法文。

T5TokenizerT5ForConditionalGeneration 已為你載入。

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 從預訓練的 "t5-small" 模型初始化 tokenizermodel
  • 使用 tokenizer 將輸入提示編碼,並確保回傳 PyTorch 張量。
  • 使用 model 翻譯輸入提示,並產生翻譯後的輸出。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Initalize tokenizer and model
tokenizer = ____.from_pretrained("t5-small")
model = ____.from_pretrained("t5-small")

input_prompt = "translate English to French: 'Hello, how are you?'"

# Encode the input prompt using the tokenizer
input_ids = ____.____(input_prompt, return_tensors="____")

# Generate the translated ouput
output = model.____(input_ids, max_length=50)
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
print("Generated text:",generated_text)
編輯並執行程式碼