Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 786
NicolaiF Avatar asked Jun 03 '18 09:06

NicolaiF


1 Answers

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]
like image 140
twolffpiggott Avatar answered Sep 30 '22 08:09

twolffpiggott