🚀 使用HuggingFace Transformers進行摘要任務
本項目利用HuggingFace Transformers庫實現文本摘要任務,通過預訓練模型對輸入文本進行處理,生成相應的摘要內容。
🚀 快速開始
安裝依賴
確保你已經安裝了HuggingFace Transformers庫,可以使用以下命令進行安裝:
pip install transformers
代碼示例
以下是使用預訓練模型進行文本摘要的示例代碼:
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained("AlekseyKulnevich/Pegasus-Summarization")
tokenizer = AutoTokenizer.from_pretrained('google/pegasus-large')
input_text =
input_ = tokenizer.batch_encode_plus([input_text], max_length=1024, pad_to_max_length=True,
truncation=True, padding='longest', return_tensors='pt')
input_ids = input_['input_ids']
input_mask = input_['attention_mask']
summary = model.generate(input_ids=input_ids,
attention_mask=input_mask,
num_beams=32,
min_length=100,
no_repeat_ngram_size=2,
early_stopping=True,
num_return_sequences=10)
questions = tokenizer.batch_decode(summary, skip_special_tokens=True)
💻 使用示例
基礎用法
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained("AlekseyKulnevich/Pegasus-Summarization")
tokenizer = AutoTokenizer.from_pretrained('google/pegasus-large')
input_text =
input_ = tokenizer.batch_encode_plus([input_text], max_length=1024, pad_to_max_length=True,
truncation=True, padding='longest', return_tensors='pt')
input_ids = input_['input_ids']
input_mask = input_['attention_mask']
summary = model.generate(input_ids=input_ids,
attention_mask=input_mask,
num_beams=32,
min_length=100,
no_repeat_ngram_size=2,
early_stopping=True,
num_return_sequences=10)
questions = tokenizer.batch_decode(summary, skip_special_tokens=True)
高級用法
解碼器配置示例
你可以參考以下鏈接中的輸入文本進行測試:輸入文本示例
summary = model.generate(input_ids=input_ids,
attention_mask=input_mask,
num_beams=32,
min_length=100,
no_repeat_ngram_size=2,
early_stopping=True,
num_return_sequences=1)
tokenizer.batch_decode(summary, skip_special_tokens=True)
輸出示例:
- 根據政府間氣候變化專門委員會(IPCC)和美國國家海洋和大氣管理局(NOAA)發表的一項新研究,全球變暖將擴大熱帶氣旋在世界中緯度地區的活動範圍。該研究表明,氣候變暖將使這類風暴能夠在比過去300萬年更廣泛的範圍內形成。“隨著氣候變暖,這些風暴可能會變得更加頻繁和強烈,”該研究的作者說。
summary = model.generate(input_ids=input_ids,
attention_mask=input_mask,
top_k=30,
no_repeat_ngram_size=2,
early_stopping=True,
min_length=100,
num_return_sequences=1)
tokenizer.batch_decode(summary, skip_special_tokens=True)
輸出示例:
- 根據政府間氣候變化專門委員會(IPCC)發表的一項關於人類活動引起的氣候變化對風暴影響的新研究,世界中緯度地區的熱帶氣旋可能會形成更多這類風暴。該研究表明,氣候變暖將增加亞熱帶氣旋在比過去300萬年更廣泛的緯度範圍內形成的可能性,包括赤道地區,並且更有可能在熱帶地區形成。
你還可以在generate
方法中調整以下參數:
有關生成文本參數的含義,你可以參考:參數含義說明