【问题标题】:Sinusoidal embedding - Attention is all you need正弦嵌入 - 只需要注意
【发布时间】: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


    【解决方案1】:

    我在pytorch implementation找到了答案:

    # keep dim 0 for padding token position encoding zero vector
    position_enc = np.array([
        [pos / np.power(10000, 2*i/d_pos_vec) for i in range(d_pos_vec)]
        if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])
    
    position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim 2i
    position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2]) # dim 2i+1
    return torch.from_numpy(position_enc).type(torch.FloatTensor)
    

    其中 d_pos_vec 是嵌入维度,n_position 是最大序列长度。

    编辑:

    在论文中,作者说嵌入矩阵的这种表示允许“模型推断出比训练期间遇到的序列长度更长的序列长度”。

    两个位置之间的唯一区别是pos 变量。查看下图以获取图形表示。

    【讨论】:

    • 您能解释一下您的可视化吗? @马克西姆
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2018-12-22
    相关资源
    最近更新 更多