科学论文通常难以理解,因为它们的结构复杂且文本较长,使我们难以找到切入点。幸运的是,我们可以使用语言模型对其进行摘要,从而简化阅读过程。
在本文中,我们将探讨如何使用 BART 模型对科学论文进行摘要。让我们开始吧!
准备工作
要跟随本教程,我们需要安装以下 Python 包:
pip install transformers pymupdf
然后,你需要安装适用于你环境的 PyTorch 包。安装完成后,我们将进入下一步。
使用 BART 进行科学论文摘要
BART(Bidirectional and Auto-Regressive Transformers,双向自回归变换器)是 Facebook(现称 Meta)开发的基于 Transformer 的神经网络模型,适用于诸如摘要生成等序列到序列(sequence-to-sequence)任务。
BART 的架构基于一个双向编码器(Bidirectional Encoder),用于理解输入文本内容,并使用一个自回归解码器(Autoregressive Decoder)来生成相关的输出序列。该模型经过训练,可以处理噪声输入文本,并学习如何基于这些输入重建原始文本。
由于 BART 擅长摘要任务,我们将尝试使用它来总结科学论文。本教程中,我们将使用 Attention Is All You Need 论文的 PDF 作为示例。
首先,让我们使用以下代码提取论文中的所有文本:
import fitz
def extract_paper_text(pdf_path): text = "" doc = fitz.open(pdf_path) for page in doc: text += page.get_text() return text
pdf_path = "attention_is_all_you_need.pdf"cleaned_text = extract_paper_text(pdf_path)
文本提取完成后,我们将其传递给 BART 模型进行摘要。以下代码将文本分割成小块进行摘要,并将所有摘要结果合并,以确保输出更加连贯。
from transformers import BartTokenizer, BartForConditionalGeneration
tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
def summarize_text(text, model, tokenizer, max_chunk_size=1024): chunks = [text[i:i+max_chunk_size] for i in range(0, len(text), max_chunk_size)] summaries = [] for chunk in chunks: inputs = tokenizer(chunk, max_length=max_chunk_size, return_tensors="pt", truncation=True) summary_ids = model.generate( inputs["input_ids"], max_length=200, min_length=50, length_penalty=2.0, num_beams=4, early_stopping=True ) summaries.append(tokenizer.decode(summary_ids[0], skip_special_tokens=True)) return " ".join(summaries)
summary = summarize_text(cleaned_text, model, tokenizer)
该方法会为每 1024 个单词的文本块生成约 200 个标记(tokens)的摘要。为了使摘要更加整洁,我们可以执行 分层摘要(Hierarchical Summarization),即对第一轮摘要结果再次进行摘要。
为此,我们可以使用以下代码:
def hierarchical_summarization(text, model, tokenizer, max_chunk_size=1024): first_level_summary = summarize_text(text, model, tokenizer, max_chunk_size) inputs = tokenizer(first_level_summary, max_length=max_chunk_size, return_tensors="pt", truncation=True) summary_ids = model.generate( inputs["input_ids"], max_length=200, min_length=50, length_penalty=2.0, num_beams=4, early_stopping=True ) final_summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True) return final_summary
final_summary = hierarchical_summarization(cleaned_text, model, tokenizer)
最终输出示例
The Transformer is the first transduction model relying solely on self-attention to compute representations. It can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs. The attention function can be described as mapping a query and a set of key-value pairs to an output.
该摘要很好地提炼了论文的核心内容。你可以调整文本块的大小,以进一步优化摘要质量。
希望这篇文章对你有所帮助!
领取专属 10元无门槛券
私享最新 技术干货