Q:

Followup on question "Use coo_matrix in TensorFlow"

In the answer to the question was mentioned:
tf_coo_matrix = tf.SparseTensorValue(
indices=np.array([coo_matrix.rows, coo_matrix.cols]).T,
values=coo_matrix.data,
dense_shape=coo_matrix.shape)

I'm trying to understand why one needs to transpose a scipy sparse matrix when using TensorFlow. Thanks in  advance.

A:

If you look at the documentation of tf.SparseTensor, indices is expected to be a 2-dimensional tensor with dimensions (N, ndims), where N is the number of non-zero values in the sparse tensor and ndims is its number of dimensions. For a sparse matrix (two dimensions), each row will contain the row and the column of the corresponding value in values.
In the snippet, coo_matrix.rows is an array of row indices of the sparse matrix, and coo_matrix.cols is an array of column indices. np.array([coo_matrix.rows, coo_matrix.cols]) will be an array with two rows and N columns, which is the opposite order of what a sparse tensor expects, so transposing it with .T you get the (N, 2) indices tensor. Not that you are not transposing the sparse matrix, the indices still remain the same, you are just giving them to tf.SparseTensorValue in the required order. You could get the same result by doing, for example, np.stack([coo_matrix.rows, coo_matrix.cols], axis=1).

