Words as vectors
読了まで約39 分分、10 節 節の 8 例 例。
この部分はまだ翻訳されていないため、英語で表示している。
By the end of this chapter you can turn every token of the store's text into a short vector of numbers, so that tokens used in similar ways get similar vectors, by two methods: compressing counts of which tokens appear together, and training a small model to predict each token's neighbours. You'll measure what those vectors know, where they fail, and how they let a model relate text it has never seen to text it has.
Chapter 3 ended on a limit that counting can't get past. Its 4-gram model had seen patio bar stool many times, and suggested stool after patio bar. After outdoor bar, which no training name contains, it fell back to generic suggestions, because a count of one context tells it nothing about another. A shopper, or any reader, knows that outdoor and patio mean nearly the same thing to the store, and a model needs some way to know it too. This chapter gives every token a vector, a list of numbers, and arranges the vectors so that tokens used alike sit close together.
Vectors need text that shows how words get used, and the store, an online seller of furniture and home goods, has plenty of it in its catalog's names and descriptions. Its training split, the 80% of products that models learn from, holds 2,744,320 tokens of that text, and every vector in this chapter comes from it alone, through the store's tokenizer from chapter 2.
one-hotベクトルは何も知らない
ここまでのモデルはいずれも、トークンを名前として扱ってきた。patioは表の一つの項目であり、outdoorは別の項目であって、両者を結びつけるものは何もない。これをベクトルとして書いたものがone-hotエンコーディングである。各トークンに語彙と同じ長さのベクトルを割り当て、そのトークン自身の位置に1を、それ以外のすべての位置に0を置く。二つのベクトルがどれだけ似ているかを測るために、本書ではコサイン類似度を用いる。これは二つのベクトルのなす角のコサインであり、同じ向きを指すときは1、直角をなすときは0になる。ベクトルの長さは無視し、向きだけを比較する。
訓練テキストで出現頻度の高い上位2,000トークンにone-hotベクトルを与え、patioをoutdoor、sofa、そして自分自身と比較する。この2,000トークンは、店舗用トークナイザの語彙のおよそ半分にあたり、この章のどの行列も数秒で計算できる大きさに収まる。
1"""One-hot vectors for the 2,000 most frequent tokens, and the cosine similarity of patio with outdoor, with sofa and with2itself. The prose's point rests on the patio–outdoor and patio–sofa lines: patio is as unrelated to outdoor as to sofa."""3import numpy as np45from lib.vectors import BREAK, training_ids # the book's shared module; BREAK marks the gap between two texts67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8index = {token: i for i, token in enumerate(vocabulary)}91011def one_hot(token):12 vector = np.zeros(len(vocabulary))13 vector[index[token]] = 1.0 # one column per token: 1 for this token, 0 everywhere else14 return vector151617def cosine(a, b):18 return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))192021print("numbers in each vector:", len(vocabulary))22print("cosine(patio, outdoor):", cosine(one_hot("patio</w>"), one_hot("outdoor</w>"))) # </w> marks a word's last token: patio</w> is the whole word23print("cosine(patio, sofa):", cosine(one_hot("patio</w>"), one_hot("sofa</w>")))24print("cosine(patio, patio):", cosine(one_hot("patio</w>"), one_hot("patio</w>")))25print("share of training tokens with a vector:", f"{(ids >= 0).sum() / (ids != BREAK).sum():.0%}") # ids >= 0 are the kept tokens; BREAK gaps aren't tokens
python one-hot-vectors.pynumbers in each vector: 2000
cosine(patio, outdoor): 0.0
cosine(patio, sofa): 0.0
cosine(patio, patio): 1.0
share of training tokens with a vector: 91%
one-hotエンコーディングは、二つの屋外に関する語が、パティオとソファと同じだけ無関係であると告げる。patioとoutdoorのコサイン類似度は0.0であり、patioとsofaのコサイン類似度も同じ値である。1.0となるのは、トークンを自分自身と比較したときだけである。各ベクトルは2000個の数値からなる。ベクトルを与えた2,000トークンは訓練テキストの91%を占める。残りはより稀なトークンであり、この章では扱わない。異なるトークンのどの組も互いに直角に位置しているため、あるトークンについて学習したことを別のトークンに引き継ぐことはできない。
これは第3章のカウントと同じ欠陥が、別の形で現れたものである。one-hotベクトルを読むモデルは、各トークンについて、そのトークン自身が現れる文脈だけから個別に学習しなければならない。稀なトークンについてはほとんど学べず、見たことのない組み合わせについては何も学べない。
実践ルール: トークンどうしを関連づける必要のあるモデルに、one-hotベクトルを入力してはならない。one-hotベクトルは、次の節で行うように、各トークンに対応する学習済みのベクトルを引くための添字としてだけ用いる。
トークンを周囲のトークンで記述する
この行き詰まりを抜ける方法は、単語をその交友関係によって記述することである。patio と outdoor のように、同じ隣接語を持って現れる二つの単語は、たとえ一緒に現れることがまれであっても、似た意味を持つ可能性が高い。この二つはどちらも furniture、chair、umbrella の近くに現れる。そこで、各トークンを隣接するトークンで記述する。すべてのトークンの組について、一方が他方の小さなウィンドウ内、ここでは前後2トークン以内に現れる頻度を数える。ただし、二つの商品のテキストの境界をまたいでは数えない。こうして得られる各トークンの頻度の行は、そのトークンがどのトークンの近くに現れるかを表すベクトルとなる。
訓練分割の名称と説明文で共起を数え、patio の近くに最も頻繁に現れるものを列挙する。
1"""Counts how often each of the 2,000 kept tokens appears within two tokens of another, and lists the six tokens seen most2often near patio. The prose's point rests on that list: punctuation and common words come first."""3import numpy as np45from lib.vectors import BREAK, cooccurrence, training_ids # the book's shared module; BREAK marks the gap between two texts67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8counts = cooccurrence(ids, len(vocabulary)) # how often each token appears within 2 tokens of another9patio = vocabulary.index("patio</w>") # </w> marks a word's last token: patio</w> is the whole word, not a piece of a longer one1011print("training tokens:", f"{int((ids != BREAK).sum()):,}") # RARE tokens count here, since they are tokens; only the BREAK gaps don't12print("vocabulary kept:", f"{len(vocabulary):,}")13print("tokens near patio, counting repeats:", f"{int(counts[patio].sum()):,}") # the row's total, a token counted again at each repeat14for i in np.argsort(-counts[patio], kind="stable")[:6]: # the minus sorts most frequent first; ties keep vocabulary order15 print(f" near patio: {vocabulary[i]:<12} {int(counts[patio, i]):>6,}")
python cooccurrence-counts.pytraining tokens: 2,744,320
vocabulary kept: 2,000
tokens near patio, counting repeats: 8,790
near patio: ,</w> 646
near patio: or</w> 448
near patio: with</w> 433
near patio: your</w> 381
near patio: .</w> 340
near patio: furniture</w> 249
patio から2トークン以内にある 8,790 個のトークン(そこに現れるたびに重複して数える)のうち、最も頻度が高いものは期待外れである。コンマ、or、with、your、ピリオドが並び、パティオに関係のある最初の単語である furniture は、これらより後に現れる。これらのトークンは至る所にあるため、ほとんどすべてのものの近くに現れる。生の頻度の行が主に示すのは、各隣接語がどれだけ一般的かであり、その行の持ち主であるトークンに固有の特徴ではない。
したがって、生の頻度はベクトルとして適さない。頻出する二つのトークンは、意味に関係なく、コンマや with といった頻出する隣接語を共有するために、似て見えてしまう。重要なのは、隣接語がどれだけ一般的かから予想される頻度よりも、そのトークンが、予想より多く持っている隣接語はどれかという点である。
実践ルール: 共起は、モデルが学習するテキストにおいて、2から5トークンの小さなウィンドウ内で数え、文書の境界をまたいでは数えない。生の頻度をそのままベクトルとして使わない。次の節で行うように重み付けし直し、頻出する隣接語が支配的にならないようにする。
共起を意外性で重み付けする
解決策は、各カウントを偶然から予測される値と比較することである。patio と furniture が互いに独立に現れるなら、両者は個々の出現頻度から導かれる程度の頻度で共起するはずである。点相互情報量(pointwise mutual information, PMI)は、実際のカウントが偶然からどれだけ離れているかを測る。すなわち、2 つのトークンが共起する頻度と、偶然に共起するはずの頻度との比の対数である(Church and Hanks, 1990)。トークン a と b について式で書くと、次のようになる。
PMI(a, b) = log [ P(a, b) / (P(a) · P(b)) ]
ここで P(a, b) は、共起カウント全体のうち a と b が一緒に現れたものの割合であり、P(a) と P(b) は各トークンの割合である。PMI は、2 つのトークンが偶然の予測より多く一緒に現れるときに正となり、少ないときに負となる。負の値は信頼できない。「偶然より少ない」とは、たいてい「そもそもほとんど観測されていない」ことを意味するからである。そこで正の PMI(positive PMI, PPMI)では、負の値をすべて 0 に置き換える。本書の共有モジュール lib.vectors は、前の節の共起カウントからこれを 3 行で計算する。各ペアについて偶然が予測するカウント、実際のカウントをそれで割った値の対数、そして負になる場合やペアが一度も現れない場合は 0 とする処理である。
expected = counts.sum(1, keepdims=True) * counts.sum(0, keepdims=True) / total
pmi = np.log(counts / expected)
return np.where(counts > 0, np.maximum(pmi, 0), 0.0)
再重み付けの目的は、頻出する近傍語が支配的になるのを防ぐことである。そこで生のカウントを PPMI に置き換えて、patio の最も強い近傍語を改めて一覧にする。
1"""Reweights the co-occurrence counts with positive PMI, and lists the six tokens with the strongest weight beside patio.2The prose's point rests on that list: the commas and common words of the raw counts are gone."""3import numpy as np45from lib.vectors import cooccurrence, ppmi, training_ids67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8weights = ppmi(cooccurrence(ids, len(vocabulary))) # PPMI of the co-occurrence counts, within the same window of 2 tokens9patio = vocabulary.index("patio</w>") # </w> marks a word's last token: patio</w> is the whole word1011print("share of PPMI entries that are zero:", f"{(weights == 0).mean():.0%}") # zero for pairs that never co-occur and for pairs seen no more often than chance12for i in np.argsort(-weights[patio], kind="stable")[:6]: # the largest weights first; ties keep vocabulary order13 print(f" PPMI with patio: {vocabulary[i]:<12} {weights[patio, i]:.2f}")
python ppmi-neighbours.pyshare of PPMI entries that are zero: 86%
PPMI with patio: porch</w> 4.51
PPMI with patio: deck</w> 4.19
PPMI with patio: backyard</w> 3.97
PPMI with patio: sectional</w> 3.75
PPMI with patio: furniture</w> 3.59
PPMI with patio: garden</w> 3.53
コンマは消えた。PPMI で見た patio の最も強い近傍語は porch、deck、backyard、sectional、furniture、garden である。これらは人がパティオから連想する語であり、偶然よりどれだけ頻繁に近くに現れるかによって順位付けされている。トークンのペアの大半は偶然以上には一緒に現れない。PPMI 行列の 86% が 0 であるのはそのためである。
PPMI ベクトルはすでに有用である。PPMI の行が似ている 2 つのトークンは、特徴的な近傍語も似ているからである。しかし各ベクトルは依然として 2,000 個の数値からなり、大半は 0 である。また、近傍語が関連してはいるが同一ではない 2 つのトークン、たとえば deck と porch は、非零の要素をほとんど共有しないことがある。
実践ルール: 共起カウントをベクトルとして使う前に、正の PMI で再重み付けする。PMI は稀なトークンどうしのペアを過大評価しがちである。そのようなペアは共起がわずかでも偶然よりはるかに高く見えるからである。本章のように頻出するトークンだけを残す、あるいは最小カウントを要求するのは、このためでもある。
カウントを密なベクトルに圧縮する
2,000個の数値からなるPPMIベクトルは、大半が0であり、容量は大きいが情報は少ない。これを短く密なベクトルに圧縮すると、共起の最も強いパターンが残り、ノイズが落ち、正確に一致する近傍語が少ないトークンどうしでも、近傍語が関連していれば近くに配置される。この目的に使う手法が特異値分解(SVD)である。SVDは、PPMIの各行を最もよく再構成する64個の方向を見つけ、各方向を、それが行をどれだけ説明するかによって重み付けする。トークンの、これらの方向に沿った64個の重み付き座標が、そのトークンの新しいベクトルとなる。これが埋め込み(embedding)、すなわちトークンを表す密なベクトルである。メソッドlib.vectors.svd_vectorsがこれらの埋め込みを計算し、各ベクトルを単位長にスケーリングする。そしてlib.vectors.nearestが、任意のベクトルに対してコサイン類似度が最も高いトークンを探す。
6個のトークンについて、それぞれ最も近い4個の近傍語を見ると、64個の数値が何を保持しているかが分かる。
1"""Compresses the PPMI matrix into 64 numbers per token, and lists the four nearest neighbours of six tokens. The prose's2point rests on the first two lists and the last line: patio and outdoor are each other's nearest neighbour, at the cosine printed last."""3from lib.vectors import DIMENSIONS, nearest, svd_vectors # svd_vectors does the PPMI and SVD steps; nearest ranks tokens by cosine similarity45vectors, vocabulary = svd_vectors() # one 64-number row per token, each scaled to unit length6index = {token: i for i, token in enumerate(vocabulary)}78print("dimensions per token:", DIMENSIONS)9for token in ["patio</w>", "outdoor</w>", "sofa</w>", "oak</w>", "blue</w>", "48</w>"]: # </w> marks a word's last token10 neighbours = nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,)) # skip leaves out the token itself, which would otherwise be its own nearest at 1.0011 print(f"{token:<12} -> " + ", ".join(f"{t} {s:.2f}" for t, s in neighbours))12print("cosine(patio, outdoor):", f"{float(vectors[index['patio</w>']] @ vectors[index['outdoor</w>']]):.2f}") # unit-length vectors, so the dot product is the cosine
python svd-neighbours.pydimensions per token: 64
patio</w> -> outdoor</w> 0.84, bistro</w> 0.79, porch</w> 0.79, lounge</w> 0.77
outdoor</w> -> patio</w> 0.84, porch</w> 0.82, indoor</w> 0.80, furniture</w> 0.74
sofa</w> -> sectional</w> 0.93, chaise</w> 0.90, loveseat</w> 0.89, lounge</w> 0.87
oak</w> -> walnut</w> 0.96, veneers</w> 0.90, espresso</w> 0.89, weathered</w> 0.88
blue</w> -> green</w> 0.86, beige</w> 0.86, pur 0.80, abstract</w> 0.79
48</w> -> 36</w> 0.94, 32</w> 0.93, 24</w> 0.92, 30</w> 0.89
cosine(patio, outdoor): 0.84
どのトークンも64個の数値を持つようになり、その近傍語は、家具店のために作られた類語辞典のように読める。patioとoutdoorは互いに最も近い近傍語であり、コサイン類似度は0.84である。one-hotベクトルでは、この値は0であった。sofaはsectional、chaise、loveseatの隣に位置する。oakはwalnutやespressoの隣にあり、これらは木材の仕上げである。blueは他の色の隣にあり、48は、インチで表した他のサイズの隣にある。
これらは何も教えられていない。この手法は、sofaの定義も、色の一覧も、48が数値であるというヒントも見ていない。店のテキストの中で、これらのトークンが同じ種類の近傍語に囲まれて現れることを見つけ、SVDがそれを理由に近くへ配置したのである。これは、第3章のカウントに欠けていた性質である。モデルがpatio bar stoolについて学んだことは、埋め込みを通じてoutdoor bar stoolにも引き継げるようになる。
実践ルール: PPMIはSVDで50次元から300次元の間に圧縮し、結果はこの節と同じ方法で確認する。いくつかのトークンの近傍語を列挙し、読んでみる。近傍語が頻出する機能語ばかりであれば、再重み付けに誤りがある。近傍語が無関係であれば、ウィンドウか語彙が小さすぎる。
近傍の予測でベクトルを学習する
埋め込みを得るもう一つの方法は、予測を通じて学習することである。本書に登場するすべてのニューラル言語モデルは、この方法で自前の埋め込みを得ている。word2vec の背後にある手法である負例サンプリング付きスキップグラム(skip-gram with negative sampling)は、各トークンに2つのベクトルを与える。1つは中心トークンとして現れるときのもの、もう1つは近傍トークンとして現れるときのものである。そして、あるトークンが与えられたとき、その本物の近傍をランダムなトークンから見分けるという、ただ一つのタスクでこれらを学習させる(Mikolov et al., 2013a; Mikolov et al., 2013b)。あるトークンとその本物の近傍の1つについて、モデルは両者のベクトルの内積でその組にスコアを付け、ロジスティック関数でスコアを確率に変換し、その確率が上がるようにベクトルをわずかに動かす。語彙から引いた数個のランダムなノイズトークンについては、確率が下がるようにベクトルを動かす。これを数百万の組にわたって繰り返すと、同じ近傍を持つトークンは似たベクトルを持つようになる。これは偶然ではない。Levy と Goldberg は、このように学習したスキップグラムが、ノイズトークンの数の対数だけ下方にシフトした PMI 行列を実質的に因数分解していることを示した。これは SVD が PPMI を因数分解するのとよく似ている(Levy and Goldberg, 2014)。
中心トークンのベクトルを v、本物の近傍のベクトルを u、各ノイズトークンのベクトルを uₙ、ロジスティック関数を σ とする。σ(s) = 1 / (1 + e⁻ˢ) であり、スコアを確率に変換する。1組あたりのスキップグラム損失は、本物の近傍に対する驚きと、各ノイズトークンが近傍でないことに対する驚きの和である。
L = −log σ(v·u) − Σₙ log σ(−v·uₙ)
そして lib.skipgram.step は、3行の勾配降下法でこれを下げる。ここで real は σ(v·u)、fake は各ノイズトークンについての σ(v·uₙ) を保持し、rate はステップサイズである。
np.add.at(inputs, centre, -rate * grad_v) # move v: towards u, away from each uₙ
np.add.at(outputs, context, -rate * (real - 1)[:, None] * v) # move u towards v
np.add.at(outputs, noise, -rate * fake[:, :, None] * v[:, None, :]) # move each uₙ away from v
1組の本物の近傍、patio と umbrella について、sofa と 48 をノイズトークンとして、3回更新を実行する。中心ベクトルは小さなランダム値から、近傍ベクトルはゼロから始める。これは lib.skipgram.train の初期化と同じである。
1"""Three updates of skip-gram with negative sampling on one real pair, patio and umbrella, with sofa and 48 as noise tokens,2printing each pair's probability before and after. The prose's point rests on the four probability lines: umbrella's rises,3and the noise tokens' fall."""4import numpy as np56from lib.skipgram import sigmoid, step # one gradient step, and the logistic function7from lib.vectors import training_ids89_, vocabulary = training_ids()10rng = np.random.default_rng(2026) # a fixed seed, so the starting vectors are the same on every run11inputs = (rng.random((len(vocabulary), 8)) - 0.5) / 8 # each token's vector as a centre, small and random12outputs = np.zeros((len(vocabulary), 8)) # and as a neighbour: zero, as training starts13centre, context = [vocabulary.index("patio</w>")], [vocabulary.index("umbrella</w>")] # the real pair: patio as the centre, umbrella its real neighbour14noise = np.array([[vocabulary.index("sofa</w>"), vocabulary.index("48</w>")]]) # noise tokens, picked by hand here; training draws them at random151617def chances():18 real = sigmoid(inputs[centre[0]] @ outputs[context[0]])19 fake = sigmoid(outputs[noise[0]] @ inputs[centre[0]])20 return real, fake212223before = chances() # zero neighbour vectors give every score zero, so every probability is one half24for _ in range(3): # three updates on the same pair25 step(np.array(centre), np.array(context), noise, inputs, outputs, rate=1.0) # rate 1.0, far above the 0.025 that training starts from, so three steps show26after = chances()27print("P(umbrella is a real neighbour of patio), before:", f"{before[0]:.3f}")28print("P(umbrella is a real neighbour of patio), after 3 steps:", f"{after[0]:.3f}")29print("P(sofa, 48 are real neighbours), before:", ", ".join(f"{p:.3f}" for p in before[1]))30print("P(sofa, 48 are real neighbours), after 3 steps:", ", ".join(f"{p:.3f}" for p in after[1]))
python skipgram-step.pyP(umbrella is a real neighbour of patio), before: 0.500
P(umbrella is a real neighbour of patio), after 3 steps: 0.525
P(sofa, 48 are real neighbours), before: 0.500, 0.500
P(sofa, 48 are real neighbours), after 3 steps: 0.475, 0.475
学習は本物の近傍を引き寄せ、ランダムなトークンを遠ざける。3回の更新はそれを小さな規模で示している。更新の前は近傍ベクトルがゼロなので、すべてのスコアはゼロであり、σ(0) は 1/2 である。モデルは何も知らない。3回の更新後、umbrella が patio の近傍であるとするスコアは 0.525 となり、0.500 から上がっている。また sofa と 48 は 0.475, 0.475 に下がっている。学習がしているのはこれだけであり、それを数百万回繰り返すのである。
実践ルール: 埋め込みを学習するときは、lib.skipgram.train と同様に、2つ目のベクトル群をゼロから、1つ目を小さなランダム値から始める。ノイズトークンは、頻度の0.75乗に比例して引く。Mikolov らは、これが単純な頻度よりもうまく働くことを見いだした。数百万回実行する前に、1回の更新を手計算で確認すること。確率が誤った方向に動くなら、勾配の符号が誤っている。
学習したベクトルと数え上げたベクトルを比較する
ストアの訓練テキスト全体でskip-gramを訓練すると、数百万回の更新が行われ、その正確な結果は計算機の浮動小数点演算に左右される。浮動小数点演算の挙動はプロセッサごとにわずかに異なる。そのため、訓練は本書自身のコードと固定したシードを用いてrecordings/skipgram.pyで一度だけ実行し、各例はその保存済みベクトルを読み込む。マニフェストには設定が記録されている。ウィンドウは2トークン、次元数は64、1組あたりのノイズトークンは5個、テキストへの走査は2回である。ただし、1つの設定だけは記録されずlib.skipgramの中で固定されている。カンマのように頻度の非常に高いトークンを中心とする組は大半が読み飛ばされ、その閾値は10⁻⁴である。これにより、そうしたトークンが訓練を支配することを防ぐ(Mikolov et al., 2013b。より大きなテキストでは10⁻⁵前後が提案されている)。
記録済みのskip-gramベクトルに対して、同じ6つのトークンの近傍を尋ね、SVDの結果と比較する。
1"""Reads the skip-gram vectors and training losses that recordings/skipgram.py saved, and lists the same six tokens' four2nearest neighbours as the SVD example. The prose's point rests on the two loss lines and on outdoor's nearest neighbour."""3import json45import numpy as np67from lib.vectors import nearest89recorded = "data/recorded/skipgram/" # saved by recordings/skipgram.py, which trains once: its values depend on the machine10vectors = np.load(recorded + "vectors.npy")11vocabulary = json.load(open(recorded + "vocabulary.json", encoding="utf-8"))12losses = np.load(recorded + "losses.npy") # one loss per batch, in training order13index = {token: i for i, token in enumerate(vocabulary)}1415print("training loss, first batch:", f"{losses[0]:.2f}") # index 0: the first batch, when nothing has been learned yet16print("training loss, last 100 batches:", f"{losses[-100:].mean():.2f}")17for token in ["patio</w>", "outdoor</w>", "sofa</w>", "oak</w>", "blue</w>", "48</w>"]:18 neighbours = nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,)) # skip leaves out the token itself19 print(f"{token:<12} -> " + ", ".join(f"{t} {s:.2f}" for t, s in neighbours))
python skipgram-neighbours.pytraining loss, first batch: 4.16
training loss, last 100 batches: 2.05
patio</w> -> porch</w> 0.77, bistro</w> 0.69, garden</w> 0.69, couch</w> 0.67
outdoor</w> -> indoor</w> 0.75, patio</w> 0.66, garden</w> 0.65, living</w> 0.61
sofa</w> -> couch</w> 0.85, sleeper</w> 0.84, chaise</w> 0.80, sectional</w> 0.78
oak</w> -> walnut</w> 0.91, espresso</w> 0.84, weathered</w> 0.81, glossy</w> 0.80
blue</w> -> beige</w> 0.88, gray</w> 0.87, green</w> 0.85, brown</w> 0.80
48</w> -> 36</w> 0.94, 32</w> 0.92, 1.5</w> 0.89, 24</w> 0.89
モデルは、実際の近傍とノイズを見分けることを学習した。訓練時の損失は、最初のバッチの4.16から、直近100バッチの2.05まで下がった。skip-gramの近傍は、ほとんどのトークンでSVDの近傍と一致している。たとえばsofaにはsectionalとchaise、oakにはwalnutとespressoが近く、色は色と、サイズはサイズと並ぶ。一方、他のトークンでは重点が異なる。skip-gramはoutdoorに最も近い語としてindoorを挙げる。これは、indoor or outdoor useのような説明文の中で、この2語が同じ位置に現れるためである。
この違いは注目に値する。近傍から作られたベクトルは、同じ場所で使われる語を近くに集める。反対の意味を持つ語はしばしば同じ場所で使われる。ここではindoorとoutdoorがそうであり、次の節ではsmallがそうである。その最近傍にはlargerだけでなくsmallerも含まれる。ベクトルが似ていることは使われ方が似ていることを意味し、意味が似ていることを意味するわけではない。
実践ルール: 数え上げた埋め込み(PPMIとSVD)と学習した埋め込み(skip-gram)は、互いに近い代替手段として扱う。数百万トークン程度であれば両者は似た近傍を与え、数え上げた埋め込みは決定的で高速である。埋め込みが、いずれにせよ訓練する大きなモデルの一部である場合は、学習した埋め込みを選ぶ。本書の以降のどの章でもそうである。反対の意味を持つ語がないかを確かめずに、高い類似度を同義性として読んではならない。
この部分はまだ翻訳されていないため、英語で表示している。
Analogies, and where they fail
Embeddings famously support analogies by arithmetic: if the difference between chair and chairs is a direction that means "plural", then adding it to table should land near tables. In vectors, the answer to "a is to b as c is to what?" is the token nearest to b − a + c, leaving out the three tokens in the question (Mikolov et al., 2013a). It's a neat test of whether the vectors have learned consistent relationships, and a good place to see their limits.
Three analogies on the skip-gram vectors show where the arithmetic holds and where it breaks, and the nearest neighbours of three tokens they raise show why:
1"""Three analogies on the skip-gram vectors, each answered by the tokens nearest b minus a plus c; whether lamps and light2have vectors at all; and the nearest tokens to a few single words. The prose rests on the three analogy lines, the lamps line and the neighbour lists."""3import json45import numpy as np67from lib.vectors import nearest89vectors = np.load("data/recorded/skipgram/vectors.npy") # saved by recordings/skipgram.py, which trains once10vocabulary = json.load(open("data/recorded/skipgram/vocabulary.json", encoding="utf-8"))11index = {token: i for i, token in enumerate(vocabulary)}1213for a, b, c in [("chair", "chairs", "table"), ("chair", "chairs", "lamp"), ("black", "white", "dark")]: # each reads: a is to b as c is to what14 a, b, c = (word + "</w>" for word in (a, b, c)) # the tokenizer marks each word's last token with </w>, so words are looked up in that form15 query = vectors[index[b]] - vectors[index[a]] + vectors[index[c]] # b - a + c: "c, changed the way a became b"16 answers = nearest(vectors, vocabulary, query, k=3, skip=(a, b, c)) # the words in the question can't be their own answer17 print(f"{a} : {b} :: {c} : ? -> " + ", ".join(t for t, _ in answers))18print("lamps in the vocabulary:", "lamps</w>" in index)19print("light in the vocabulary:", "light</w>" in index)20for token in ["light</w>", "dark</w>", "small</w>"]:21 print(f"{token:<12} -> " + ", ".join(t for t, _ in nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,))))
python analogies.pychair</w> : chairs</w> :: table</w> : ? -> tables</w>, cup</w>, stools</w>
chair</w> : chairs</w> :: lamp</w> : ? -> tops</w>, coffee</w>, tray</w>
black</w> : white</w> :: dark</w> : ? -> brown</w>, blue</w>, glossy</w>
lamps in the vocabulary: False
light in the vocabulary: True
light</w> -> lights</w>, bulb</w>, dimmable</w>, candle</w>
dark</w> -> brown</w>, walnut</w>, gray</w>, espresso</w>
small</w> -> smaller</w>, larger</w>, displaying</w>, storing</w>
Only the first analogy gets the answer you'd expect: chair is to chairs as table is to tables, the top answer. The second fails because lamps isn't among the 2,000 tokens that have vectors, so the right answer can't be found at all, and the arithmetic returns whatever is nearest. The third fails differently. light is in the vocabulary, but black is to white as dark is to brown, by the vectors' reckoning. The neighbour lists show why: light sits with lights, bulb, dimmable and candle, because in the store's text it's mostly a lamp, as in ceiling light, not a shade, while dark sits with brown, walnut and espresso, the finishes it describes. And small sits with larger as well as smaller: size words appear in the same places, whichever size they name.
Analogies are a demonstration, not a measure. They work for relationships the text expresses consistently and often, such as plurals of common words, and fail for rare words, for words with several senses, and for relationships the text rarely spells out. A model doesn't use analogies; it uses the vectors' positions, and those carry the same strengths and blind spots.
Working rule: Don't judge embeddings by analogies; judge them by how much they help the task they're for, as the next section and every later chapter do. When an analogy fails, check whether the answer is in the vocabulary and whether the words mean what you assume in your text.
ベクトルで似た名前を探す
トークンの埋め込みに、もう一段階の処理を加えると、テキスト全体の埋め込みが得られる。テキストに含まれるトークンのベクトルを平均し、その結果を単位長にスケーリングすると、似たテキストは似たベクトルを持つようになる。これは、検索エンジンが意味検索(semantic retrieval)と呼ぶものの粗いバージョンであり、単語の一致ではなく意味によってテキストを探す手法である。本書の姉妹編である A Primer on Search Relevance では、訓練済みモデルを使ってこれを本格的に構築している(semantic retrieval)。ここでは、この章が解決しようと掲げた問題を確かめるために用いる。第3章のカウントに基づくモデルは、outdoor bar と patio bar を関連づけられなかった。
訓練データに含まれるすべての名前について、スキップグラムのベクトルを平均すると、各名前が 1 つのベクトルになる。まれな単語は、多くの場合は製品ラインの名前であり、第1章で説明したとおり [name] と表示される。2 つのクエリでこの方法の効果を見る。1 つは outdoor bar で、第3章の 4-gram モデルが扱えなかった接頭辞である。もう 1 つは patio umbrella である。
1"""Averages each training name's skip-gram token vectors into one unit-length vector, and prints the four training names2nearest to each of two queries. The prose's point rests on the first query: two patio bar stool names come up for outdoor bar."""3import json45import numpy as np67from lib import bpe8from lib.store import load_products, masked910vectors = np.load("data/recorded/skipgram/vectors.npy")11vocabulary = json.load(open("data/recorded/skipgram/vocabulary.json", encoding="utf-8"))12index, tokenizer = {t: i for i, t in enumerate(vocabulary)}, bpe.store_tokenizer()131415def name_vector(text): # the average of the text's token vectors, at unit length16 found = [index[t] for t in tokenizer.encode(text) if t in index] # tokens outside the 2,000 kept have no vector, so they're left out17 average = vectors[found].mean(0) if found else np.zeros(vectors.shape[1]) # a text with no kept tokens gets the zero vector18 return average / (np.linalg.norm(average) or 1.0) # `or 1.0`: a zero average stays zero, rather than dividing by zero192021names = load_products("train")["name"].tolist() # the training split's product names, the texts to compare22matrix = np.array([name_vector(n) for n in names])23for query in ["outdoor bar", "patio umbrella"]:24 best = np.argsort(-(matrix @ name_vector(query)), kind="stable")[:4] # unit vectors, so the dot product is the cosine; the four largest, most similar first25 print(f"{query}: " + " | ".join(masked(names[i]) for i in best)) # [name]: a rare word
python name-vectors.pyoutdoor bar: outdoor modern industrial 5 piece bar height dining set | [name] bar & bar stool | 29.5 '' patio bar stool | 28.5 '' patio bar stool
patio umbrella: premium tight weave outdoor patio umbrella cover | patio lantern | garden patio 88 [name] rattan deck box | outdoor patio chair
平均したベクトルでは、patio bar stool を含む 2 つの名前が outdoor bar に最も近いものに入り、そのどちらにも単語 outdoor は含まれていない。そのモデル(第3章のモデル)にはこの関連づけができなかった。patio bar stool についてはカウントがあったが、outdoor bar についてはなかったからである。この関連は outdoor と patio を通っており、両者のベクトルは近い。patio umbrella については、最も近い名前はパティオ用品とアウトドア用品であり、最上位はパラソルのカバーである。しかし、そのどれもパラソルそのものではない。平均によって、patio が umbrella より大きく効いてしまうのである。
平均は粗い方法である。語順を無視するため、bar stool と stool bar は同じベクトルになり、頻出するトークンが重要なトークンを埋もれさせてしまう。しかし、本書の以降のすべてのモデルが拠り所とする性質は、これで確認できる。ワンホットのトークンではなく埋め込みを読むモデルは、あるフレーズについて学んだことを別のフレーズに持ち越せるのである。
実践ルール: 短いテキストを手早く順序に依存しない形で表現したいときは、トークンの埋め込みを平均する。ただし、関連する項目は見つかるが、順位づけは緩いものになると考えておく。本格的な意味検索には、Primer のように、そのために訓練されたモデルを使う。言語モデリングでは、埋め込みそのものをモデルに与え、それらをどう組み合わせるかをモデルに学習させる。これは第5章で始まる。
本番環境で起こる問題
埋め込みは、学習に使われたテキストの癖を、それを利用するあらゆるものに持ち込む。
- 用法が似ていても意味が似ているとは限らない。
indoorとoutdoorは近くに位置する。近いベクトルを互いに置き換え可能なものとして扱うシステムは、反対の意味の語を平然と取り替えてしまう。製品が依存する語については、最近傍の語を確認すること。 - まれなトークンや新しいトークンには、質の低いベクトルが与えられるか、まったく与えられない。 この章では2,000個のトークンを保持した。この一覧にないトークンにはベクトルがなく、数回しか現れなかったトークンのベクトルにはノイズが多い。ストアのトークナイザーが持つトークンはその2倍より多く、まれな語がトークナイザーによって複数の断片に分割された場合、その語のベクトルは、断片のうち2,000個に含まれるものからしか得られない。後続の各章のモデルのように、独自に埋め込みを学習するモデルは、語彙全体を扱える。
- ベクトルは元になったテキストを反映する。 ストアのテキストでは
lightはランプとして説明されているため、そのベクトルは照明に関する語の近くに位置する。ある領域で学習した埋め込みは、その領域での語義や偏りを別の領域に持ち込む。 - レシピではなくベクトルを出荷する。 勾配降下法で埋め込みを学習すると、プロセッサが異なればベクトルがわずかに異なる。本書がベクトルを記録しているのはこのためである。出荷するベクトルは、それを作ったコードや設定とともに保存すること。
- 埋め込みは古くなる。 カタログには新しい製品ラインや語が現れる。語彙が変化したら、埋め込みを再学習するか拡張すること。再学習のたびに、重要なトークンの近傍リストを確認すること。
この章で決めたこと
- トークンは、ベクトルのコサイン類似度で比較する。 コサイン類似度は長さを無視して向きを比較するものであり、
lib.vectors.nearestが返す値でもある。すべてのベクトルをあらかじめ単位長に正規化するため、コサインは単なる内積になり、生のベクトルが長い高頻度トークンが、その大きさによって有利になることはない。 - カウントに基づく埋め込みは、正の PMI を SVD で圧縮して得る。
lib.vectorsでは、幅2トークンのウィンドウと頻度上位2,000トークンを用いる。店舗のテキストでは、この埋め込みはpatioをoutdoorの近くに配置する。one-hot ベクトルにはこれができなかった。 - 学習による埋め込みは、負例サンプリングを用いたスキップグラムで得る。 正確な値は実行するマシンに依存するため、
recordings/skipgram.pyで本書自身のコードと固定したシードを使って一度だけ学習する。この埋め込みは、ほとんどのトークンについてカウントに基づく埋め込みと一致する。 - 似たベクトルは、似た使われ方を意味する。
indoorとoutdoorのような反意語は近いベクトルを持つ。類推が成り立つのは、テキストが頻繁に表現する関係に限られる。そのため本書は、埋め込みを類推ではなく、タスクにどれだけ役立つかで評価する。 - 以降のモデルはすべて、自前の埋め込みを学習する。 埋め込みは次のトークンを予測する過程の一部として学習され、最初は第5章のニューラル言語モデルである。この章のベクトルは、埋め込みがある文脈から別の文脈へ知識を運ぶことを示しており、本書の以降のモデルはこの性質を活用する。
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格
英語版の書籍(版2026.11.16)から翻訳した。