10.12 机器翻译
机器翻译是指将一段文本从一种语言自动翻译到另一种语言。因为一段文本序列在不同语言中的长度不一定相同,所以我们使用机器翻译为例来介绍编码器—解码器和注意力机制的应用。
10.12.1 读取和预处理数据
我们先定义一些特殊符号。其中“<pad>”(padding)符号用来添加在较短序列后,直到每个序列等长,而“<bos>”和“<eos>”符号分别表示序列的开始和结束。
!tar -xf d2lzh_pytorch.tar
import collections
import os
import io
import math
import torch
from torch import nn
import torch.nn.functional as F
import torchtext.vocab as Vocab
import torch.utils.data as Data
import sys
# sys.path.append("..")
import d2lzh_pytorch as d2l
PAD, BOS, EOS = '<pad>', '<bos>', '<eos>'
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(torch.__version__, device)
1.5.0 cpu
接着定义两个辅助函数对后面读取的数据进行预处理。
# 将一个序列中所有的词记录在all_tokens中以便之后构造词典,然后在该序列后面添加PAD直到序列
# 长度变为max_seq_len,然后将序列保存在all_seqs中
def process_one_seq(seq_tokens, all_tokens, all_seqs, max_seq_len):
all_tokens.extend(seq_tokens)
seq_tokens += [EOS] + [PAD] * (max_seq_len - len(seq_tokens) - 1)
all_seqs.append(seq_tokens)
# 使用所有的词来构造词典。并将所有序列中的词变换为词索引后构造Tensor
def build_data(all_tokens, all_seqs):
vocab = Vocab.Vocab(collections.Counter(all_tokens),
specials=[PAD, BOS, EOS])
indices = [[vocab.stoi[w] for w in seq] for seq in all_seqs]
return vocab, torch.tensor(indices)
为了演示方便,我们在这里使用一个很小的法语—英语数据集。在这个数据集里,每一行是一对法语句子和它对应的英语句子,中间使用'\t'
隔开。在读取数据时,我们在句末附上“<eos>”符号,并可能通过添加“<pad>”符号使每个序列的长度均为max_seq_len
。我们为法语词和英语词分别创建词典。法语词的索引和英语词的索引相互独立。
def read_data(max_seq_len):
# in和out分别是input和output的缩写
in_tokens, out_tokens, in_seqs, out_seqs = [], [], [], []
with io.open('fr-en-small.txt') as f:
lines = f.readlines()
for line in lines:
in_seq, out_seq = line.rstrip().split('\t')
in_seq_tokens, out_seq_tokens = in_seq.split(' '), out_seq.split(' ')
if max(len(in_seq_tokens), len(out_seq_tokens)) > max_seq_len - 1:
continue # 如果加上EOS后长于max_seq_len,则忽略掉此样本
process_one_seq(in_seq_tokens, in_tokens, in_seqs, max_seq_len)
process_one_seq(out_seq_tokens, out_tokens, out_seqs, max_seq_len)
in_vocab, in_data = build_data(in_tokens, in_seqs)
out_vocab, out_data = build_data(out_tokens, out_seqs)
return in_vocab, out_vocab, Data.TensorDataset(in_data, out_data)
将序列的最大长度设成7,然后查看读取到的第一个样本。该样本分别包含法语词索引序列和英语词索引序列。
max_seq_len = 7
in_vocab, out_vocab, dataset = read_data(max_seq_len)
dataset[0]
(tensor([ 5, 4, 45, 3, 2, 0, 0]), tensor([ 8, 4, 27, 3, 2, 0, 0]))
10.12.2 含注意力机制的编码器—解码器
我们将使用含注意力机制的编码器—解码器来将一段简短的法语翻译成英语。下面我们来介绍模型的实现。
10.12.2.1 编码器
在编码器中,我们将输入语言的词索引通过词嵌入层得到词的表征,然后输入到一个多层门控循环单元中。正如我们在6.5节(循环神经网络的简洁实现)中提到的,PyTorch的nn.GRU
实例在前向计算后也会分别返回输出和最终时间步的多层隐藏状态。其中的输出指的是最后一层的隐藏层在各个时间步的隐藏状态,并不涉及输出层计算。注意力机制将这些输出作为键项和值项。
class Encoder(nn.Module):
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
drop_prob=0, **kwargs):
super(Encoder, self).__init__(**kwargs)
self.embedding = nn.Embedding(vocab_size, embed_size)
self.rnn = nn.GRU(embed_size, num_hiddens, num_layers, dropout=drop_prob)
def forward(self, inputs, state):
# 输入形状是(批量大小, 时间步数)。将输出互换样本维和时间步维
embedding = self.embedding(inputs.long()).permute(1, 0, 2) # (seq_len, batch, input_size)
return self.rnn(embedding, state)
def begin_state(self):
return None
下面我们来创建一个批量大小为4、时间步数为7的小批量序列输入。设门控循环单元的隐藏层个数为2,隐藏单元个数为16。编码器对该输入执行前向计算后返回的输出形状为(时间步数, 批量大小, 隐藏单元个数)。门控循环单元在最终时间步的多层隐藏状态的形状为(隐藏层个数, 批量大小, 隐藏单元个数)。对于门控循环单元来说,state
就是一个元素,即隐藏状态;如果使用长短期记忆,state
是一个元组,包含两个元素即隐藏状态和记忆细胞。
encoder = Encoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)
output, state = encoder(torch.zeros((4, 7)), encoder.begin_state())
output.shape, state.shape # GRU的state是h, 而LSTM的是一个元组(h, c)
(torch.Size([7, 4, 16]), torch.Size([2, 4, 16]))
10.12.2.2 注意力机制
我们将实现10.11节(注意力机制)中定义的函数
a
a
a:将输入连结后通过含单隐藏层的多层感知机变换。其中隐藏层的输入是解码器的隐藏状态与编码器在所有时间步上隐藏状态的一一连结,且使用tanh函数作为激活函数。输出层的输出个数为1。两个Linear
实例均不使用偏差。其中函数
a
a
a定义里向量
v
\boldsymbol{v}
v的长度是一个超参数,即attention_size
。
def attention_model(input_size, attention_size):
model = nn.Sequential(nn.Linear(input_size, attention_size, bias=False),
nn.Tanh(),
nn.Linear(attention_size, 1, bias=False))
return model
注意力机制的输入包括查询项、键项和值项。设编码器和解码器的隐藏单元个数相同。这里的查询项为解码器在上一时间步的隐藏状态,形状为(批量大小, 隐藏单元个数);键项和值项均为编码器在所有时间步的隐藏状态,形状为(时间步数, 批量大小, 隐藏单元个数)。注意力机制返回当前时间步的背景变量,形状为(批量大小, 隐藏单元个数)。
def attention_forward(model, enc_states, dec_state):
"""
enc_states: (时间步数, 批量大小, 隐藏单元个数)
dec_state: (批量大小, 隐藏单元个数)
"""
# 将解码器隐藏状态广播到和编码器隐藏状态形状相同后进行连结
dec_states = dec_state.unsqueeze(dim=0).expand_as(enc_states)
enc_and_dec_states = torch.cat((enc_states, dec_states), dim=2)
e = model(enc_and_dec_states) # 形状为(时间步数, 批量大小, 1)
alpha = F.softmax(e, dim=0) # 在时间步维度做softmax运算
return (alpha * enc_states).sum(dim=0) # 返回背景变量
在下面的例子中,编码器的时间步数为10,批量大小为4,编码器和解码器的隐藏单元个数均为8。注意力机制返回一个小批量的背景向量,每个背景向量的长度等于编码器的隐藏单元个数。因此输出的形状为(4, 8)。
seq_len, batch_size, num_hiddens = 10, 4, 8
model = attention_model(2*num_hiddens, 10)
enc_states = torch.zeros((seq_len, batch_size, num_hiddens))
dec_state = torch.zeros((batch_size, num_hiddens))
attention_forward(model, enc_states, dec_state).shape
torch.Size([4, 8])
10.12.2.3 含注意力机制的解码器
我们直接将编码器在最终时间步的隐藏状态作为解码器的初始隐藏状态。这要求编码器和解码器的循环神经网络使用相同的隐藏层个数和隐藏单元个数。
在解码器的前向计算中,我们先通过刚刚介绍的注意力机制计算得到当前时间步的背景向量。由于解码器的输入来自输出语言的词索引,我们将输入通过词嵌入层得到表征,然后和背景向量在特征维连结。我们将连结后的结果与上一时间步的隐藏状态通过门控循环单元计算出当前时间步的输出与隐藏状态。最后,我们将输出通过全连接层变换为有关各个输出词的预测,形状为(批量大小, 输出词典大小)。
class Decoder(nn.Module):
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
attention_size, drop_prob=0):
super(Decoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, embed_size)
self.attention = attention_model(2*num_hiddens, attention_size)
# GRU的输入包含attention输出的c和实际输入, 所以尺寸是 num_hiddens+embed_size
self.rnn = nn.GRU(num_hiddens + embed_size, num_hiddens,
num_layers, dropout=drop_prob)
self.out = nn.Linear(num_hiddens, vocab_size)
def forward(self, cur_input, state, enc_states):
"""
cur_input shape: (batch, )
state shape: (num_layers, batch, num_hiddens)
"""
# 使用注意力机制计算背景向量
c = attention_forward(self.attention, enc_states, state[-1])
# 将嵌入后的输入和背景向量在特征维连结, (批量大小, num_hiddens+embed_size)
input_and_c = torch.cat((self.embedding(cur_input), c), dim=1)
# 为输入和背景向量的连结增加时间步维,时间步个数为1
output, state = self.rnn(input_and_c.unsqueeze(0), state)
# 移除时间步维,输出形状为(批量大小, 输出词典大小)
output = self.out(output).squeeze(dim=0)
return output, state
def begin_state(self, enc_state):
# 直接将编码器最终时间步的隐藏状态作为解码器的初始隐藏状态
return enc_state
10.12.3 训练模型
我们先实现batch_loss
函数计算一个小批量的损失。解码器在最初时间步的输入是特殊字符BOS
。之后,解码器在某时间步的输入为样本输出序列在上一时间步的词,即强制教学。此外,同10.3节(word2vec的实现)中的实现一样,我们在这里也使用掩码变量避免填充项对损失函数计算的影响。
def batch_loss(encoder, decoder, X, Y, loss):
batch_size = X.shape[0]
enc_state = encoder.begin_state()
enc_outputs, enc_state = encoder(X, enc_state)
# 初始化解码器的隐藏状态
dec_state = decoder.begin_state(enc_state)
# 解码器在最初时间步的输入是BOS
dec_input = torch.tensor([out_vocab.stoi[BOS]] * batch_size)
# 我们将使用掩码变量mask来忽略掉标签为填充项PAD的损失, 初始全1
mask, num_not_pad_tokens = torch.ones(batch_size,), 0
l = torch.tensor([0.0])
for y in Y.permute(1,0): # Y shape: (batch, seq_len)
dec_output, dec_state = decoder(dec_input, dec_state, enc_outputs)
l = l + (mask * loss(dec_output, y)).sum()
dec_input = y # 使用强制教学
num_not_pad_tokens += mask.sum().item()
# EOS后面全是PAD. 下面一行保证一旦遇到EOS接下来的循环中mask就一直是0
mask = mask * (y != out_vocab.stoi[EOS]).float()
return l / num_not_pad_tokens
在训练函数中,我们需要同时迭代编码器和解码器的模型参数。
def train(encoder, decoder, dataset, lr, batch_size, num_epochs):
enc_optimizer = torch.optim.Adam(encoder.parameters(), lr=lr)
dec_optimizer = torch.optim.Adam(decoder.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction='none')
data_iter = Data.DataLoader(dataset, batch_size, shuffle=True)
for epoch in range(num_epochs):
l_sum = 0.0
for X, Y in data_iter:
enc_optimizer.zero_grad()
dec_optimizer.zero_grad()
l = batch_loss(encoder, decoder, X, Y, loss)
l.backward()
enc_optimizer.step()
dec_optimizer.step()
l_sum += l.item()
if (epoch + 1) % 10 == 0:
print("epoch %d, loss %.3f" % (epoch + 1, l_sum / len(data_iter)))
接下来,创建模型实例并设置超参数。然后,我们就可以训练模型了。
embed_size, num_hiddens, num_layers = 64, 64, 2
attention_size, drop_prob, lr, batch_size, num_epochs = 10, 0.5, 0.01, 2, 50
encoder = Encoder(len(in_vocab), embed_size, num_hiddens, num_layers,
drop_prob)
decoder = Decoder(len(out_vocab), embed_size, num_hiddens, num_layers,
attention_size, drop_prob)
train(encoder, decoder, dataset, lr, batch_size, num_epochs)
epoch 10, loss 0.442
epoch 20, loss 0.229
epoch 30, loss 0.140
epoch 40, loss 0.064
epoch 50, loss 0.064
10.12.4 预测不定长的序列
在10.10节(束搜索)中我们介绍了3种方法来生成解码器在每个时间步的输出。这里我们实现最简单的贪婪搜索。
def translate(encoder, decoder, input_seq, max_seq_len):
in_tokens = input_seq.split(' ')
in_tokens += [EOS] + [PAD] * (max_seq_len - len(in_tokens) - 1)
enc_input = torch.tensor([[in_vocab.stoi[tk] for tk in in_tokens]]) # batch=1
enc_state = encoder.begin_state()
enc_output, enc_state = encoder(enc_input, enc_state)
dec_input = torch.tensor([out_vocab.stoi[BOS]])
dec_state = decoder.begin_state(enc_state)
output_tokens = []
for _ in range(max_seq_len):
dec_output, dec_state = decoder(dec_input, dec_state, enc_output)
pred = dec_output.argmax(dim=1)
pred_token = out_vocab.itos[int(pred.item())]
if pred_token == EOS: # 当任一时间步搜索出EOS时,输出序列即完成
break
else:
output_tokens.append(pred_token)
dec_input = pred
return output_tokens
简单测试一下模型。输入法语句子“ils regardent.”,翻译后的英语句子应该是“they are watching.”。
input_seq = 'ils regardent .'
translate(encoder, decoder, input_seq, max_seq_len)
['they', 'are', 'watching', '.']
10.12.5 评价翻译结果
评价机器翻译结果通常使用BLEU(Bilingual Evaluation Understudy)[1]。对于模型预测序列中任意的子序列,BLEU考察这个子序列是否出现在标签序列中。
具体来说,设词数为 n n n的子序列的精度为 p n p_n pn。它是预测序列与标签序列匹配词数为 n n n的子序列的数量与预测序列中词数为 n n n的子序列的数量之比。举个例子,假设标签序列为 A A A、 B B B、 C C C、 D D D、 E E E、 F F F,预测序列为 A A A、 B B B、 B B B、 C C C、 D D D,那么 p 1 = 4 / 5 , p 2 = 3 / 4 , p 3 = 1 / 3 , p 4 = 0 p_1 = 4/5, p_2 = 3/4, p_3 = 1/3, p_4 = 0 p1=4/5,p2=3/4,p3=1/3,p4=0。设 l e n label len_{\text{label}} lenlabel和 l e n pred len_{\text{pred}} lenpred分别为标签序列和预测序列的词数,那么,BLEU的定义为
exp ( min ( 0 , 1 − l e n label l e n pred ) ) ∏ n = 1 k p n 1 / 2 n , \exp\left(\min\left(0, 1 - \frac{len_{\text{label}}}{len_{\text{pred}}}\right)\right) \prod_{n=1}^k p_n^{1/2^n}, exp(min(0,1−lenpredlenlabel))n=1∏kpn1/2n,
其中 k k k是我们希望匹配的子序列的最大词数。可以看到当预测序列和标签序列完全一致时,BLEU为1。
因为匹配较长子序列比匹配较短子序列更难,BLEU对匹配较长子序列的精度赋予了更大权重。例如,当 p n p_n pn固定在0.5时,随着 n n n的增大, 0. 5 1 / 2 ≈ 0.7 , 0. 5 1 / 4 ≈ 0.84 , 0. 5 1 / 8 ≈ 0.92 , 0. 5 1 / 16 ≈ 0.96 0.5^{1/2} \approx 0.7, 0.5^{1/4} \approx 0.84, 0.5^{1/8} \approx 0.92, 0.5^{1/16} \approx 0.96 0.51/2≈0.7,0.51/4≈0.84,0.51/8≈0.92,0.51/16≈0.96。另外,模型预测较短序列往往会得到较高 p n p_n pn值。因此,上式中连乘项前面的系数是为了惩罚较短的输出而设的。举个例子,当 k = 2 k=2 k=2时,假设标签序列为 A A A、 B B B、 C C C、 D D D、 E E E、 F F F,而预测序列为 A A A、 B B B。虽然 p 1 = p 2 = 1 p_1 = p_2 = 1 p1=p2=1,但惩罚系数 exp ( 1 − 6 / 2 ) ≈ 0.14 \exp(1-6/2) \approx 0.14 exp(1−6/2)≈0.14,因此BLEU也接近0.14。
下面来实现BLEU的计算。
def bleu(pred_tokens, label_tokens, k):
len_pred, len_label = len(pred_tokens), len(label_tokens)
score = math.exp(min(0, 1 - len_label / len_pred))
for n in range(1, k + 1):
num_matches, label_subs = 0, collections.defaultdict(int)
for i in range(len_label - n + 1):
label_subs[''.join(label_tokens[i: i + n])] += 1
for i in range(len_pred - n + 1):
if label_subs[''.join(pred_tokens[i: i + n])] > 0:
num_matches += 1
label_subs[''.join(pred_tokens[i: i + n])] -= 1
score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))
return score
接下来,定义一个辅助打印函数。
def score(input_seq, label_seq, k):
pred_tokens = translate(encoder, decoder, input_seq, max_seq_len)
label_tokens = label_seq.split(' ')
print('bleu %.3f, predict: %s' % (bleu(pred_tokens, label_tokens, k),
' '.join(pred_tokens)))
预测正确则分数为1。
score('ils regardent .', 'they are watching .', k=2)
bleu 1.000, predict: they are watching .
score('ils sont canadienne .', 'they are canadian .', k=2)
bleu 0.658, predict: they are russian .
小结
- 可以将编码器—解码器和注意力机制应用于机器翻译中。
- BLEU可以用来评价翻译结果。
练习
- 如果编码器和解码器的隐藏单元个数不同或层数不同,我们该如何改进解码器的隐藏状态初始化方法?
-
线性变换 (Linear Transformation):
对于隐藏单元数目不同的情况,可以通过一个线性变换(如全连接层)将编码器的隐藏状态转换为解码器的隐藏状态。假设编码器的隐藏状态为h_e
,解码器的隐藏状态为h_d
,可以使用以下公式进行转换:
[
h_d = W \cdot h_e + b
]
其中,W
和b
是需要学习的参数。 -
全连接层 (Fully Connected Layer):
对于隐藏层数目不同的情况,可以使用多个全连接层将编码器的隐藏状态映射到解码器的隐藏状态。例如,假设编码器有n
层,解码器有m
层,可以使用m
个全连接层分别将编码器的每一层隐藏状态转换为解码器的每一层隐藏状态。 -
均匀分布初始化 (Uniform Distribution Initialization):
另一种方法是将编码器的隐藏状态均匀分布到解码器的隐藏状态中。例如,如果编码器有 2 层,解码器有 4 层,可以将编码器的每一层隐藏状态分别复制两次,初始化解码器的每一层隐藏状态。 -
均值池化 (Mean Pooling):
对于层数不同的情况,可以将编码器的隐藏状态通过均值池化的方法进行缩放或扩展。例如,假设编码器有n
层,解码器有m
层,可以通过均值池化将n
层隐藏状态缩放到m
层隐藏状态。 -
重复和裁剪 (Repetition and Trimming):
如果编码器的层数少于解码器的层数,可以重复编码器的隐藏状态以匹配解码器的层数;如果编码器的层数多于解码器的层数,可以裁剪编码器的隐藏状态以匹配解码器的层数。
- 在训练中,将强制教学替换为使用解码器在上一时间步的输出作为解码器在当前时间步的输入。结果有什么变化吗?
在训练过程中,将强制教学(Teacher Forcing)替换为使用解码器在上一时间步的输出作为解码器在当前时间步的输入,这一策略通常称为“无教师强制”或“自回归解码”。两种方法在训练过程中的效果可能会有所不同:
-
训练稳定性:
- 强制教学: 训练过程更稳定,因为模型在每个时间步都能得到正确的输入(即实际的目标序列),因此更容易学习到正确的映射。
- 无教师强制: 训练过程可能会不稳定,因为模型可能会错误地预测一些步骤,这些错误的输出会作为下一时间步的输入,导致错误积累和梯度消失或爆炸问题。
-
模型性能:
- 强制教学: 训练过程中模型可能会表现得很好,但在推理时,模型需要在没有正确输入的情况下生成整个序列,导致性能下降,因为训练时没有学到如何处理自己的错误预测。
- 无教师强制: 训练过程中模型学会处理自己的错误预测,因此在推理时的性能可能更好,因为训练和推理的输入方式一致。
-
收敛速度:
- 强制教学: 由于每个时间步都使用了正确的输入,模型通常会更快收敛。
- 无教师强制: 由于使用了模型的预测作为输入,训练过程中的误差传播更加复杂,可能导致收敛速度变慢。
-
生成序列的质量:
- 强制教学: 生成序列在训练时的质量可能较高,但在推理时由于没有了强制教学的帮助,质量可能会下降。
- 无教师强制: 生成序列的质量在训练和推理时更加一致,尽管训练时的序列质量可能略低,但在推理时的质量往往更可靠。
将强制教学替换为无教师强制解码可能会导致训练不稳定,但在推理时模型的表现通常会更好,因为它已经学会了处理自己的错误预测。在实际应用中,可以考虑在训练初期使用较高的教师强制比率(如 0.5 或更高),然后逐渐降低到完全无教师强制,以实现两者的平衡。
- 试着使用更大的翻译数据集来训练模型,例如 WMT [2] 和 Tatoeba Project [3]。
!pip install spacy
Collecting spacy
[?25l Downloading https://files.pythonhosted.org/packages/94/f5/c1cb70915af0a1976c40512e450ec86dba02ef547e3af49bd9061af4bbd0/spacy-3.6.1.tar.gz (1.3MB)
[K 100% |████████████████████████████████| 1.3MB 14.7MB/s
[?25h Installing build dependencies ... [?25ldone
[?25h Getting requirements to build wheel ... [?25ldone
[?25h Installing backend dependencies ... [?25ldone
[?25h Preparing wheel metadata ... [?25ldone
[?25hRequirement already satisfied: requests<3.0.0,>=2.13.0 in /opt/conda/lib/python3.6/site-packages (from spacy) (2.21.0)
Collecting langcodes<4.0.0,>=3.2.0 (from spacy)
[?25l Downloading https://files.pythonhosted.org/packages/fe/c3/0d04d248624a181e57c2870127dfa8d371973561caf54333c85e8f9133a2/langcodes-3.3.0-py3-none-any.whl (181kB)
[K 100% |████████████████████████████████| 184kB 2.1MB/s
[?25hCollecting smart-open<7.0.0,>=5.2.1 (from spacy)
[?25l Downloading https://files.pythonhosted.org/packages/fc/d9/d97f1db64b09278aba64e8c81b5d322d436132df5741c518f3823824fae0/smart_open-6.4.0-py3-none-any.whl (57kB)
[K 100% |████████████████████████████████| 61kB 8.3MB/s
[?25hRequirement already satisfied: typing-extensions<4.5.0,>=3.7.4.1; python_version < "3.8" in /opt/conda/lib/python3.6/site-packages (from spacy) (3.7.4.2)
Collecting spacy-loggers<2.0.0,>=1.0.0 (from spacy)
Downloading https://files.pythonhosted.org/packages/33/78/d1a1a026ef3af911159398c939b1509d5c36fe524c7b644f34a5146c4e16/spacy_loggers-1.0.5-py3-none-any.whl
Collecting srsly<3.0.0,>=2.4.3 (from spacy)
Collecting pathy>=0.10.0 (from spacy)
[?25l Downloading https://files.pythonhosted.org/packages/0e/6b/d64babaaeaea0311e55a193d6385bcd2b342e30158ce336cbc05eae7fec6/pathy-0.10.3-py3-none-any.whl (48kB)
[K 100% |████████████████████████████████| 51kB 8.6MB/s
[?25hRequirement already satisfied: numpy>=1.15.0 in /opt/conda/lib/python3.6/site-packages (from spacy) (1.18.4)
Collecting catalogue<2.1.0,>=2.0.6 (from spacy)
Using cached https://files.pythonhosted.org/packages/9e/96/d32b941a501ab566a16358d68b6eb4e4acc373fab3c3c4d7d9e649f7b4bb/catalogue-2.0.10-py3-none-any.whl
Requirement already satisfied: jinja2 in /opt/conda/lib/python3.6/site-packages (from spacy) (2.10)
Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /opt/conda/lib/python3.6/site-packages (from spacy) (4.46.0)
Collecting wasabi<1.2.0,>=0.9.1 (from spacy)
Using cached https://files.pythonhosted.org/packages/06/7c/34330a89da55610daa5f245ddce5aab81244321101614751e7537f125133/wasabi-1.1.3-py3-none-any.whl
Collecting typer<0.10.0,>=0.3.0 (from spacy)
[?25l Downloading https://files.pythonhosted.org/packages/62/39/82c9d3e10979851847361d922a373bdfef4091020da7f893acfaf07c0225/typer-0.9.4-py3-none-any.whl (45kB)
[K 100% |████████████████████████████████| 51kB 4.6MB/s
[?25hCollecting pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4 (from spacy)
Using cached https://files.pythonhosted.org/packages/fe/27/0de772dcd0517770b265dbc3998ed3ee3aa2ba25ba67e3685116cbbbccc6/pydantic-1.9.2-py3-none-any.whl
Collecting preshed<3.1.0,>=3.0.2 (from spacy)
Using cached https://files.pythonhosted.org/packages/93/a5/8c584d06c06ea54de9ae0f052d9491bff2c03b6dbec52b787489fbe9dd86/preshed-3.0.9-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Collecting murmurhash<1.1.0,>=0.28.0 (from spacy)
Using cached https://files.pythonhosted.org/packages/dd/4f/509c544c53342656c486cd3df0093ad9bebe0a01bb9e6af27d6bb8f7f69f/murmurhash-1.0.10-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Collecting packaging>=20.0 (from spacy)
Using cached https://files.pythonhosted.org/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl
Collecting spacy-legacy<3.1.0,>=3.0.11 (from spacy)
Downloading https://files.pythonhosted.org/packages/c3/55/12e842c70ff8828e34e543a2c7176dac4da006ca6901c9e8b43efab8bc6b/spacy_legacy-3.0.12-py2.py3-none-any.whl
Requirement already satisfied: setuptools in /opt/conda/lib/python3.6/site-packages (from spacy) (46.4.0)
Collecting cymem<2.1.0,>=2.0.2 (from spacy)
Collecting thinc<8.2.0,>=8.1.8 (from spacy)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (2.8)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (1.24.1)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (2018.11.29)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (3.0.4)
Collecting dataclasses<1.0,>=0.6; python_version < "3.7" (from pathy>=0.10.0->spacy)
Using cached https://files.pythonhosted.org/packages/fe/ca/75fac5856ab5cfa51bbbcefa250182e50441074fdc3f803f6e76451fab43/dataclasses-0.8-py3-none-any.whl
Collecting zipp>=0.5; python_version < "3.8" (from catalogue<2.1.0,>=2.0.6->spacy)
Using cached https://files.pythonhosted.org/packages/bd/df/d4a4974a3e3957fd1c1fa3082366d7fff6e428ddb55f074bf64876f8e8ad/zipp-3.6.0-py3-none-any.whl
Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from jinja2->spacy) (1.1.0)
Requirement already satisfied: click<9.0.0,>=7.1.1 in /opt/conda/lib/python3.6/site-packages (from typer<0.10.0,>=0.3.0->spacy) (7.1.2)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging>=20.0->spacy) (2.3.1)
Collecting contextvars<3,>=2.4; python_version < "3.7" (from thinc<8.2.0,>=8.1.8->spacy)
Collecting blis<0.8.0,>=0.7.8 (from thinc<8.2.0,>=8.1.8->spacy)
Collecting confection<1.0.0,>=0.0.1 (from thinc<8.2.0,>=8.1.8->spacy)
Using cached https://files.pythonhosted.org/packages/0c/00/3106b1854b45bd0474ced037dfe6b73b90fe68a68968cef47c23de3d43d2/confection-0.1.5-py3-none-any.whl
Collecting immutables>=0.9 (from contextvars<3,>=2.4; python_version < "3.7"->thinc<8.2.0,>=8.1.8->spacy)
Using cached https://files.pythonhosted.org/packages/fb/ad/154c84dcb517f534c74accd5811d00d41af112ccfe505b7013f32efebb9e/immutables-0.19-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Building wheels for collected packages: spacy
Building wheel for spacy (PEP 517) ... [?25ldone
[?25h Stored in directory: /home/jovyan/.cache/pip/wheels/b1/f0/3a/dcddbd0292f72de3e8a8a78e9cd2dee69d64ed405188a003bd
Successfully built spacy
[31mtyper 0.9.4 has requirement typing-extensions>=3.7.4.3, but you'll have typing-extensions 3.7.4.2 which is incompatible.[0m
[31mpydantic 1.9.2 has requirement typing-extensions>=3.7.4.3, but you'll have typing-extensions 3.7.4.2 which is incompatible.[0m
[31mimmutables 0.19 has requirement typing-extensions>=3.7.4.3; python_version < "3.8", but you'll have typing-extensions 3.7.4.2 which is incompatible.[0m
Installing collected packages: langcodes, smart-open, spacy-loggers, zipp, catalogue, srsly, dataclasses, typer, pathy, wasabi, pydantic, cymem, murmurhash, preshed, packaging, spacy-legacy, immutables, contextvars, blis, confection, thinc, spacy
Found existing installation: smart-open 1.8.0
Uninstalling smart-open-1.8.0:
Successfully uninstalled smart-open-1.8.0
Found existing installation: packaging 19.0
Uninstalling packaging-19.0:
Successfully uninstalled packaging-19.0
Successfully installed blis-0.7.11 catalogue-2.0.10 confection-0.1.5 contextvars-2.4 cymem-2.0.8 dataclasses-0.8 immutables-0.19 langcodes-3.3.0 murmurhash-1.0.10 packaging-21.3 pathy-0.10.3 preshed-3.0.9 pydantic-1.9.2 smart-open-6.4.0 spacy-3.6.1 spacy-legacy-3.0.12 spacy-loggers-1.0.5 srsly-2.4.8 thinc-8.1.12 typer-0.9.4 wasabi-1.1.3 zipp-3.6.0
!python -m spacy download de_core_news_sm
!python -m spacy download en_core_web_sm
/opt/conda/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Collecting de-core-news-sm==3.6.0 from https://github.com/explosion/spacy-models/releases/download/de_core_news_sm-3.6.0/de_core_news_sm-3.6.0-py3-none-any.whl
[?25l Downloading https://github.com/explosion/spacy-models/releases/download/de_core_news_sm-3.6.0/de_core_news_sm-3.6.0-py3-none-any.whl (14.6MB)
[K 100% |████████████████████████████████| 14.6MB 3.3MB/s
[?25hRequirement already satisfied: spacy<3.7.0,>=3.6.0 in /opt/conda/lib/python3.6/site-packages (from de-core-news-sm==3.6.0) (3.6.1)
Requirement already satisfied: pathy>=0.10.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.10.3)
Requirement already satisfied: catalogue<2.1.0,>=2.0.6 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.0.10)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.0.10)
Requirement already satisfied: typing-extensions<4.5.0,>=3.7.4.1; python_version < "3.8" in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.7.4.2)
Requirement already satisfied: spacy-loggers<2.0.0,>=1.0.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.0.5)
Requirement already satisfied: wasabi<1.2.0,>=0.9.1 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.1.3)
Requirement already satisfied: pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.9.2)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.0.9)
Requirement already satisfied: numpy>=1.15.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.18.4)
Requirement already satisfied: typer<0.10.0,>=0.3.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.9.4)
Requirement already satisfied: spacy-legacy<3.1.0,>=3.0.11 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.0.12)
Requirement already satisfied: requests<3.0.0,>=2.13.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.21.0)
Requirement already satisfied: thinc<8.2.0,>=8.1.8 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (8.1.12)
Requirement already satisfied: packaging>=20.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (21.3)
Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (4.46.0)
Requirement already satisfied: jinja2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.10)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (46.4.0)
Requirement already satisfied: smart-open<7.0.0,>=5.2.1 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (6.4.0)
Requirement already satisfied: srsly<3.0.0,>=2.4.3 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.4.8)
Requirement already satisfied: langcodes<4.0.0,>=3.2.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.3.0)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.0.8)
Requirement already satisfied: dataclasses<1.0,>=0.6; python_version < "3.7" in /opt/conda/lib/python3.6/site-packages (from pathy>=0.10.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.8)
Requirement already satisfied: zipp>=0.5; python_version < "3.8" in /opt/conda/lib/python3.6/site-packages (from catalogue<2.1.0,>=2.0.6->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.6.0)
Requirement already satisfied: click<9.0.0,>=7.1.1 in /opt/conda/lib/python3.6/site-packages (from typer<0.10.0,>=0.3.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (7.1.2)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.24.1)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2018.11.29)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.8)
Requirement already satisfied: blis<0.8.0,>=0.7.8 in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.7.11)
Requirement already satisfied: contextvars<3,>=2.4; python_version < "3.7" in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.4)
Requirement already satisfied: confection<1.0.0,>=0.0.1 in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.1.5)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging>=20.0->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (2.3.1)
Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from jinja2->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (1.1.0)
Requirement already satisfied: immutables>=0.9 in /opt/conda/lib/python3.6/site-packages (from contextvars<3,>=2.4; python_version < "3.7"->thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->de-core-news-sm==3.6.0) (0.19)
Installing collected packages: de-core-news-sm
Successfully installed de-core-news-sm-3.6.0
[38;5;2m✔ Download and installation successful[0m
You can now load the package via spacy.load('de_core_news_sm')
/opt/conda/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Collecting en-core-web-sm==3.6.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.6.0/en_core_web_sm-3.6.0-py3-none-any.whl
[?25l Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.6.0/en_core_web_sm-3.6.0-py3-none-any.whl (12.8MB)
[K 100% |████████████████████████████████| 12.8MB 3.6MB/s
[?25hRequirement already satisfied: spacy<3.7.0,>=3.6.0 in /opt/conda/lib/python3.6/site-packages (from en-core-web-sm==3.6.0) (3.6.1)
Requirement already satisfied: pathy>=0.10.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.10.3)
Requirement already satisfied: pydantic!=1.8,!=1.8.1,<3.0.0,>=1.7.4 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.9.2)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (46.4.0)
Requirement already satisfied: thinc<8.2.0,>=8.1.8 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (8.1.12)
Requirement already satisfied: smart-open<7.0.0,>=5.2.1 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (6.4.0)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.0.9)
Requirement already satisfied: typing-extensions<4.5.0,>=3.7.4.1; python_version < "3.8" in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.7.4.2)
Requirement already satisfied: srsly<3.0.0,>=2.4.3 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.4.8)
Requirement already satisfied: requests<3.0.0,>=2.13.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.21.0)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.0.8)
Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (4.46.0)
Requirement already satisfied: spacy-legacy<3.1.0,>=3.0.11 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.0.12)
Requirement already satisfied: catalogue<2.1.0,>=2.0.6 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.0.10)
Requirement already satisfied: numpy>=1.15.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.18.4)
Requirement already satisfied: wasabi<1.2.0,>=0.9.1 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.1.3)
Requirement already satisfied: typer<0.10.0,>=0.3.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.9.4)
Requirement already satisfied: packaging>=20.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (21.3)
Requirement already satisfied: jinja2 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.10)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.0.10)
Requirement already satisfied: langcodes<4.0.0,>=3.2.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.3.0)
Requirement already satisfied: spacy-loggers<2.0.0,>=1.0.0 in /opt/conda/lib/python3.6/site-packages (from spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.0.5)
Requirement already satisfied: dataclasses<1.0,>=0.6; python_version < "3.7" in /opt/conda/lib/python3.6/site-packages (from pathy>=0.10.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.8)
Requirement already satisfied: contextvars<3,>=2.4; python_version < "3.7" in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.4)
Requirement already satisfied: confection<1.0.0,>=0.0.1 in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.1.5)
Requirement already satisfied: blis<0.8.0,>=0.7.8 in /opt/conda/lib/python3.6/site-packages (from thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.7.11)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2018.11.29)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.24.1)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.0.4)
Requirement already satisfied: zipp>=0.5; python_version < "3.8" in /opt/conda/lib/python3.6/site-packages (from catalogue<2.1.0,>=2.0.6->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (3.6.0)
Requirement already satisfied: click<9.0.0,>=7.1.1 in /opt/conda/lib/python3.6/site-packages (from typer<0.10.0,>=0.3.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (7.1.2)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging>=20.0->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (2.3.1)
Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from jinja2->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (1.1.0)
Requirement already satisfied: immutables>=0.9 in /opt/conda/lib/python3.6/site-packages (from contextvars<3,>=2.4; python_version < "3.7"->thinc<8.2.0,>=8.1.8->spacy<3.7.0,>=3.6.0->en-core-web-sm==3.6.0) (0.19)
Installing collected packages: en-core-web-sm
Successfully installed en-core-web-sm-3.6.0
[38;5;2m✔ Download and installation successful[0m
You can now load the package via spacy.load('en_core_web_sm')
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator
import spacy
# 加载 SpaCy 模型
spacy_de = spacy.load("de_core_news_sm")
spacy_en = spacy.load("en_core_web_sm")
# 定义分词函数
def tokenize_de(text):
return [tok.text for tok in spacy_de.tokenizer(text)]
def tokenize_en(text):
return [tok.text for tok in spacy_en.tokenizer(text)]
# 定义字段
SRC = Field(tokenize=tokenize_de,
init_token='<sos>',
eos_token='<eos>',
lower=True)
TRG = Field(tokenize=tokenize_en,
init_token='<sos>',
eos_token='<eos>',
lower=True)
# 下载和加载数据集
train_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'),
fields=(SRC, TRG))
# 构建词汇表
SRC.build_vocab(train_data, min_freq=2)
TRG.build_vocab(train_data, min_freq=2)
# 创建数据迭代器
BATCH_SIZE = 128
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size = BATCH_SIZE,
device = device)
# 定义模型
class Encoder(nn.Module):
def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
embedded = self.dropout(self.embedding(src))
outputs, (hidden, cell) = self.rnn(embedded)
return hidden, cell
class Decoder(nn.Module):
def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.output_dim = output_dim
self.embedding = nn.Embedding(output_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)
self.fc_out = nn.Linear(hid_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, input, hidden, cell):
input = input.unsqueeze(0)
embedded = self.dropout(self.embedding(input))
output, (hidden, cell) = self.rnn(embedded, (hidden, cell))
prediction = self.fc_out(output.squeeze(0))
return prediction, hidden, cell
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, device):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.device = device
def forward(self, src, trg, teacher_forcing_ratio=0.5):
trg_len = trg.shape[0]
batch_size = trg.shape[1]
trg_vocab_size = self.decoder.output_dim
outputs = torch.zeros(trg_len, batch_size, trg_vocab_size).to(self.device)
hidden, cell = self.encoder(src)
input = trg[0,:]
for t in range(1, trg_len):
output, hidden, cell = self.decoder(input, hidden, cell)
outputs[t] = output
top1 = output.argmax(1)
input = trg[t] if random.random() < teacher_forcing_ratio else top1
return outputs
# 初始化模型
INPUT_DIM = len(SRC.vocab)
OUTPUT_DIM = len(TRG.vocab)
ENC_EMB_DIM = 256
DEC_EMB_DIM = 256
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5
enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)
model = Seq2Seq(enc, dec, device).to(device)
# 定义优化器和损失函数
optimizer = optim.Adam(model.parameters())
criterion = nn.CrossEntropyLoss(ignore_index=TRG.vocab.stoi[TRG.pad_token])
# 训练模型
def train(model, iterator, optimizer, criterion, clip):
model.train()
epoch_loss = 0
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
optimizer.zero_grad()
output = model(src, trg)
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
loss = criterion(output, trg)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
epoch_loss += loss.item()
return epoch_loss / len(iterator)
# 验证模型
def evaluate(model, iterator, criterion):
model.eval()
epoch_loss = 0
with torch.no_grad():
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
output = model(src, trg, 0)
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
loss = criterion(output, trg)
epoch_loss += loss.item()
return epoch_loss / len(iterator)
N_EPOCHS = 10
CLIP = 1
for epoch in range(N_EPOCHS):
train_loss = train(model, train_iterator, optimizer, criterion, CLIP)
valid_loss = evaluate(model, valid_iterator, criterion)
print(f'Epoch: {epoch+1:02}')
print(f'\tTrain Loss: {train_loss:.3f}')
print(f'\t Val. Loss: {valid_loss:.3f}')
# 测试模型
test_loss = evaluate(model, test_iterator, criterion)
print(f'Test Loss: {test_loss:.3f}')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[3], line 32
26 TRG = Field(tokenize=tokenize_en,
27 init_token='<sos>',
28 eos_token='<eos>',
29 lower=True)
31 # 下载和加载数据集
---> 32 train_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'),
33 fields=(SRC, TRG))
35 # 构建词汇表
36 SRC.build_vocab(train_data, min_freq=2)
File ~\AppData\Roaming\Python\Python310\site-packages\torchtext\datasets\translation.py:113, in Multi30k.splits(cls, exts, fields, root, train, validation, test, **kwargs)
110 path = kwargs['path']
111 del kwargs['path']
--> 113 return super(Multi30k, cls).splits(
114 exts, fields, path, root, train, validation, test, **kwargs)
File ~\AppData\Roaming\Python\Python310\site-packages\torchtext\datasets\translation.py:65, in TranslationDataset.splits(cls, exts, fields, path, root, train, validation, test, **kwargs)
62 if path is None:
63 path = cls.download(root)
---> 65 train_data = None if train is None else cls(
66 os.path.join(path, train), exts, fields, **kwargs)
67 val_data = None if validation is None else cls(
68 os.path.join(path, validation), exts, fields, **kwargs)
69 test_data = None if test is None else cls(
70 os.path.join(path, test), exts, fields, **kwargs)
File ~\AppData\Roaming\Python\Python310\site-packages\torchtext\datasets\translation.py:34, in TranslationDataset.__init__(self, path, exts, fields, **kwargs)
31 src_path, trg_path = tuple(os.path.expanduser(path + x) for x in exts)
33 examples = []
---> 34 with io.open(src_path, mode='r', encoding='utf-8') as src_file, \
35 io.open(trg_path, mode='r', encoding='utf-8') as trg_file:
36 for src_line, trg_line in zip(src_file, trg_file):
37 src_line, trg_line = src_line.strip(), trg_line.strip()
FileNotFoundError: [Errno 2] No such file or directory: '.data\\multi30k\\train.de'
参考文献
[1] Papineni, K., Roukos, S., Ward, T., & Zhu, W. J. (2002, July). BLEU: a method for automatic evaluation of machine translation. In Proceedings of the 40th annual meeting on association for computational linguistics (pp. 311-318). Association for Computational Linguistics.
[2] WMT. http://www.statmt.org/wmt14/translation-task.html
[3] Tatoeba Project. http://www.manythings.org/anki/