4
我想将未压缩的稀疏数组转换为tf.SparseTensor接受的格式。有一个内置函数tf.sparse_to_dense,正好与我正在做的相反。所以我的问题是Tensorflow或Python中有什么内置功能来做这种转换?Tensorflow dense_to_sparse
我想将未压缩的稀疏数组转换为tf.SparseTensor接受的格式。有一个内置函数tf.sparse_to_dense,正好与我正在做的相反。所以我的问题是Tensorflow或Python中有什么内置功能来做这种转换?Tensorflow dense_to_sparse
你可以用这个做到这一点:
您可以使用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
是否有可能将TF图中的变量从稠密替换为稀疏,以便图表起作用? – pcejrowski
按我所知,没有任何这样。但是你可以实现一个。作为参考,您可以查看https://github.com/fchollet/keras/blob/master/keras/backend/tensorflow_backend.py#L2982-L3015 – indraforyou
[密集的一个Tensorflow稀疏矩阵](https:// stackoverflow.com/questions/39838234/sparse-matrix-from-a-dense-one-tensorflow) –