查詢(自主提示)和鍵(非自主提示)之間的交互形成了注意力匯聚; 注意力匯聚有選擇地聚合了值(感官輸入)以生成最終的輸出。 本節將介紹注意力匯聚的更多細節, 以便從宏觀上了解注意力機制在實踐中的運作方式。 具體來說,1964年提出的Nadaraya-Watson核回歸模型 是一個簡單但完整的例子,可以用于演示具有注意力機制的機器學習。
import torch
from torch import nn
from d2l import torch as d2l
生成數據集
在這里生成了50個訓練樣本和\(50\)個測試樣本。 為了更好地可視化之后的注意力模式,需要將訓練樣本進行排序。
n_train = 50 # 訓練樣本數
x_train, _ = torch.sort(torch.rand(n_train) * 5) # 排序后的訓練樣本def f(x):return 2 * torch.sin(x) + x**0.8y_train = f(x_train) + torch.normal(0.0, 0.5, (n_train,)) # 訓練樣本的輸出
x_test = torch.arange(0, 5, 0.1) # 測試樣本
y_truth = f(x_test) # 測試樣本的真實輸出
n_test = len(x_test) # 測試樣本數
n_test
下面的函數將繪制所有的訓練樣本(樣本由圓圈表示), 不帶噪聲項的真實數據生成函數\(f\)(標記為“Truth”), 以及學習得到的預測函數(標記為“Pred”)。
def plot_kernel_reg(y_hat):d2l.plot(x_test, [y_truth, y_hat], 'x', 'y', legend=['Truth', 'Pred'],xlim=[0, 5], ylim=[-1, 5])d2l.plt.plot(x_train, y_train, 'o', alpha=0.5);
平均匯聚
如下圖所示,這個估計器確實不夠聰明。 真實函數(f)(“Truth”)和預測函數(“Pred”)相差很大。
y_hat = torch.repeat_interleave(y_train.mean(), n_test)
plot_kernel_reg(y_hat)
?