Created
October 23, 2017 18:25
-
-
Save elibixby/475de49822ce493385fdaa3c5a8c8229 to your computer and use it in GitHub Desktop.
Convert arbitrary rank dense tensor to sparse tensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dense_to_sparse(t): | |
num_elements = tf.reduce_prod(tf.shape(t)) | |
def _index_dim(dim): | |
return tf.reshape( | |
tf.tile( | |
tf.expand_dims(tf.range(0, dim), -1), | |
multiples=[1, num_elements/dim] | |
), | |
[-1] | |
) | |
index_dims = tf.map_fn(_index_dim, tf.shape(t)) | |
return tf.SparseTensor( | |
indices=tf.transpose(index_dims), | |
values=tf.reshape(t, [-1]) | |
dense_shape=tf.shape(t) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment