プリンキピア

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

15.3.4. Negative Sampling15.3.4 負例サンプリング

We use negative sampling for approximate training. To sample noise words according to a predefined distribution, we define the following RandomGenerator class, where the (possibly unnormalized) sampling distribution is passed via the argument sampling_weights.
英語のヒント
近似的な訓練には負例サンプリングを使う。あらかじめ決めた分布に従ってノイズ語を抜き出すため、次のRandomGeneratorクラスを定義する。そこでは、(正規化されていないかもしれない)サンプリング分布が引数sampling_weightsで渡される。
#@save
class RandomGenerator:
    """Randomly draw among {1, ..., n} according to n sampling weights."""
    def __init__(self, sampling_weights):
        # Exclude
        self.population = list(range(1, len(sampling_weights) + 1))
        self.sampling_weights = sampling_weights
        self.candidates = []
        self.i = 0

    def draw(self):
        if self.i == len(self.candidates):
            # Cache `k` random sampling results
            self.candidates = random.choices(
                self.population, self.sampling_weights, k=10000)
            self.i = 0
        self.i += 1
        return self.candidates[self.i - 1]
For example, we can draw 10 random variables X among indices 1, 2, and 3 with sampling probabilities P(X=1)=2/9,P(X=2)=3/9, and P(X=3)=4/9 as follows.
英語のヒント
たとえば、次のように、インデックス1、2、3の中から、サンプリング確率P(X=1)=2/9,P(X=2)=3/9、P(X=3)=4/9で、10個の確率変数Xを抜き出せる。
For a pair of center word and context word, we randomly sample K (5 in the experiment) noise words. According to the suggestions in the word2vec paper, the sampling probability P(w) of a noise word w is set to its relative frequency in the dictionary raised to the power of 0.75 (Mikolov et al., 2013).
英語のヒント
中心語と文脈語の組一つについて、K個(実験では5個)のノイズ語をランダムに抜き出す。word2vecの論文の提案に従って、ノイズ語wのサンプリング確率P(w)は、辞書でのその相対頻度を0.75乗したものに設定する(Mikolov et al., 2013)。
#@save
def get_negatives(all_contexts, vocab, counter, K):
    """Return noise words in negative sampling."""
    # Sampling weights for words with indices 1, 2, ... (index 0 is the
    # excluded unknown token) in the vocabulary
    sampling_weights = [counter[vocab.to_tokens(i)]**0.75
                        for i in range(1, len(vocab))]
    all_negatives, generator = [], RandomGenerator(sampling_weights)
    for contexts in all_contexts:
        negatives = []
        while len(negatives) < len(contexts) * K:
            neg = generator.draw()
            # Noise words cannot be context words
            if neg not in contexts:
                negatives.append(neg)
        all_negatives.append(negatives)
    return all_negatives

all_negatives = get_negatives(all_contexts, vocab, counter, 5)