Transformers 文档

TAPEX

TAPEX

此模型仅处于维护模式,我们不接受任何更改其代码的新PR。

如果您在运行此模型时遇到任何问题,请重新安装支持此模型的最后一个版本:v4.30.0。 您可以通过运行以下命令来执行此操作:pip install -U transformers==4.30.0

概述

TAPEX模型由Qian Liu、Bei Chen、Jiaqi Guo、Morteza Ziyadi、Zeqi Lin、Weizhu Chen、Jian-Guang Lou在TAPEX: Table Pre-training via Learning a Neural SQL Executor中提出。TAPEX通过解决合成的SQL查询来预训练一个BART模型,之后可以对其进行微调,以回答与表格数据相关的自然语言问题,以及执行表格事实检查。

TAPEX 已经在多个数据集上进行了微调:

  • SQA (微软的顺序问答)
  • WTQ (斯坦福大学的维基表格问题)
  • WikiSQL (由Salesforce提供)
  • TabFact (由USCB NLP实验室提供).

论文的摘要如下:

语言模型预训练的最新进展通过利用大规模非结构化文本数据取得了巨大成功。然而,由于缺乏大规模高质量的结构化表格数据,在结构化表格数据上应用预训练仍然是一个挑战。在本文中,我们提出了TAPEX,通过在一个合成语料库上学习神经SQL执行器来展示表格预训练的可能性,该语料库是通过自动合成可执行的SQL查询及其执行输出获得的。TAPEX通过引导语言模型在多样化、大规模和高质量的合成语料库上模仿SQL执行器,解决了数据稀缺的挑战。我们在四个基准数据集上评估了TAPEX。实验结果表明,TAPEX大幅超越了之前的表格预训练方法,并在所有这些数据集上取得了新的最先进结果。这包括将弱监督的WikiSQL表示准确率提高到89.5%(+2.3%),WikiTableQuestions表示准确率提高到57.5%(+4.8%),SQA表示准确率提高到74.5%(+3.5%),以及TabFact准确率提高到84.2%(+3.2%)。据我们所知,这是第一个通过合成可执行程序进行表格预训练并在各种下游任务中取得新的最先进结果的工作。

使用提示

  • TAPEX 是一个生成式(seq2seq)模型。可以直接将 TAPEX 的权重插入到 BART 模型中。
  • TAPEX在hub上有检查点,这些检查点要么是仅预训练的,要么是在WTQ、SQA、WikiSQL和TabFact上微调的。
  • 句子和表格以sentence + " " + linearized table的形式呈现给模型。线性化表格的格式如下: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
  • TAPEX 有自己的分词器,可以轻松为模型准备所有数据。可以将 Pandas DataFrames 和字符串传递给分词器,它会自动创建 input_idsattention_mask(如下面的使用示例所示)。

用法:推理

下面,我们展示了如何使用TAPEX进行表格问答。可以看到,可以直接将TAPEX的权重插入到BART模型中。 我们使用Auto API,它将根据hub上检查点的配置文件自动实例化适当的tokenizer(TapexTokenizer)和模型(BartForConditionalGeneration)。

>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
>>> import pandas as pd

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-wtq")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/tapex-large-finetuned-wtq")

>>> # prepare table + question
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
>>> table = pd.DataFrame.from_dict(data)
>>> question = "how many movies does Leonardo Di Caprio have?"

>>> encoding = tokenizer(table, question, return_tensors="pt")

>>> # let the model generate an answer autoregressively
>>> outputs = model.generate(**encoding)

>>> # decode back to text
>>> predicted_answer = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
>>> print(predicted_answer)
53

请注意,TapexTokenizer 也支持批量推理。因此,可以提供一批不同的表格/问题,或者一批单个表格和多个问题,或者一批单个查询和多个表格。让我们来说明这一点:

>>> # prepare table + question
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
>>> table = pd.DataFrame.from_dict(data)
>>> questions = [
...     "how many movies does Leonardo Di Caprio have?",
...     "which actor has 69 movies?",
...     "what's the first name of the actor who has 87 movies?",
... ]
>>> encoding = tokenizer(table, questions, padding=True, return_tensors="pt")

>>> # let the model generate an answer autoregressively
>>> outputs = model.generate(**encoding)

>>> # decode back to text
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
[' 53', ' george clooney', ' brad pitt']

