プリンキピア

第11章注意機構とTransformer

11.2.1. Kernels and Data11.2.1 カーネルとデータ

All the kernels α(𝐤,𝐪) defined in this section are translation and rotation invariant; that is, if we shift and rotate 𝐤 and 𝐪 in the same manner, the value of α remains unchanged. For simplicity we thus pick scalar arguments k,q∈ℝ and pick the key k=0 as the origin. This yields:
英語のヒント
この節で定義するカーネルα(𝐤,𝐪)はどれも、平行移動と回転に対して不変である。つまり、𝐤と𝐪を同じやり方でずらしたり回転させたりしても、αの値は変わらない。そのため、簡単にするため、スカラーの引数k,q∈ℝを選び、キーk=0を原点に選ぶ。すると次が得られる。
# Define some kernels
def gaussian(x):
    return torch.exp(-x**2 / 2)

def boxcar(x):
    return torch.abs(x) < 1.0

def constant(x):
    return 1.0 + 0 * x

def epanechikov(x):
    return torch.max(1 - torch.abs(x), torch.zeros_like(x))

fig, axes = d2l.plt.subplots(1, 4, sharey=True, figsize=(12, 3))

kernels = (gaussian, boxcar, constant, epanechikov)
names = ('Gaussian', 'Boxcar', 'Constant', 'Epanechikov')
x = torch.arange(-2.5, 2.5, 0.1)
for kernel, name, ax in zip(kernels, names, axes):
    ax.plot(x.detach().numpy(), kernel(x).detach().numpy())
    ax.set_xlabel(name)

d2l.plt.show()
Different kernels correspond to different notions of range and smoothness. For instance, the boxcar kernel only attends to observations within a distance of 1 (or some otherwise defined hyperparameter) and does so indiscriminately.
英語のヒント
異なるカーネルは、範囲となめらかさの異なる考え方に対応する。たとえば、箱型カーネルは、距離1(あるいは別に定義したハイパーパラメータ)以内の観測にだけ注意を向け、それを区別なく行う。
To see Nadaraya–Watson estimation in action, let’s define some training data. In the following we use the dependency
英語のヒント
ナダラヤ・ワトソン推定が実際に働くところを見るため、訓練データを定義しよう。以下では、次の依存関係を使う。
yi=2sin⁡(xi)+xi+ϵ,(11.2.3)
where ϵ is drawn from a normal distribution with zero mean and unit variance. We draw 40 training examples.
英語のヒント
ここで、ϵは平均0、分散1の正規分布から引かれる。40個の訓練事例を引く。
def f(x):
    return 2 * torch.sin(x) + x

n = 40
x_train, _ = torch.sort(torch.rand(n) * 5)
y_train = f(x_train) + torch.randn(n)
x_val = torch.arange(0, 5, 0.1)
y_val = f(x_val)