第10章現代のリカレントニューラルネットワーク
10.5.3. Loading Sequences of Fixed Length10.5.3 固定長の系列を読み込む
Recall that in language modeling each example sequence, either a segment of one sentence or a span over multiple sentences, had a fixed length. This was specified by the
num_steps (number of time steps or tokens) argument from Section 9.3. In machine translation, each example is a pair of source and target text sequences, where the two text sequences may have different lengths.英語のヒント
言語のモデリングでは、各事例の系列は、一つの文の一部であれ複数の文にまたがるものであれ、固定の長さをもっていたことを思い出そう。これは、9.3節の引数
num_steps(時間ステップ、つまりトークンの数)で指定された。機械翻訳では、各事例は原文と目標のテキスト系列の組であり、二つのテキスト系列の長さは異なることがある。For computational efficiency, we can still process a minibatch of text sequences at one time by truncation and padding. Suppose that every sequence in the same minibatch should have the same length
num_steps. If a text sequence has fewer than num_steps tokens, we will keep appending the special “<pad>” token to its end until its length reaches num_steps. Otherwise, we will truncate the text sequence by only taking its first num_steps tokens and discarding the remaining. In this way, every text sequence will have the same length to be loaded in minibatches of the same shape. Furthermore, we also record length of the source sequence excluding padding tokens. This information will be needed by some models that we will cover later.英語のヒント
計算の効率のため、打ち切りと詰め物によって、テキスト系列のミニバッチを一度に処理することはできる。同じミニバッチのすべての系列が同じ長さ
num_stepsをもつべきだとしよう。テキスト系列のトークンがnum_steps個より少なければ、長さがnum_stepsに達するまで、その末尾に特別な「<pad>」トークンを付け加え続ける。そうでなければ、最初のnum_steps個のトークンだけをとって残りを捨て、テキスト系列を打ち切る。こうして、どのテキスト系列も同じ長さになり、同じ形状のミニバッチに読み込める。さらに、詰め物のトークンを除いた原文の系列の長さも記録する。この情報は、後で扱ういくつかのモデルで必要になる。Since the machine translation dataset consists of pairs of languages, we can build two vocabularies for both the source language and the target language separately. With word-level tokenization, the vocabulary size will be significantly larger than that using character-level tokenization. To alleviate this, here we treat infrequent tokens that appear less than twice as the same unknown (“<unk>”) token. As we will explain later (Fig. 10.7.1), when training with target sequences, the decoder output (label tokens) can be the same decoder input (target tokens), shifted by one token; and the special beginning-of-sequence “<bos>” token will be used as the first input token for predicting the target sequence (Fig. 10.7.3).
英語のヒント
機械翻訳のデータセットは言語の組からなるので、原言語と目標言語の両方について、二つの語彙を別々に作れる。単語単位のトークン化では、語彙の大きさは文字単位のトークン化のものよりかなり大きくなる。これを和らげるため、ここでは2回未満しか現れないまれなトークンを、同じ未知の(「<unk>」)トークンとして扱う。後で説明するように(図10.7.1)、目標系列で訓練するとき、デコーダの出力(ラベルのトークン)は、1トークンずらした同じデコーダの入力(目標のトークン)にできる。そして、目標系列を予測するための最初の入力トークンとして、系列の始まりを表す特別な「<bos>」トークンが使われる(図10.7.3)。
@d2l.add_to_class(MTFraEng) #@save
def __init__(self, batch_size, num_steps=9, num_train=512, num_val=128):
super(MTFraEng, self).__init__()
self.save_hyperparameters()
self.arrays, self.src_vocab, self.tgt_vocab = self._build_arrays(
self._download())
@d2l.add_to_class(MTFraEng) #@save
def _build_arrays(self, raw_text, src_vocab=None, tgt_vocab=None):
def _build_array(sentences, vocab, is_tgt=False):
pad_or_trim = lambda seq, t: (
seq[:t] if len(seq) > t else seq + ['<pad>'] * (t - len(seq)))
sentences = [pad_or_trim(s, self.num_steps) for s in sentences]
if is_tgt:
sentences = [['<bos>'] + s for s in sentences]
if vocab is None:
vocab = d2l.Vocab(sentences, min_freq=2)
array = torch.tensor([vocab[s] for s in sentences])
valid_len = (array != vocab['<pad>']).type(torch.int32).sum(1)
return array, vocab, valid_len
src, tgt = self._tokenize(self._preprocess(raw_text),
self.num_train + self.num_val)
src_array, src_vocab, src_valid_len = _build_array(src, src_vocab)
tgt_array, tgt_vocab, _ = _build_array(tgt, tgt_vocab, True)
return ((src_array, tgt_array[:,:-1], src_valid_len, tgt_array[:,1:]),
src_vocab, tgt_vocab)