如果某人想要进行表格验证(即确定给定句子是否被表格内容支持或反驳的任务),可以实例化一个BartForSequenceClassification模型。TAPEX在TabFact上微调的检查点位于hub上,TabFact是表格事实检查的一个重要基准(它达到了84%的准确率)。下面的代码示例再次利用了Auto API

>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-tabfact")
>>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/tapex-large-finetuned-tabfact")

>>> # prepare table + sentence
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
>>> table = pd.DataFrame.from_dict(data)
>>> sentence = "George Clooney has 30 movies"

>>> encoding = tokenizer(table, sentence, return_tensors="pt")

>>> # forward pass
>>> outputs = model(**encoding)

>>> # print prediction
>>> predicted_class_idx = outputs.logits[0].argmax(dim=0).item()
>>> print(model.config.id2label[predicted_class_idx])
Refused

TAPEX架构与BART相同,除了分词部分。有关配置类及其参数的信息,请参阅BART文档。下面记录了TAPEX特定的分词器。

TapexTokenizer

transformers.TapexTokenizer

< >

( vocab_file merges_file do_lower_case = True errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' mask_token = '' add_prefix_space = False max_cell_length = 15 **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件的路径。
  • do_lower_case (bool, optional, defaults to True) — 是否在分词时将输入转换为小写。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • sep_token (str, optional, defaults to "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, 可选, 默认为 "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在批处理不同长度的序列时使用。
  • mask_token (str, 可选, 默认为 "") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(BART 分词器通过前面的空格检测词的开头)。
  • max_cell_length (int, 可选, 默认为 15) — 表格线性化时每个单元格的最大字符数。如果超过此数字,将进行截断。

构建一个TAPEX分词器。基于字节级的字节对编码(BPE)。

此分词器可用于展平一个或多个表,并将它们与一个或多个相关句子连接起来,以供TAPEX模型使用。TAPEX分词器创建的格式如下:

句子列:col1 | col2 | col 3 行 1:val1 | val2 | val3 行 2:…

分词器支持单个表+单个查询、单个表和多个查询(在这种情况下,表将为每个查询复制)、单个查询和多个表(在这种情况下,查询将为每个表复制)以及多个表和查询。换句话说,你可以提供一批表+问题给分词器,例如为模型准备它们。

分词本身基于BPE算法。它与BART、RoBERTa和GPT-2使用的算法相同。

此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

__call__

< >

( table: typing.Union[ForwardRef('pd.DataFrame'), typing.List[ForwardRef('pd.DataFrame')]] = None query: typing.Union[str, typing.List[str], NoneType] = None answer: typing.Union[str, typing.List[str]] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 pad_to_multiple_of: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs )

参数

  • table (pd.DataFrame, List[pd.DataFrame]) — 包含表格数据的表(s)。
  • query (strList[str], 可选) — 与一个或多个表相关的句子或句子批次进行编码。请注意,句子的数量必须与表的数量匹配。
  • 答案 (strList[str], 可选) — 可选的,作为监督的问题对应的答案。
  • add_special_tokens (bool, optional, defaults to True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果您想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — 激活并控制填充。接受以下值:
    • True'longest': 填充到批次中最长的序列(如果只提供一个序列,则不进行填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认): 不进行填充(即,可以输出具有不同长度序列的批次)。
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分成单词)。如果设置为 True,分词器会假设输入已经分成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应应用填充的一侧。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • add_special_tokens (bool, optional, defaults to True) — 是否使用与模型相关的特殊标记对序列进行编码。
  • padding (bool, str or PaddingStrategy, optional, 默认为 False) — 激活并控制填充。接受以下值:
    • True'longest': 填充到批次中最长的序列(如果只提供一个序列,则不进行填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认): 不进行填充(即,可以输出具有不同长度序列的批次)。
  • truncation (bool, str, TapexTruncationStrategy or TruncationStrategy, — optional, defaults to False):

    激活并控制截断。接受以下值:

    • 'drop_rows_to_fit': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate row by row, removing rows from the table.
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, 可选) — 控制由截断/填充参数之一使用的最大长度。如果未设置或设置为 None,则在需要最大长度的情况下,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet), 则截断/填充到最大长度的功能将被停用。
  • stride (int, optional, defaults to 0) — 如果与max_length一起设置为一个数字,当return_overflowing_tokens=True时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。

用于将模型中的一个或多个表序列对进行标记化和准备的主要方法。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

< > Update on GitHub