我正在尝试将未压缩的稀疏数组转换为tf.SparseTensor可接受的格式。有一个内置的函数tf.sparse_to_dense,它的作用与我要做的完全相反。那么我的问题是,Tensorflow或Python中是否有内置函数来执行此转换?
发布于 2017-02-09 11:38:56
你可以这样做:
您可以使用tf.where和tf.gather_nd来完成此操作:
a = np.reshape(np.arange(24), (3, 4, 2))
with tf.Session() as sess:
a_t = tf.constant(a)
idx = tf.where(tf.not_equal(a_t, 0))
# Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape() if tensor shape is dynamic
sparse = tf.SparseTensor(idx, tf.gather_nd(a_t, idx), a_t.get_shape())
dense = tf.sparse_tensor_to_dense(sparse)
b = sess.run(dense)
np.all(a == b)
>>> True发布于 2018-07-24 01:59:39
tf.contrib.layers.dense_to_sparse执行密集张量到稀疏张量的转换。通过在数组末尾出现零来检测终止。请访问https://www.tensorflow.org/api_docs/python/tf/contrib/layers/dense_to_sparse了解更多详细信息。
https://stackoverflow.com/questions/42127505
复制相似问题