プリンキピア

第11章注意機構とTransformer

11.2. Attention Pooling by Similarity11.2 類似度による注意プーリング

Now that we have introduced the primary components of the attention mechanism, let’s use them in a rather classical setting, namely regression and classification via kernel density estimation (Nadaraya, 1964, Watson, 1964). This detour simply provides additional background: it is entirely optional and can be skipped if needed. At their core, Nadaraya–Watson estimators rely on some similarity kernel α(𝐪,𝐤) relating queries 𝐪 to keys 𝐤. Some common kernels are
英語のヒント
注意機構の主な部品を紹介したので、それらをかなり古典的な設定、つまりカーネル密度推定による回帰と分類で使ってみよう(Nadaraya, 1964、Watson, 1964)。この寄り道は追加の背景を与えるだけであり、まったく任意なので、必要なら飛ばしてかまわない。中核では、ナダラヤ・ワトソン推定量は、クエリ𝐪をキー𝐤に結びつける何らかの類似度カーネルα(𝐪,𝐤)に頼っている。よく使われるカーネルには次のものがある。
α(𝐪,𝐤)=exp⁡(−12∥𝐪−𝐤∥2)Gaussian;α(𝐪,𝐤)=1 if ∥𝐪−𝐤∥≤1Boxcar;α(𝐪,𝐤)=max⁡(0,1−∥𝐪−𝐤∥)Epanechikov.(11.2.1)
There are many more choices that we could pick. See a Wikipedia article for a more extensive review and how the choice of kernels is related to kernel density estimation, sometimes also called Parzen Windows (Parzen, 1957). All of the kernels are heuristic and can be tuned. For instance, we can adjust the width, not only on a global basis but even on a per-coordinate basis. Regardless, all of them lead to the following equation for regression and classification alike:
英語のヒント
ほかにも選べるものはたくさんある。もっと広い概観や、カーネルの選び方が、パルツェン窓(Parzen, 1957)とも呼ばれるカーネル密度推定とどう関係するかについては、ウィキペディアの記事を見てほしい。カーネルはどれも経験則にもとづくもので、調整できる。たとえば、幅を全体で調整するだけでなく、座標ごとに調整することさえできる。いずれにせよ、どれも回帰と分類のどちらについても次の式につながる。
f(𝐪)=∑i𝐯iα(𝐪,𝐤i)∑jα(𝐪,𝐤j).(11.2.2)
In the case of a (scalar) regression with observations (𝐱i,yi) for features and labels respectively, 𝐯i=yi are scalars, 𝐤i=𝐱i are vectors, and the query 𝐪 denotes the new location where f should be evaluated. In the case of (multiclass) classification, we use one-hot-encoding of yi to obtain 𝐯i. One of the convenient properties of this estimator is that it requires no training. Even more so, if we suitably narrow the kernel with increasing amounts of data, the approach is consistent (Mack and Silverman, 1982), i.e., it will converge to some statistically optimal solution. Let’s start by inspecting some kernels.
英語のヒント
(スカラーの)回帰で、特徴量とラベルの観測がそれぞれ(𝐱i,yi)の場合、𝐯i=yiはスカラー、𝐤i=𝐱iはベクトルであり、クエリ𝐪はfを評価すべき新しい位置を表す。(多クラスの)分類の場合は、yiのワンホット符号化を使って𝐯iを得る。この推定量の便利な性質の一つは、訓練が要らないことである。さらに、データの量が増えるにつれてカーネルを適切に狭めれば、このやり方は一致性をもつ(Mack and Silverman, 1982)。つまり、統計的に最適な何らかの解に収束する。いくつかのカーネルを調べることから始めよう。
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l

d2l.use_svg_display()