文本摘要


观看原文配套视频

文本摘要将文档或文章变成更短的版本,同时保留所有重要信息。与翻译一样,它也是可以表述为序列到序列任务的一个例子。文本摘要可以分为:

  • 抽取式:从文档中提取最相关的信息。
  • 生成式:生成能够表达最相关信息的新文本。

本指南将介绍如何:

  1. 在 BillSum 数据集的加利福尼亚州法案子集上微调 T5,进行生成式摘要。
  2. 使用微调后的模型进行推理。

要查看与此任务兼容的所有架构和检查点,建议查看任务页面。

开始前,请确保已经安装所有必要的库:

pip install transformers datasets evaluate rouge_score

建议登录 Hugging Face 账号,以便上传模型并与社区分享。在提示时输入令牌完成登录:

>>> from huggingface_hub import notebook_login



>>> notebook_login()

加载 BillSum 数据集

首先,通过 Datasets 库加载较小的 BillSum 加利福尼亚州法案子集:

>>> from datasets import load_dataset



>>> billsum = load_dataset("billsum", split="ca_test")

使用 train_test_split 方法将数据集拆分为训练集和测试集:

>>> billsum = billsum.train_test_split(test_size=0.2)

然后查看一个示例:

>>> billsum["train"][0]

{'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\nThis bill would provide that no reimbursement is required by this act for a specified reason.',

 'text': 'The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n10295.35.\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee’s or dependent’s actual or perceived gender identity, including, but not limited to, the employee’s or dependent’s identification as transgender.\n(2) For purposes of this section, “contract” includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\n(4) The requirements of this section shall apply only to those portions of a contractor’s operations that occur under any of the following conditions:\n(A) Within the state.\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor’s presence at that location is connected to a contract with the state.\n(C) Elsewhere in the United States where work related to a state contract is being performed.\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.',

 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}

需要使用以下两个字段:

  • text:法案文本,作为模型的输入。
  • summary:text 的压缩版本,作为模型的目标输出。

预处理

下一步,加载 T5 分词器来处理 text 和 summary:

>>> from transformers import AutoTokenizer



>>> checkpoint = "google-t5/t5-small"

>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)

需要创建的预处理函数应完成以下工作:

  1. 为输入添加提示前缀,让 T5 知道这是摘要任务。有些能够执行多种自然语言处理任务的模型,需要针对具体任务提供提示。
  2. 对标签进行分词时,使用 text_target 关键字参数。
  3. 截断序列,使其长度不超过 max_length 参数设定的最大值。
>>> prefix = "summarize: "





>>> def preprocess_function(examples):

...     inputs = [prefix + doc for doc in examples["text"]]

...     model_inputs = tokenizer(inputs, max_length=1024, truncation=True)



...     labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True)



...     model_inputs["labels"] = labels["input_ids"]

...     return model_inputs

要对整个数据集应用预处理函数,使用 Datasets 的 map 方法。设置 batched=True 可以一次处理多个数据集元素,加快 map 函数的执行:

>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)

现在使用 DataCollatorForSeq2Seq 创建一批样本。在整理批次时,将句子动态填充到当前批次的最长长度,比将整个数据集填充到最大长度更高效。

>>> from transformers import DataCollatorForSeq2Seq



>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)

评估

在训练中加入评估指标,通常有助于评估模型表现。使用 Evaluate 库可以快速加载评估方法。针对本任务,加载 ROUGE 指标;有关加载和计算指标的方法,请参阅 Evaluate 快速导览:

>>> import evaluate



>>> rouge = evaluate.load("rouge")

然后创建一个函数,将预测结果和标签传给 compute,以计算 ROUGE 指标:

>>> import numpy as np





>>> def compute_metrics(eval_pred):

...     predictions, labels = eval_pred

...     decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)

...     labels = np.where(labels != -100, labels, tokenizer.pad_token_id)

...     decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)



...     result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)



...     prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]

...     result["gen_len"] = np.mean(prediction_lens)



...     return {k: round(v, 4) for k, v in result.items()}

现在 compute_metrics 函数已准备就绪,配置训练时还会用到它。

训练

如果你不熟悉使用 Trainer 微调模型,可以查看基础教程!

现在可以开始训练模型了!使用 AutoModelForSeq2SeqLM 加载 T5:

>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer



>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)

