当前位置:   article > 正文

Transformer 位置编码(Positional Encoding)_positional encoding绘图代码

positional encoding绘图代码

原式(见1706.03762.pdf (arxiv.org)

PE(pos, 2i) =sin(\frac{pos}{10000^{\frac{2i}{d_{model}}}})

 PE(pos, 2i+1) =cos(\frac{pos}{10000^{\frac{2i}{d_{model}}}})

合并化简得

PE(pos, i) =\left\{\begin{matrix} sin(\frac{pos}{10000^{\frac{i}{d_{model}}}}) & \text{if i is even} \\ cos(\frac{pos}{10000^{\frac{i-1}{d_{model}}}}) & \text{if i is odd} \end{matrix}\right.

参数解读:

  • pos: 词向量的位置
  • i:维度的位置
  • d_{model}:词向量的维度大小

以一个2个词,每个词维度维度为4的输入为例:

维度0(i=0)维度1(i=1)维度2(i=2)维度3(i=3)
词向量0(pos=0)sin(\frac{0}{10000^{\frac{0}{4}}})cos(\frac{0}{10000^{\frac{0}{4}}})sin(\frac{0}{10000^{\frac{2}{4}}})cos(\frac{0}{10000^{\frac{2}{4}}})
词向量1(pos=1)sin(\frac{1}{10000^{\frac{0}{4}}})cos(\frac{1}{10000^{\frac{0}{4}}})sin(\frac{1}{10000^{\frac{2}{4}}})cos(\frac{1}{10000^{\frac{2}{4}}})

由上可见,位置编码与词向量所包含的值无关,仅与位置和维度大小有关。 

代码示例如下: 

  1. import numpy as np
  2. def PE(pos, i, dmodel):
  3. n = 10000
  4. if i % 2 == 0:
  5. # i is even
  6. return np.sin(pos / np.power(n, (i / dmodel)))
  7. else:
  8. # i is odd
  9. return np.cos(pos / np.power(n, ((i - 1) / dmodel)))
  10. sample = np.zeros((2, 4)) # 2 word vectors; each vector has four dimensions
  11. dmodel = sample.shape[1]
  12. for pos in range(sample.shape[0]):
  13. for i in range(sample.shape[1]):
  14. sample[pos][i] = np.round(PE(pos, i, dmodel), 5)
  15. print(sample)
  16. # output
  17. # [[0. 1. 0. 1. ]
  18. # [0.84147098 0.54030231 0.00999983 0.99995 ]]
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/360960
推荐阅读
相关标签
  

闽ICP备14008679号