プリンキピア

第15章自然言語処理:事前学習

15.3.3. Extracting Center Words and Context Words15.3.3 中心語と文脈語の抽出

The following get_centers_and_contexts function extracts all the center words and their context words from corpus. It uniformly samples an integer between 1 and max_window_size at random as the context window size. For any center word, those words whose distance from it does not exceed the sampled context window size are its context words.
英語のヒント
次のget_centers_and_contexts関数は、corpusからすべての中心語とその文脈語を抽出する。この関数は、文脈窓の大きさとして、1からmax_window_sizeまでの整数を一様にランダムに抜き出す。任意の中心語について、中心語からの距離が抜き出した文脈窓の大きさを超えない語が、その文脈語である。
#@save
def get_centers_and_contexts(corpus, max_window_size):
    """Return center words and context words in skip-gram."""
    centers, contexts = [], []
    for line in corpus:
        # To form a "center word--context word" pair, each sentence needs to
        # have at least 2 words
        if len(line) < 2:
            continue
        centers += line
        for i in range(len(line)):  # Context window centered at `i`
            window_size = random.randint(1, max_window_size)
            indices = list(range(max(0, i - window_size),
                                 min(len(line), i + 1 + window_size)))
            # Exclude the center word from the context words
            indices.remove(i)
            contexts.append([line[idx] for idx in indices])
    return centers, contexts
Next, we create an artificial dataset containing two sentences of 7 and 3 words, respectively. Let the maximum context window size be 2 and print all the center words and their context words.
英語のヒント
次に、それぞれ7語と3語の二つの文を含む人工的なデータセットを作る。文脈窓の大きさの最大値を2として、すべての中心語とその文脈語を表示する。
tiny_dataset = [list(range(7)), list(range(7, 10))]
print('dataset', tiny_dataset)
for center, context in zip(*get_centers_and_contexts(tiny_dataset, 2)):
    print('center', center, 'has contexts', context)
dataset [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]
center 0 has contexts [1]
center 1 has contexts [0, 2]
center 2 has contexts [0, 1, 3, 4]
center 3 has contexts [1, 2, 4, 5]
center 4 has contexts [2, 3, 5, 6]
center 5 has contexts [3, 4, 6]
center 6 has contexts [5]
center 7 has contexts [8, 9]
center 8 has contexts [7, 9]
center 9 has contexts [7, 8]
When training on the PTB dataset, we set the maximum context window size to 5. The following extracts all the center words and their context words in the dataset.
英語のヒント
PTBのデータセットで訓練するときは、文脈窓の大きさの最大値を5に設定する。次のコードは、データセットのすべての中心語とその文脈語を抽出する。
all_centers, all_contexts = get_centers_and_contexts(corpus, 5)
f'# center-context pairs: {sum([len(contexts) for contexts in all_contexts])}'
'# center-context pairs: 1503420'