プリンキピア

第10章現代のリカレントニューラルネットワーク

10.5.2. Tokenization10.5.2 トークン化

Unlike the character-level tokenization in Section 9.3, for machine translation we prefer word-level tokenization here (today’s state-of-the-art models use more complex tokenization techniques). The following _tokenize method tokenizes the first max_examples text sequence pairs, where each token is either a word or a punctuation mark. We append the special “<eos>” token to the end of every sequence to indicate the end of the sequence. When a model is predicting by generating a sequence token after token, the generation of the “<eos>” token can suggest that the output sequence is complete. In the end, the method below returns two lists of token lists: src and tgt. Specifically, src[i] is a list of tokens from the ith text sequence in the source language (English here) and tgt[i] is that in the target language (French here).
英語のヒント
9.3節の文字単位のトークン化とは違って、機械翻訳では、ここでは単語単位のトークン化を好む(今日の最先端のモデルは、もっと複雑なトークン化の手法を使う)。次の_tokenizeメソッドは、最初のmax_examples個のテキスト系列の組をトークン化する。各トークンは単語か句読点である。系列の終わりを示すため、すべての系列の末尾に特別な「<eos>」トークンを付け加える。モデルが系列をトークンごとに生成して予測しているとき、「<eos>」トークンが生成されれば、出力の系列が完成したことを示せる。最後に、以下のメソッドは、トークンのリストのリストを二つ、srcとtgtを返す。具体的には、src[i]は原言語(ここでは英語)のithのテキスト系列のトークンのリストであり、tgt[i]は目標言語(ここではフランス語)のそれである。
@d2l.add_to_class(MTFraEng)  #@save
def _tokenize(self, text, max_examples=None):
    src, tgt = [], []
    for i, line in enumerate(text.split('\n')):
        if max_examples and i > max_examples: break
        parts = line.split('\t')
        if len(parts) == 2:
            # Skip empty tokens
            src.append([t for t in f'{parts[0]} <eos>'.split(' ') if t])
            tgt.append([t for t in f'{parts[1]} <eos>'.split(' ') if t])
    return src, tgt

src, tgt = data._tokenize(text)
src[:6], tgt[:6]
([['go', '.', '<eos>'],
  ['hi', '.', '<eos>'],
  ['run', '!', '<eos>'],
  ['run', '!', '<eos>'],
  ['who', '?', '<eos>'],
  ['wow', '!', '<eos>']],
 [['va', '!', '<eos>'],
  ['salut', '!', '<eos>'],
  ['cours', '!', '<eos>'],
  ['courez', '!', '<eos>'],
  ['qui', '?', '<eos>'],
  ['ça', 'alors', '!', '<eos>']])
Let’s plot the histogram of the number of tokens per text sequence. In this simple English–French dataset, most of the text sequences have fewer than 20 tokens.
英語のヒント
テキスト系列あたりのトークン数のヒストグラムを描こう。この単純な英語・フランス語のデータセットでは、ほとんどのテキスト系列のトークンは20個未満である。
#@save
def show_list_len_pair_hist(legend, xlabel, ylabel, xlist, ylist):
    """Plot the histogram for list length pairs."""
    d2l.set_figsize()
    _, _, patches = d2l.plt.hist(
        [[len(l) for l in xlist], [len(l) for l in ylist]])
    d2l.plt.xlabel(xlabel)
    d2l.plt.ylabel(ylabel)
    for patch in patches[1].patches:
        patch.set_hatch('/')
    d2l.plt.legend(legend)

show_list_len_pair_hist(['source', 'target'], '# tokens per sequence',
                        'count', src, tgt);