16.4. 自然语言推断和数据集
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 SageMaker Studio Lab 中打开 Notebook

第 16.1 节中,我们讨论了情感分析问题。 此任务旨在将单个文本序列分类到预定义的类别中,例如一组情感极性。 然而,当需要判断一个句子是否可以从另一个句子推断出来,或者通过识别语义上等效的句子来消除冗余时,仅仅知道如何对单个文本序列进行分类是不够的。 相反,我们需要能够对成对的文本序列进行推理。

16.4.1. 自然语言推断

自然语言推断研究一个假设是否可以从一个前提中推断出来,其中两者都是文本序列。 换句话说,自然语言推断决定了一对文本序列之间的逻辑关系。 这种关系通常分为三种类型:

  • 蕴涵(Entailment):假设可以从前提中推断出来。

  • 矛盾(Contradiction):假设的否定可以从前提中推断出来。

  • 中性(Neutral):所有其他情况。

自然语言推断也称为识别文本蕴涵任务。 例如,下面这对句子将被标记为蕴涵,因为假设中的“表达爱意”可以从前提中的“互相拥抱”推断出来。

前提:两个女人在互相拥抱。

假设:两个女人在表达爱意。

以下是一个矛盾的例子,因为“运行代码示例”表示“没有睡觉”,而不是“正在睡觉”。

前提:一个男人正在运行《动手学深度学习》中的代码示例。

假设:这个男人正在睡觉。

第三个例子显示了一种中性关系,因为无论是“出名”还是“不出名”都无法从“正在为我们表演”这一事实中推断出来。

前提:音乐家们正在为我们表演。

假设:音乐家们很有名。

自然语言推断一直是理解自然语言的核心课题。它在信息检索、开放域问答等领域有着广泛的应用。为了研究这个问题,我们将从一个流行的自然语言推断基准数据集开始。

16.4.2. 斯坦福自然语言推断(SNLI)数据集

斯坦福自然语言推断(SNLI)语料库是超过50万个带标签的英语句子对的集合 (Bowman et al., 2015)。 我们下载并存储提取的SNLI数据集在路径 ../data/snli_1.0 下。

import os
import re
import torch
from torch import nn
from d2l import torch as d2l

#@save
d2l.DATA_HUB['SNLI'] = (
    'https://nlp.stanford.edu/projects/snli/snli_1.0.zip',
    '9fcde07509c7e87ec61c640c1b2753d9041758e4')

data_dir = d2l.download_extract('SNLI')
import os
import re
from mxnet import gluon, np, npx
from d2l import mxnet as d2l

npx.set_np()

#@save
d2l.DATA_HUB['SNLI'] = (
    'https://nlp.stanford.edu/projects/snli/snli_1.0.zip',
    '9fcde07509c7e87ec61c640c1b2753d9041758e4')

data_dir = d2l.download_extract('SNLI')

16.4.2.1. 读取数据集

原始的SNLI数据集包含的信息比我们在实验中实际需要的要丰富得多。因此,我们定义了一个函数 read_snli 来仅提取数据集的一部分,然后返回前提、假设和它们的标签的列表。

#@save
def read_snli(data_dir, is_train):
    """Read the SNLI dataset into premises, hypotheses, and labels."""
    def extract_text(s):
        # Remove information that will not be used by us
        s = re.sub('\\(', '', s)
        s = re.sub('\\)', '', s)
        # Substitute two or more consecutive whitespace with space
        s = re.sub('\\s{2,}', ' ', s)
        return s.strip()
    label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}
    file_name = os.path.join(data_dir, 'snli_1.0_train.txt'
                             if is_train else 'snli_1.0_test.txt')
    with open(file_name, 'r') as f:
        rows = [row.split('\t') for row in f.readlines()[1:]]
    premises = [extract_text(row[1]) for row in rows if row[0] in label_set]
    hypotheses = [extract_text(row[2]) for row in rows if row[0] in label_set]
    labels = [label_set[row[0]] for row in rows if row[0] in label_set]
    return premises, hypotheses, labels
