Tensorflow dense_to_sparse

DVK*_*DVK 11 python tensorflow

我试图将未压缩的稀疏数组转换为tf.SparseTensor接受的格式.有一个内置函数tf.sparse_to_dense,它正好与我试图做的完全相反.所以我的问题是Tensorflow或Python中有任何内置函数来进行这种转换吗?

Tim*_*ker 10

根据这个问题:

你可以这样做:

你可以使用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
Run Code Online (Sandbox Code Playgroud)