Something goes horribly wrong when I try to create variables

I am trying to convert a scipy coo format sparse matrix to a sparse tensor, but something goes wrong when I assign my values and indices to torch variables, what is going on?

I noticed it when I tried creating my sparse matrix as following:

i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
shape = Ycoo.shape

tY = torch.sparse.FloatTensor(i, v, torch.Size(shape))

and it turned out empty…

apparently it only works if I EXPLICITLY cast the data type for the float tensor to in32, and the datatype for the long tensor to int16, and int16 is to small for my purpose, it makes the value go into overflow. what is going on?

The correct way to get a torch tensor from numpy array is using torch.from_numpy().
Trying to build a tensor directly can have unexpected effect in some cases.

What is the correct way of constructing a pytorch sparse matrix from a numpy coo matrix?
Right now I am doing it as so:

i = np.vstack((Ytest.row, Ytest.col))
v = np.ones(len(i[0]))

i = torch.from_numpy(i.astype(“int64”))
v = torch.from_numpy(v.astype(“float32”))

tSparse = torch.sparse.FloatTensor(i, v)

This looks correct to me. But I’m not a specialist of the sparse api :slight_smile:

1 Like