#@save
def read_snli(data_dir, is_train):
    """Read the SNLI dataset into premises, hypotheses, and labels."""
    def extract_text(s):
        # Remove information that will not be used by us
        s = re.sub('\\(', '', s)
        s = re.sub('\\)', '', s)
        # Substitute two or more consecutive whitespace with space
        s = re.sub('\\s{2,}', ' ', s)
        return s.strip()
    label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}
    file_name = os.path.join(data_dir, 'snli_1.0_train.txt'
                             if is_train else 'snli_1.0_test.txt')
    with open(file_name, 'r') as f:
        rows = [row.split('\t') for row in f.readlines()[1:]]
    premises = [extract_text(row[1]) for row in rows if row[0] in label_set]
    hypotheses = [extract_text(row[2]) for row in rows if row[0] in label_set]
    labels = [label_set[row[0]] for row in rows if row[0] in label_set]
    return premises, hypotheses, labels

现在让我们打印前3对前提和假设,以及它们的标签(“0”、“1”和“2”分别对应“蕴涵”、“矛盾”和“中性”)。

train_data = read_snli(data_dir, is_train=True)
for x0, x1, y in zip(train_data[0][:3], train_data[1][:3], train_data[2][:3]):
    print('premise:', x0)
    print('hypothesis:', x1)
    print('label:', y)
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is training his horse for a competition .
label: 2
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is at a diner , ordering an omelette .
label: 1
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is outdoors , on a horse .
label: 0
train_data = read_snli(data_dir, is_train=True)
for x0, x1, y in zip(train_data[0][:3], train_data[1][:3], train_data[2][:3]):
    print('premise:', x0)
    print('hypothesis:', x1)
    print('label:', y)
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is training his horse for a competition .
label: 2
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is at a diner , ordering an omelette .
label: 1
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is outdoors , on a horse .
label: 0

训练集大约有55万对,测试集大约有1万对。下面显示了“蕴涵”、“矛盾”和“中性”这三个标签在训练集和测试集中都是平衡的。

test_data = read_snli(data_dir, is_train=False)
for data in [train_data, test_data]:
    print([[row for row in data[2]].count(i) for i in range(3)])
[183416, 183187, 182764]
[3368, 3237, 3219]
test_data = read_snli(data_dir, is_train=False)
for data in [train_data, test_data]:
    print([[row for row in data[2]].count(i) for i in range(3)])
[183416, 183187, 182764]
[3368, 3237, 3219]

16.4.2.2. 定义一个用于加载数据集的类

下面我们定义一个用于加载SNLI数据集的类,通过继承Gluon中的 Dataset 类。类构造函数中的参数 num_steps 指定了文本序列的长度,以便每个小批量的序列具有相同的形状。换句话说,较长序列中超过前 num_steps 个词元的部分将被截断,而较短的序列将附加特殊词元“<pad>”,直到其长度变为 num_steps。通过实现 __getitem__ 函数,我们可以用索引 idx 任意访问前提、假设和标签。

#@save
class SNLIDataset(torch.utils.data.Dataset):
    """A customized dataset to load the SNLI dataset."""
    def __init__(self, dataset, num_steps, vocab=None):
        self.num_steps = num_steps
        all_premise_tokens = d2l.tokenize(dataset[0])
        all_hypothesis_tokens = d2l.tokenize(dataset[1])
        if vocab is None:
            self.vocab = d2l.Vocab(all_premise_tokens + all_hypothesis_tokens,
                                   min_freq=5, reserved_tokens=['<pad>'])
        else:
            self.vocab = vocab
        self.premises = self._pad(all_premise_tokens)
        self.hypotheses = self._pad(all_hypothesis_tokens)
        self.labels = torch.tensor(dataset[2])
        print('read ' + str(len(self.premises)) + ' examples')

    def _pad(self, lines):
        return torch.tensor([d2l.truncate_pad(
            self.vocab[line], self.num_steps, self.vocab['<pad>'])
                         for line in lines])

    def __getitem__(self, idx):
        return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]

    def __len__(self):
        return len(self.premises)
