Attention Is All You Needでは、著者は位置埋め込み(単語がシーケンス内のどこにあるかに関する情報を追加する)を実装しています。このため、正弦波埋め込みを使用します。正弦波埋め込み - 注意が必要です。
PE(pos,2i) = sin(pos/10000**(2*i/hidden_units))
PE(pos,2i+1) = cos(pos/10000**(2*i/hidden_units))
ここで、posは位置、iは次元です。それは、形状[max_length、embedding_size]の埋め込み行列をもたらさなければならない、すなわち、シーケンス中の位置を与えられれば、PE [position ,:]のテンソルを返す。
Kyubyong'sの実装が見つかりましたが、完全に理解していません。
私はnumpyの中で次のようにそれを実装しようとした:
hidden_units = 100 # Dimension of embedding
vocab_size = 10 # Maximum sentence length
# Matrix of [[1, ..., 99], [1, ..., 99], ...]
i = np.tile(np.expand_dims(range(hidden_units), 0), [vocab_size, 1])
# Matrix of [[1, ..., 1], [2, ..., 2], ...]
pos = np.tile(np.expand_dims(range(vocab_size), 1), [1, hidden_units])
# Apply the intermediate funcitons
pos = np.multiply(pos, 1/10000.0)
i = np.multiply(i, 2.0/hidden_units)
matrix = np.power(pos, i)
# Apply the sine function to the even colums
matrix[:, 1::2] = np.sin(matrix[:, 1::2]) # even
# Apply the cosine function to the odd columns
matrix[:, ::2] = np.cos(matrix[:, ::2]) # odd
# Plot
im = plt.imshow(matrix, cmap='hot', aspect='auto')
私はこの行列は、入力の位置に関する情報を与えることができる方法を理解していません。誰かが最初に、これが正しい計算方法であるのか、その背後に根拠があるのかを教えてもらえますか?
ありがとうございます。
自由にお答えください。 – greeness