tf.nn.embedding_lookup()

本文介绍如何使用 TensorFlow 的 embedding_lookup 函数实现基于索引的向量查找,并展示具体的 Python 代码示例及运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

a = np.identity(5, dtype=np.int32)
a[0,0] = 0
a[0,1] = 1
#print(a)

tf.reset_default_graph()


ids = tf.placeholder(tf.int32, shape=None)
embedding = tf.Variable(a)
embedding_look = tf.nn.embedding_lookup(embedding, ids)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    print(sess.run(embedding))
    
    print("\n")
    
    print(sess.run(embedding_look, feed_dict={ids:[1, 2, 3]}))

结果为:

[[0 1 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]

[[0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]]

当输入的ids为,

[[0, 1], 
 [1, 2]]


结果为:

 

[[0 1 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]


[[[0 1 0 0 0]
  [0 1 0 0 0]]

 [[0 1 0 0 0]
  [0 0 1 0 0]]]

此函数用ids中的元素值当做tensor的下标,去查找embedding数组(tensor)中的对应行,然后组成一个新的数组返回。

返回的shape为:[ids.shape, params.shape[1]] #params 即为上述代码中所使用的embedding 查找表

 

 


embedding_matrix is a tensor of shape [vocabulary_size, embedding size]

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值