Skip to content

Instantly share code, notes, and snippets.

@elibixby
Created October 23, 2017 18:25
Show Gist options
  • Save elibixby/475de49822ce493385fdaa3c5a8c8229 to your computer and use it in GitHub Desktop.
Save elibixby/475de49822ce493385fdaa3c5a8c8229 to your computer and use it in GitHub Desktop.
Convert arbitrary rank dense tensor to sparse tensor
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