自然语言推理和数据集
自然語(yǔ)言推理和數(shù)據(jù)集
Natural Language Inference and the Dataset
情緒分析的問(wèn)題。此任務(wù)旨在將單個(gè)文本序列分類(lèi)為預(yù)定義的類(lèi)別,例如一組情感極性。然而,當(dāng)需要判斷一個(gè)句子是否可以從另一個(gè)句子中推斷出來(lái),或者通過(guò)識(shí)別語(yǔ)義上等價(jià)的句子來(lái)消除冗余時(shí),知道如何對(duì)一個(gè)文本序列進(jìn)行分類(lèi)是不夠的。相反,需要能夠?qū)ξ谋拘蛄羞M(jìn)行推理。
- Natural Language Inference
自然語(yǔ)言推理研究一個(gè)假設(shè)是否可以從一個(gè)前提中推斷出來(lái),前提和前提都是文本序列。換句話(huà)說(shuō),自然語(yǔ)言推理決定了一對(duì)文本序列之間的邏輯關(guān)系。這種關(guān)系通常分為三類(lèi):
蘊(yùn)涵:假設(shè)可以從前提中推斷出來(lái)。
矛盾:假設(shè)的否定可以從前提推斷出來(lái)。
中立:所有其情況。
自然語(yǔ)言推理也被稱(chēng)為識(shí)別文本蘊(yùn)涵任務(wù)。例如,下面的一對(duì)會(huì)被標(biāo)記為蘊(yùn)涵,因?yàn)榧僭O(shè)中的“示愛(ài)”可以從前提中的“擁抱”中推斷出來(lái)。
前提:兩個(gè)女人互相擁抱。
假設(shè):兩個(gè)女人在表達(dá)愛(ài)意。
下面是一個(gè)矛盾的例子,因?yàn)椤斑\(yùn)行編碼示例”表示“不睡覺(jué)”而不是“睡眠”。
前提:一個(gè)男人正在運(yùn)行一個(gè)代碼示例,該示例來(lái)自于深度學(xué)習(xí)。
假設(shè):這個(gè)人正在睡覺(jué)。
第三個(gè)例子顯示了一種中立關(guān)系,因?yàn)椤盀檠莩觥钡氖聦?shí)不能推斷出“著名”和“不出名”。
前提:音樂(lè)家在為表演。
假設(shè):音樂(lè)家是有名的。
自然語(yǔ)言推理一直是理解自然語(yǔ)言的中心話(huà)題。在信息檢索、開(kāi)放領(lǐng)域問(wèn)答等領(lǐng)域有著廣泛的應(yīng)用。為了研究這個(gè)問(wèn)題,將從研究一個(gè)流行的自然語(yǔ)言推理基準(zhǔn)數(shù)據(jù)集開(kāi)始。
- The Stanford Natural Language Inference (SNLI) Dataset
斯坦福自然語(yǔ)言推理(SNLI)語(yǔ)料庫(kù)是一個(gè)50萬(wàn)標(biāo)記英語(yǔ)句子對(duì)【Bowman等人,2015年】。將提取的SNLI數(shù)據(jù)集下載并存儲(chǔ)在路徑…/data/SNLI_1.0中。
import collections
from d2l import mxnet as d2l
from mxnet import gluon, np, npx
import os
import re
import zipfile
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’)
Downloading …/data/snli_1.0.zip from https://nlp.stanford.edu/projects/snli/snli_1.0.zip…
2.1. Reading the Dataset
原始的SNLI數(shù)據(jù)集包含了比在實(shí)驗(yàn)中真正需要的更豐富的信息。因此,定義了一個(gè)函數(shù)read_snli來(lái)只提取部分?jǐn)?shù)據(jù)集,然后返回前提、假設(shè)及其標(biāo)簽的列表。
#@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 uss = re.sub('\\(', '', s)s = re.sub('\\)', '', s)# Substitute two or more consecutive whitespace with spaces = 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
現(xiàn)在讓打印第一個(gè)3對(duì)前提和假設(shè),以及標(biāo)簽(“0”、“1”和“2”分別對(duì)應(yīng)于“蘊(yùn)涵”、“矛盾”和“中性”)。
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
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)])
訓(xùn)練集有大約55萬(wàn)組,測(cè)試集有大約10000組。結(jié)果表明,在訓(xùn)練集和測(cè)試集中,“蘊(yùn)涵”、“矛盾”和“中性”三個(gè)標(biāo)簽是平衡的。
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]
2.2. Defining a Class for Loading the Dataset
下面定義了一個(gè)類(lèi),通過(guò)繼承Gluon中的dataset類(lèi)來(lái)加載SNLI數(shù)據(jù)集。類(lèi)構(gòu)造函數(shù)中的num_steps參數(shù)指定文本序列的長(zhǎng)度,以便每個(gè)序列的小批量都具有相同的形狀。換言之,第一個(gè)num_steps后面的標(biāo)記將被修剪,而特殊標(biāo)記“”將被附加到較短的序列中,直到長(zhǎng)度變?yōu)閚um_steps。通過(guò)實(shí)現(xiàn)the getitem function函數(shù),可以任意訪問(wèn)前提、假設(shè)和索引idx的標(biāo)簽。
#@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_stepsall_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 = vocabself.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)
2.3. Putting All Things Together
現(xiàn)在可以調(diào)用read_snli函數(shù)和SNLIDataset類(lèi)來(lái)下載snli數(shù)據(jù)集,并返回訓(xùn)練集和測(cè)試集的DataLoader實(shí)例以及訓(xùn)練集的詞匯表。值得注意的是,必須使用從測(cè)試中構(gòu)建的詞匯集。因此,來(lái)自測(cè)試集的任何新令牌對(duì)于訓(xùn)練集上訓(xùn)練的模型都是未知的。
#@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
這里將批量大小設(shè)置為128,序列長(zhǎng)度為50,并調(diào)用load_data_snli函數(shù)來(lái)獲取數(shù)據(jù)迭代器和詞匯表。然后打印出詞匯量。
train_iter, test_iter, vocab = load_data_snli(128, 50)
len(vocab)
read 549367 examples
read 9824 examples
18678
現(xiàn)在打印第一個(gè)小批量的形狀。與情緒分析相反,輸入X[0]和X[1]表示一對(duì)前提和假設(shè)。
for X, Y in train_iter:
print(X[0].shape)print(X[1].shape)print(Y.shape)break
(128, 50)
(128, 50)
(128,)
- Summary
· Natural language inference studies whether a hypothesis can be inferred from a premise, where both are a text sequence.
· In natural language inference, relationships between premises and hypotheses include entailment, contradiction, and neutral.
· Stanford Natural Language Inference (SNLI) Corpus is a popular benchmark dataset of natural language inference.
總結(jié)
以上是生活随笔為你收集整理的自然语言推理和数据集的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 情感分析:基于卷积神经网络
- 下一篇: 自然语言推理:使用注意力机制