到这里,只剩下三个步骤:

  1. 在 Seq2SeqTrainingArguments 中定义训练超参数。唯一必需的参数是 output_dir,用来指定模型保存位置。设置 push_to_hub=True 会将模型推送到 Hub,上传前需要登录 Hugging Face。每个 epoch 结束时,Trainer 都会评估 ROUGE 指标并保存训练检查点。
  2. 将训练参数以及模型、数据集、分词器、数据整理器和 compute_metrics 函数传给 Seq2SeqTrainer。
  3. 调用 train() 微调模型。
>>> training_args = Seq2SeqTrainingArguments(

...     output_dir="my_awesome_billsum_model",

...     eval_strategy="epoch",

...     learning_rate=2e-5,

...     per_device_train_batch_size=16,

...     per_device_eval_batch_size=16,

...     weight_decay=0.01,

...     save_total_limit=3,

...     num_train_epochs=4,

...     predict_with_generate=True,

...     fp16=True, #change to bf16=True for XPU

...     push_to_hub=True,

... )



>>> trainer = Seq2SeqTrainer(

...     model=model,

...     args=training_args,

...     train_dataset=tokenized_billsum["train"],

...     eval_dataset=tokenized_billsum["test"],

...     processing_class=tokenizer,

...     data_collator=data_collator,

...     compute_metrics=compute_metrics,

... )



>>> trainer.train()

训练完成后,使用 push_to_hub() 方法将模型分享到 Hub,让所有人都能使用它:

>>> trainer.push_to_hub()

要了解更深入的摘要模型微调示例,请查看对应的 PyTorch notebook。

推理

现在模型已经微调完成,可以用它进行推理了!

准备一些希望生成摘要的文本。对于 T5,需要根据任务给输入添加前缀。针对摘要,应如下所示添加前缀:

>>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes."

对文本进行分词,并以 PyTorch 张量形式返回 input_ids:

>>> from transformers import AutoTokenizer



>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model")

>>> inputs = tokenizer(text, return_tensors="pt").input_ids

使用 generate() 方法生成摘要。关于不同的文本生成策略以及控制生成的参数,请查看 Text Generation API。

>>> from transformers import AutoModelForSeq2SeqLM



>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model")

>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)

将生成的 token ID 解码回文本:

>>> tokenizer.decode(outputs[0], skip_special_tokens=True)

'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.'

Update on GitHub


来源与许可

原文:Summarization。作者及权利人:Hugging Face Transformers 项目贡献者。中文翻译基于用户提供的完整原文缓存,代码和示例输出保留原文;本文未实际执行示例。

许可依据:Apache License 2.0。

原文引用链接

许可文本

Copyright 2018- The Hugging Face team. All rights reserved.

Apache License

Version 2.0, January 2004

http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

“License” shall mean the terms and conditions for use, reproduction,

and distribution as defined by Sections 1 through 9 of this document.

“Licensor” shall mean the copyright owner or entity authorized by

the copyright owner that is granting the License.

“Legal Entity” shall mean the union of the acting entity and all

other entities that control, are controlled by, or are under common

control with that entity. For the purposes of this definition,

“control” means (i) the power, direct or indirect, to cause the

direction or management of such entity, whether by contract or

otherwise, or (ii) ownership of fifty percent (50%) or more of the

outstanding shares, or (iii) beneficial ownership of such entity.

“You” (or “Your”) shall mean an individual or Legal Entity

exercising permissions granted by this License.

“Source” form shall mean the preferred form for making modifications,

including but not limited to software source code, documentation

source, and configuration files.

“Object” form shall mean any form resulting from mechanical

transformation or translation of a Source form, including but

not limited to compiled object code, generated documentation,

and conversions to other media types.

“Work” shall mean the work of authorship, whether in Source or

Object form, made available under the License, as indicated by a

copyright notice that is included in or attached to the work

(an example is provided in the Appendix below).

“Derivative Works” shall mean any work, whether in Source or Object

form, that is based on (or derived from) the Work and for which the

editorial revisions, annotations, elaborations, or other modifications

represent, as a whole, an original work of authorship. For the purposes

of this License, Derivative Works shall not include works that remain

separable from, or merely link (or bind by name) to the interfaces of,

the Work and Derivative Works thereof.

“Contribution” shall mean any work of authorship, including

the original version of the Work and any modifications or additions

to that Work or Derivative Works thereof, that is intentionally

submitted to Licensor for inclusion in the Work by the copyright owner

or by an individual or Legal Entity authorized to submit on behalf of

the copyright owner. For the purposes of this definition, “submitted”

means any form of electronic, verbal, or written communication sent

to the Licensor or its representatives, including but not limited to

communication on electronic mailing lists, source code control systems,

and issue tracking systems that are managed by, or on behalf of, the

Licensor for the purpose of discussing and improving the Work, but

