Skip to content

Instantly share code, notes, and snippets.

@dkapitan
Created January 23, 2022 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkapitan/8e7ae2d3e2facf756a4a2206b2636aa3 to your computer and use it in GitHub Desktop.
Save dkapitan/8e7ae2d3e2facf756a4a2206b2636aa3 to your computer and use it in GitHub Desktop.
Convert SciPy sparse matrix to tf.sparse.SparseTensor
def sparse_matrix_to_tensor(X):
"""Transforms SciPy sparse matrix to tensorflow.sparse.SparseTensor."""
row_nnz = np.diff(X.indptr)
indices = np.asarray([[row_i, col_i]
for row_i, nnz in enumerate(row_nnz)
for col_i in range(nnz)], dtype=np.int64)
values = X.data
return SparseTensor(indices=indices, values=values, dense_shape=X.shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment