import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
# 稀疏tensor构造
import numpy as np
A = tf.constant(np.random.rand(3,2,3) < 0.3, shape=(3,2,3), dtype=tf.float32)
B = tf.sparse.from_dense(A)
# 构造稀疏矩阵例子
A = tf.constant(np.random.rand(2,4) < 0.3, shape=(2,4), dtype=tf.float32)
sp_x = tf.sparse.from_dense(A)
W = tf.constant([[1,2,3,4],
[-1,-2,-3,-4],
[5,6,7,8],
[-5,-6,-7,-8.0]])
# 稀疏矩阵乘法做 embedding
X = tf.sparse_tensor_dense_matmul(sp_x, W)
# sparse lookup
sp_y = tf.SparseTensor(sp_x.indices, sp_x.indices[:,1], sp_x.dense_shape)
Y = tf.nn.safe_embedding_lookup_sparse(W, sp_y, combiner='sum')
# embedding_lookup 实现
ids, idx = tf.unique(sp_x.indices[:,1])
segment_ids = tf.cast(sp_x.indices[:,0], tf.int32)
embeddings = tf.nn.embedding_lookup(W, ids, partition_strategy='mod')
Z = tf.sparse_segment_sum(embeddings, idx, segment_ids)
Y.eval(), X.eval(), Z.eval()