翻譯練習
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# 選擇專門的中英翻譯模型
model_name = "Helsinki-NLP/opus-mt-zh-en"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# 翻譯函數
def translate_text_new(text):
# 直接輸入原文即可
input_ids = tokenizer(text, return_tensors="pt").input_ids
outputs = model.generate(input_ids)
translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return translated_text
chinese_text_1 = "今天天氣真好,適合出去走走。"
translation_1 = translate_text_new(chinese_text_1)
print(f"原文:{chinese_text_1}\n翻譯結果:{translation_1}")
解釋 :
!pip install transformers torch sentencepiece
from transformers import AutoTokenizer, AutoModelForCausalLM
# 載入模型和分詞器
# 這個模型是一個輕量級的中文 GPT-2 模型
model_name = "uer/gpt2-chinese-cluecorpussmall"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
def get_model_response(prompt_text, max_length=200):
"""
使用給定的提示來產生模型回應。
"""
# 對提示文本進行編碼
input_ids = tokenizer.encode(prompt_text, return_tensors='pt')
# 產生回應
output = model.generate(
input_ids,
max_length=max_length,
num_return_sequences=1,
no_repeat_ngram_size=2, # 避免重複的N元語法
pad_token_id=tokenizer.eos_token_id,
do_sample=True,
top_k=50,
top_p=0.95,
temperature=0.7 # 控制創造力,數值越高越隨機
)
# 解碼並輸出結果
response_text = tokenizer.decode(output[0], skip_special_tokens=True)
return response_text
# 情境描述
situation = """
你現在是一個新創公司的資深產品經理,正在發想一個創新的 App。
公司目前專注於解決年輕人生活中的痛點。
你的任務是提出一個新的 App 點子,並說明其核心功能、目標用戶和商業模式。
請從產品經理的專業角度,詳細闡述你的想法。
"""
# 問題
question = "請針對「解決年輕人獨居時的寂寞感」這個痛點,提出一個 App 產品提案。"
# 將情境和問題結合
prompt = f"{situation}\n\n{question}"
# 呼叫函數並取得回應
response = get_model_response(prompt)
print("--- 產品經理的提案 ---")
print(response)
結果 :
The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's attention_mask
to obtain reliable results.
Setting pad_token_id
to eos_token_id
:50256 for open-end generation.
The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's attention_mask
to obtain reliable results.
--- 產品經理的提案 ---
你 現 在 是 一 個 新 創 公 司 的 資 深 產 品 經 理 , 正 在 發 想 一 個 創 新 的 。 公 司 目 前 專 注 於 解 決 年 輕 人 生 活 中 的 痛 點 。 你 的 任 務 是 提 出 一 個 新 的 點 子 , 並 說 明 其 核 心 功 能 、 目 標 用 戶 和 商 業 模 式 。 請 從 產 品 經 理 的 專 業 角 度 , 詳 細 闡 述 你 的 想 法 。 請 針 對 「 解 決 年 輕 人 獨 居 時 的 寂 寞 感 」 這 個 痛 點 , 提 出 一 個 產 品 提 案 。 結 果 可 能 只 是 個 結 論 , 但 是 這 樣 的 方 案 確 實 有 用 。 如 果 你 想 要 讓 自 己 的 產 出 能 夠 得 到 改 善 , 那 麼 這 種 做 法 就 是 可 行 的 。 首 先 , 你 需 要 做 的 是 : 解