tf.nn.embedding_lookup用法解释

tf.nn.embedding_lookup( params, ids, …),主要使用params, ids两个参数,函数的功能是从params中挑出索引为ids的元素,并返回一个张量,
假设params的shape是batch * hidden, ids的shape是batch * n
那么函数返回张量的shape是batch *n * hidden

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import tensorflow as tf
w = tf.constant([[1,2],[3,4],[5,6]])
res = tf.nn.embedding_lookup(w, [0,1,0])
res2 = tf.nn.embedding_lookup(w, [[0],[1],[0]])
res4 = tf.nn.embedding_lookup(w, [[0,0,0,0],[1,1,1,1],[0,0,0,0]])
with tf.Session() as sess:
res,res2,res4 = sess.run([res,res2,res4])
print res,res.shape
print res2,res2.shape
print res4,res4.shape

'''
打印结果
res: (3, 2)
[[1 2]
[3 4]
[1 2]]

res2:(3, 1, 2)
[[[1 2]]

[[3 4]]

[[1 2]]]

res4: (3, 4, 2)
[[[1 2]
[1 2]
[1 2]
[1 2]]

[[3 4]
[3 4]
[3 4]
[3 4]]

[[1 2]
[1 2]
[1 2]
[1 2]]] (3, 4, 2)
'''
0%