Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow dense_to_sparse [duplicate]

I am trying to convert a uncompressed sparse array into a format accepted by tf.SparseTensor. There is an inbuilt function tf.sparse_to_dense that does exactly the opposite I am trying to do. So my question is there any inbuilt function in Tensorflow or Python to do this conversion?

like image 725
DVK Avatar asked Feb 09 '17 03:02

DVK


2 Answers

according to this question:

you can do it with this:

You can use tf.where and tf.gather_nd to do that:

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
like image 67
Tim Avatar answered Sep 30 '22 17:09

Tim


tf.contrib.layers.dense_to_sparse does dense tensor to sparse conversion. termination is detected by presence of zeros in the end of array. Please visit https://www.tensorflow.org/api_docs/python/tf/contrib/layers/dense_to_sparse for more details.

like image 30
abhi Avatar answered Sep 30 '22 19:09

abhi