Transformers预训练模型使用:文本摘要 Summarization

文本摘要是一个将一个文档或文章总结成一小段文字的任务。

一个文本摘要任务的数据集叫CNN / Daily Mail dataset,包含长新闻文章和其对应的摘要。

使用pipeline

同样,我们可以使用pipeline快速实现文本摘要。下面使用的是一个用CNN / Daily Mail dataset微调BERT的模型样例。

示例代码:

from transformers import pipeline

summarizer = pipeline("summarization")

ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.
"""
print(summarizer(ARTICLE, max_length=130, min_length=30, do_sample=False))

运行结果:

[{'summary_text': 'Liana Barrientos, 39, is charged with two counts of "offering a false instrument for filing in the first degree" In total, she has been married 10 times, with nine of her marriages occurring between 1999 and 2002. She is believed to still be married to four men.'}]

使用模型和文本标记器

步骤如下,使用google的T5模型:

  1. 实例化预训练模型和对应文本标记器。文本摘要一般使用BERTT5模型。
  2. 定义需要进行摘要的文本。
  3. 在文本前面加上T5的特有标记summarize:
  4. 使用PreTrainedModel.generate()方法来生成摘要。

示例代码:

cache_dir="./transformersModels/summarization"
"""
,cache_dir = cache_dir
"""
from transformers import AutoModelWithLMHead, AutoTokenizer

model = AutoModelWithLMHead.from_pretrained("t5-base", return_dict=True,cache_dir = cache_dir)
tokenizer = AutoTokenizer.from_pretrained("t5-base",cache_dir = cache_dir)
ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.
"""
# T5 uses a max_length of 512 so we cut the article to 512 tokens.
inputs = tokenizer.encode("summarize: " + ARTICLE, return_tensors="pt", max_length=512)
outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)
print(tokenizer.decode(outputs[0]))

运行结果:

prosecutors say the marriages were part of an immigration scam. if convicted, barrientos faces two criminal counts of "offering a false instrument for filing in the first degree" she has been married 10 times, nine of them between 1999 and 2002.
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用BERT预训练模型进行中文文本分类是一种常见的应用。下面我将以基于PyTorch的方式进行介绍。 步骤一:准备数据 首先,我们需要准备用于训练和测试的文本数据集。可以选择一个适合任务的中文文本分类数据集,例如THUCNews等。将数据集划分为训练集和测试集。 步骤二:安装和导入依赖 在使用PyTorch进行BERT模型的文本分类之前,需要安装相关的软件包。首先安装transformers库,该库提供了许多预训练的BERT模型。另外,还需要安装torch和tqdm库用于训练和进度条显示。 步骤三:加载预训练模型 使用transformers库加载预训练的中文BERT模型,例如'bert-base-chinese'。可以通过以下代码进行加载: ``` from transformers import BertTokenizer, BertForSequenceClassification # 加载预训练模型 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertForSequenceClassification.from_pretrained('bert-base-chinese', num_labels=num_labels) ``` 这里需要根据具体的文本分类任务设置num_labels参数,表示分类的类别数。 步骤四:预处理数据 对训练集和测试集的文本进行预处理。这包括将文本转换为BERT模型所需的输入格式,即将文本转化为token ids,并将文本序列padding到相同的长度。 步骤五:定义训练和评估循环 定义训练和评估模型的循环。在每个训练batch中,将输入传递给BERT模型,获取模型的预测结果。然后计算损失并进行反向传播优化模型参数。 步骤六:训练模型 使用准备好的训练集对模型进行训练。根据任务需要选择合适的优化器和学习率,设置训练的epochs和batch size等参数。在训练过程中,可以通过打印损失和精度等指标来监控训练进展。 步骤七:评估模型 使用准备好的测试集对训练好的模型进行评估。计算模型在测试集上的准确率、精确率、召回率等指标,以评估模型的性能。 步骤八:保存和加载模型 可以选择保存训练好的模型以备后续使用。可以使用torch.save方法保存模型,并使用torch.load方法加载模型。 使用BERT预训练模型进行中文文本分类可以较好地捕捉词义和语义的特征,提升分类任务的性能。通过以上步骤,可以实现一个简单的中文文本分类模型。当然,根据实际需求,还可以进行模型调优、模型融合等进一步的优化操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值