直接看代码吧~
tensorflow学习笔记--embedding_lookup()用法_STHSF的博客-CSDN博客
#!/usr/bin/env/python
# coding=utf-8
import tensorflow as tf
import numpy as np
tf.__version__ # '1.15.0'
input_ids = tf.placeholder(dtype=tf.int32, shape=[None, None])
input_ids
# <tf.Tensor 'Placeholder:0' shape=(?, ?) dtype=int32>
embedding = tf.Variable(np.identity(5, dtype=np.int32))
embedding
# <tf.Variable 'Variable:0' shape=(5, 5) dtype=int32_ref>
input_embedding = tf.nn.embedding_lookup(embedding, input_ids)
input_embedding
# <tf.Tensor 'embedding_lookup/Identity:0' shape=(?, ?, 5) dtype=int32>
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("embedding")
print(embedding.eval())
input_embedding = tf.nn.embedding_lookup(embedding, input_ids)
print('-'*10)
print(input_embedding.shape)
print(sess.run(input_embedding, feed_dict={input_ids:[[1, 2], [2, 1], [3, 3]]}))
print('-'*10)
print(input_embedding.get_shape().as_list())
embedding输出:
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]
----------
(?, ?, 5)
[[[0 1 0 0 0]
[0 0 1 0 0]] # [1, 2],从embeding中直接查找index=1,index=2的向量
[[0 0 1 0 0]
[0 1 0 0 0]] # [2, 1],从embeding中直接查找index=2,index=1的向量
[[0 0 0 1 0]
[0 0 0 1 0]]] # [3, 3],从embeding中直接查找index=3,index=3的向量
----------
[None, None, 5]
embedding层_tensorflow中的Embedding操作详解_weixin_39835321的博客-CSDN博客