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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With