【发布时间】:2018-03-09 04:28:30
【问题描述】:
在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')
我不明白这个矩阵如何提供有关输入位置的信息。有人可以先告诉我这是否是计算它的正确方法,其次是什么原理?
谢谢。
【问题讨论】:
标签: python machine-learning tensorflow nlp deep-learning