栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Transformer模型中位置编码的实现

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Transformer模型中位置编码的实现

import numpy as np

"""
	FGGen模型中的PosEncoding
"""
def GetPosEncodingMatrix(max_len, d_emb):
	'''
	对应文章中的使用sine和consine function去做positional encodings
	PE(pos,2i)= sin(pos/10000^2i/dmodel)
	'''
	pos_enc = np.array([
		[pos / np.power(10000, 2 * (j // 2) / d_emb) for j in range(d_emb)]
		if pos != 0 else np.zeros(d_emb)
			for pos in range(max_len)
			])
	pos_enc[1:, 0::2] = np.sin(pos_enc[1:, 0::2]) # dim 2i
	pos_enc[1:, 1::2] = np.cos(pos_enc[1:, 1::2]) # dim 2i+1
	return pos_enc


def GetPosEncodingMatrix_myself(max_len, d_emb):
	# PE(pos,2i)= sin(pos/10000^2i/dmodel)
	pos_enc = []
	for pos in range(max_len):
		row = [pos / np.power(10000, 2 * (j // 2) / d_emb) for j in range(d_emb)]
		pos_enc.append(row)
	pos_enc = np.array(pos_enc)
	pos_enc[1:, 0::2] = np.sin(pos_enc[1:, 0::2])  # dim 2i
	pos_enc[1:, 1::2] = np.cos(pos_enc[1:, 1::2])  # dim 2i+1
	return pos_enc


if __name__ =="__main__":
	value1 = GetPosEncodingMatrix(60, 512)
	value2 = GetPosEncodingMatrix_myself(60, 512)
	equal_cnt = 0
	for i in range(value1.shape[0]):
		for j in range(value1.shape[1]):
			if value1[i][j] == value2[i][j]:
				equal_cnt += 1
			else:
				print("Error")
	print(equal_cnt)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号