pythonnumpyscipysparse-matrixpytorch

Converting a scipy coo_matrix to pytorch sparse tensor


I have a coo_matrix:

from scipy.sparse import coo_matrix
coo = coo_matrix((3, 4), dtype = "int8")

That I want converted to a pytorch sparse tensor. According to the documentation https://pytorch.org/docs/master/sparse.html it should follow the coo format, but I cannot find a simple way to do the conversion. Any help would be greatly appreciated!


Solution

  • Using the data as in the Pytorch docs, it can be done simply using the attributes of the Numpy coo_matrix:

    import torch
    import numpy as np
    from scipy.sparse import coo_matrix
    
    coo = coo_matrix(([3,4,5], ([0,1,1], [2,0,2])), shape=(2,3))
    
    values = coo.data
    indices = np.vstack((coo.row, coo.col))
    
    i = torch.LongTensor(indices)
    v = torch.FloatTensor(values)
    shape = coo.shape
    
    torch.sparse.FloatTensor(i, v, torch.Size(shape)).to_dense()
    

    Output

    0 0 3
    4 0 5
    [torch.FloatTensor of size 2x3]