#@save
class SNLIDataset(gluon.data.Dataset):
    """A customized dataset to load the SNLI dataset."""
    def __init__(self, dataset, num_steps, vocab=None):
        self.num_steps = num_steps
        all_premise_tokens = d2l.tokenize(dataset[0])
        all_hypothesis_tokens = d2l.tokenize(dataset[1])
        if vocab is None:
            self.vocab = d2l.Vocab(all_premise_tokens + all_hypothesis_tokens,
                                   min_freq=5, reserved_tokens=['<pad>'])
        else:
            self.vocab = vocab
        self.premises = self._pad(all_premise_tokens)
        self.hypotheses = self._pad(all_hypothesis_tokens)
        self.labels = np.array(dataset[2])
        print('read ' + str(len(self.premises)) + ' examples')

    def _pad(self, lines):
        return np.array([d2l.truncate_pad(
            self.vocab[line], self.num_steps, self.vocab['<pad>'])
                         for line in lines])

    def __getitem__(self, idx):
        return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]

    def __len__(self):
        return len(self.premises)

16.4.2.3. 整合

现在我们可以调用 read_snli 函数和 SNLIDataset 类来下载SNLI数据集,并返回训练集和测试集的 DataLoader 实例,以及训练集的词汇表。值得注意的是,我们必须使用从训练集构建的词汇表作为测试集的词汇表。因此,来自测试集的任何新词元对于在训练集上训练的模型来说都是未知的。

#@save
def load_data_snli(batch_size, num_steps=50):
    """Download the SNLI dataset and return data iterators and vocabulary."""
    num_workers = d2l.get_dataloader_workers()
    data_dir = d2l.download_extract('SNLI')
    train_data = read_snli(data_dir, True)
    test_data = read_snli(data_dir, False)
    train_set = SNLIDataset(train_data, num_steps)
    test_set = SNLIDataset(test_data, num_steps, train_set.vocab)
    train_iter = torch.utils.data.DataLoader(train_set, batch_size,
                                             shuffle=True,
                                             num_workers=num_workers)
    test_iter = torch.utils.data.DataLoader(test_set, batch_size,
                                            shuffle=False,
                                            num_workers=num_workers)
    return train_iter, test_iter, train_set.vocab
#@save
def load_data_snli(batch_size, num_steps=50):
    """Download the SNLI dataset and return data iterators and vocabulary."""
    num_workers = d2l.get_dataloader_workers()
    data_dir = d2l.download_extract('SNLI')
    train_data = read_snli(data_dir, True)
    test_data = read_snli(data_dir, False)
    train_set = SNLIDataset(train_data, num_steps)
    test_set = SNLIDataset(test_data, num_steps, train_set.vocab)
    train_iter = gluon.data.DataLoader(train_set, batch_size, shuffle=True,
                                       num_workers=num_workers)
    test_iter = gluon.data.DataLoader(test_set, batch_size, shuffle=False,
                                      num_workers=num_workers)
    return train_iter, test_iter, train_set.vocab

这里我们将批量大小设置为128,序列长度设置为50,并调用 load_data_snli 函数来获取数据迭代器和词汇表。然后我们打印词汇表的大小。

train_iter, test_iter, vocab = load_data_snli(128, 50)
len(vocab)
read 549367 examples
read 9824 examples
18678
train_iter, test_iter, vocab = load_data_snli(128, 50)
len(vocab)
[22:09:03] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
read 549367 examples
read 9824 examples
18678

现在我们打印第一个小批量的形状。与情感分析相反,我们有两个输入 X[0]X[1],分别代表前提和假设对。

for X, Y in train_iter:
    print(X[0].shape)
    print(X[1].shape)
    print(Y.shape)
    break
torch.Size([128, 50])
torch.Size([128, 50])
torch.Size([128])
for X, Y in train_iter:
    print(X[0].shape)
    print(X[1].shape)
    print(Y.shape)
    break
(128, 50)
(128, 50)
(128,)

16.4.3. 小结

  • 自然语言推断研究一个假设是否可以从一个前提中推断出来,其中两者都是文本序列。

  • 在自然语言推断中,前提和假设之间的关系包括蕴涵、矛盾和中性。

  • 斯坦福自然语言推断(SNLI)语料库是自然语言推断的一个流行基准数据集。

16.4.4. 练习

  1. 长期以来,机器翻译的评估都是基于输出译文和标准译文之间表面的 \(n\)-gram 匹配。您能否设计一种利用自然语言推断来评估机器翻译结果的方法?

  2. 我们如何更改超参数以减小词汇表的大小?