第9章リカレントニューラルネットワーク
9.2.3. Vocabulary9.2.3 語彙
These tokens are still strings. However, the inputs to our models must ultimately consist of numerical inputs. Next, we introduce a class for constructing vocabularies, i.e., objects that associate each distinct token value with a unique index. First, we determine the set of unique tokens in our training corpus. We then assign a numerical index to each unique token. Rare vocabulary elements are often dropped for convenience. Whenever we encounter a token at training or test time that had not been previously seen or was dropped from the vocabulary, we represent it by a special “<unk>” token, signifying that this is an unknown value.
英語のヒント
これらのトークンは、まだ文字列である。しかし、モデルへの入力は最終的には数値の入力からなっていなければならない。次に、語彙、つまり異なる各トークンの値に一意のインデックスを対応づけるオブジェクトを作るためのクラスを紹介する。まず、訓練コーパスの中の一意なトークンの集合を決める。次に、一意な各トークンに数値のインデックスを割り当てる。まれな語彙の要素は、便宜上しばしば捨てられる。訓練時やテスト時に、前に見たことのないトークンや語彙から捨てられたトークンに出会ったときはいつでも、それを特別な「<unk>」トークンで表し、それが未知の値であることを示す。
class Vocab: #@save
"""Vocabulary for text."""
def __init__(self, tokens=[], min_freq=0, reserved_tokens=[]):
# Flatten a 2D list if needed
if tokens and isinstance(tokens[0], list):
tokens = [token for line in tokens for token in line]
# Count token frequencies
counter = collections.Counter(tokens)
self.token_freqs = sorted(counter.items(), key=lambda x: x[1],
reverse=True)
# The list of unique tokens
self.idx_to_token = list(sorted(set(['<unk>'] + reserved_tokens + [
token for token, freq in self.token_freqs if freq >= min_freq])))
self.token_to_idx = {token: idx
for idx, token in enumerate(self.idx_to_token)}
def __len__(self):
return len(self.idx_to_token)
def __getitem__(self, tokens):
if not isinstance(tokens, (list, tuple)):
return self.token_to_idx.get(tokens, self.unk)
return [self.__getitem__(token) for token in tokens]
def to_tokens(self, indices):
if hasattr(indices, '__len__') and len(indices) > 1:
return [self.idx_to_token[int(index)] for index in indices]
return self.idx_to_token[indices]
@property
def unk(self): # Index for the unknown token
return self.token_to_idx['<unk>']We now construct a vocabulary for our dataset, converting the sequence of strings into a list of numerical indices. Note that we have not lost any information and can easily convert our dataset back to its original (string) representation.
英語のヒント
これで、データセットの語彙を作り、文字列の系列を数値のインデックスのリストに変換する。情報は何も失っておらず、データセットを元の(文字列の)表現に簡単に戻せることに注意してほしい。
vocab = Vocab(tokens)
indices = vocab[tokens[:10]]
print('indices:', indices)
print('words:', vocab.to_tokens(indices))indices: [21, 9, 6, 0, 21, 10, 14, 6, 0, 14]
words: ['t', 'h', 'e', ' ', 't', 'i', 'm', 'e', ' ', 'm']