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

embedding

Python 更新时间:发布时间: 百科书网 趣学号

embedding_lookup,embedding_lookup_sparse,safe_embedding_lookup_sparse的使用
  • 1. 总结
  • 2. embedding_lookup
  • 3. embedding_lookup_sparse
    • 3.1 tf.SparseTensor
    • 3.2 embedding_lookup_sparse使用
    • 3.3 稠密矩阵和稀疏矩阵之间的相互转换
      • 3.3.1 稀疏矩阵转稠密矩阵
      • 3.3.1 稠密矩阵转稀疏矩阵
  • 4. safe_embedding_lookup_sparse

1. 总结 2. embedding_lookup

embedding_lookup有两个必选参数:params和ids,即返回ids指向的embedding。
embedding_lookup是三个lookup中最简单的一个,直接举例说明。

# 创建一个长度为4,维度为5的embedding矩阵
# array([[ 0,  1,  2,  3,  4],
#        [ 5,  6,  7,  8,  9],
#        [10, 11, 12, 13, 14],
#        [15, 16, 17, 18, 19]])
EmbMat = tf.constant(np.arange(20).reshape(4,5))
ids = [1,3] # 取出Emb中索引为1和3的embedding
emb = tf.nn.embedding_lookup(EmbMat, ids)
with tf.Session() as sess:
    emb_val = sess.run(emb)
# emb_val
# array([[ 5,  6,  7,  8,  9],
#        [15, 16, 17, 18, 19]])
3. embedding_lookup_sparse 3.1 tf.SparseTensor

构造SparseTensor需要传入三个参数:

  • dense_shape:SparseTensor的矩阵维度
  • indices:非0值所在的位置
  • values:indices中所表示的非0值位置的值

如:

SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])

表示的稀疏矩阵为:

[[1, 0, 0, 0]
 [0, 0, 2, 0]
 [0, 0, 0, 0]]
3.2 embedding_lookup_sparse使用
# 创建一个长度为4,维度为5的embedding矩阵
# array([[ 0.,  1.,  2.,  3.,  4.],
#        [ 5.,  6.,  7.,  8.,  9.],
#        [10., 11., 12., 13., 14.],
#        [15., 16., 17., 18., 19.]])
EmbMat = tf.constant(np.arange(20).reshape(4,5).astype('f'))
# 创建SparseTensor
st = tf.SparseTensor(dense_shape=[3, 4],
                     indices=[[0, 1],[0, 2],
                              [1, 0],[1, 2],
                              [2, 3]],
                     values=[1,2,0,2,3])
# 根据稀疏向量SparseTensor,按照每一行取出embedding,并聚合(默认为mean)
emb = tf.nn.embedding_lookup_sparse(EmbMat, st, sp_weights=None)
with tf.Session() as sess:
    emb_val = sess.run(emb)
# emb_val
# array([[ 7.5,  8.5,  9.5, 10.5, 11.5],
#        [ 5. ,  6. ,  7. ,  8. ,  9. ],
#        [15. , 16. , 17. , 18. , 19. ]], dtype=float32)
3.3 稠密矩阵和稀疏矩阵之间的相互转换

此外,TF还提供了稀疏矩阵转换为稠密矩阵的函数:

3.3.1 稀疏矩阵转稠密矩阵
dt = tf.sparse_tensor_to_dense(st)
with tf.Session() as sess:
    val = sess.run(dt)
3.3.1 稠密矩阵转稀疏矩阵
def dense2sparse(dense):
    """
    稠密矩阵转稀疏矩阵
    tf.sparse_tensor_to_dense逆向操作
    dense: 稠密矩阵
    """
    where = tf.not_equal(dense, 0)
    indices = tf.where(where)
    values = tf.gather_nd(dense, indices)
    return tf.SparseTensor(indices, values, dense.shape)
4. safe_embedding_lookup_sparse

与embedding_lookup_sparse功能相同,针对有效地IDs。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/293850.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号