excluding communication that is conspicuously marked or otherwise

designated in writing by the copyright owner as “Not a Contribution.”

“Contributor” shall mean Licensor and any individual or Legal Entity

on behalf of whom a Contribution has been received by Licensor and

subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of

this License, each Contributor hereby grants to You a perpetual,

worldwide, non-exclusive, no-charge, royalty-free, irrevocable

copyright license to reproduce, prepare Derivative Works of,

publicly display, publicly perform, sublicense, and distribute the

Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of

this License, each Contributor hereby grants to You a perpetual,

worldwide, non-exclusive, no-charge, royalty-free, irrevocable

(except as stated in this section) patent license to make, have made,

use, offer to sell, sell, import, and otherwise transfer the Work,

where such license applies only to those patent claims licensable

by such Contributor that are necessarily infringed by their

Contribution(s) alone or by combination of their Contribution(s)

with the Work to which such Contribution(s) was submitted. If You

institute patent litigation against any entity (including a

cross-claim or counterclaim in a lawsuit) alleging that the Work

or a Contribution incorporated within the Work constitutes direct

or contributory patent infringement, then any patent licenses

granted to You under this License for that Work shall terminate

as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the

Work or Derivative Works thereof in any medium, with or without

modifications, and in Source or Object form, provided that You

meet the following conditions:

(a) You must give any other recipients of the Work or

Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices

stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works

that You distribute, all copyright, patent, trademark, and

attribution notices from the Source form of the Work,

excluding those notices that do not pertain to any part of

the Derivative Works; and

(d) If the Work includes a “NOTICE” text file as part of its

distribution, then any Derivative Works that You distribute must

include a readable copy of the attribution notices contained

within such NOTICE file, excluding those notices that do not

pertain to any part of the Derivative Works, in at least one

of the following places: within a NOTICE text file distributed

as part of the Derivative Works; within the Source form or

documentation, if provided along with the Derivative Works; or,

within a display generated by the Derivative Works, if and

wherever such third-party notices normally appear. The contents

of the NOTICE file are for informational purposes only and

do not modify the License. You may add Your own attribution

notices within Derivative Works that You distribute, alongside

or as an addendum to the NOTICE text from the Work, provided

that such additional attribution notices cannot be construed

as modifying the License.

You may add Your own copyright statement to Your modifications and

may provide additional or different license terms and conditions

for use, reproduction, or distribution of Your modifications, or

for any such Derivative Works as a whole, provided Your use,

reproduction, and distribution of the Work otherwise complies with

the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,

any Contribution intentionally submitted for inclusion in the Work

by You to the Licensor shall be under the terms and conditions of

this License, without any additional terms or conditions.

Notwithstanding the above, nothing herein shall supersede or modify

the terms of any separate license agreement you may have executed

with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade

names, trademarks, service marks, or product names of the Licensor,

except as required for reasonable and customary use in describing the

origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or

agreed to in writing, Licensor provides the Work (and each

Contributor provides its Contributions) on an “AS IS” BASIS,

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or

implied, including, without limitation, any warranties or conditions

of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A

PARTICULAR PURPOSE. You are solely responsible for determining the

appropriateness of using or redistributing the Work and assume any

risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,

whether in tort (including negligence), contract, or otherwise,

unless required by applicable law (such as deliberate and grossly

negligent acts) or agreed to in writing, shall any Contributor be

liable to You for damages, including any direct, indirect, special,

incidental, or consequential damages of any character arising as a

result of this License or out of the use or inability to use the

Work (including but not limited to damages for loss of goodwill,

work stoppage, computer failure or malfunction, or any and all

other commercial damages or losses), even if such Contributor

has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing

the Work or Derivative Works thereof, You may choose to offer,

and charge a fee for, acceptance of support, warranty, indemnity,

or other liability obligations and/or rights consistent with this

License. However, in accepting such obligations, You may act only

on Your own behalf and on Your sole responsibility, not on behalf

of any other Contributor, and only if You agree to indemnify,

defend, and hold each Contributor harmless for any liability

incurred by, or claims asserted against, such Contributor by reason

of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following

boilerplate notice, with the fields enclosed by brackets “[]”

replaced with your own identifying information. (Don’t include

the brackets!) The text should be enclosed in the appropriate

comment syntax for the file format. We also recommend that a

file or class name and description of purpose be included on the

same “printed page” as the copyright notice for easier

identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the “License”);

you may not use this file except in compliance with the License.

You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software

distributed under the License is distributed on an “AS IS” BASIS,

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and

limitations under the License.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容