Soubriquet
Soubriquet

Reputation: 3350

PyTorch Sparse Tensors number of dimensions must be nDimI + nDimV

I'm trying to insert the value in gd to coordinate [1,0]. Below are the matrices. When I try this, I get a RuntimeError.

>>> import torch
>>> cd = [[1, 0]]
>>> gd = [0.39613232016563416]
>>> i = torch.LongTensor(cd)
>>> v = torch.FloatTensor(gd)
>>> p = torch.rand(2)
>>> i

 1  0
[torch.LongTensor of size 1x2]

>>> v

 0.3961
[torch.FloatTensor of size 1]

>>> p

 0.4678
 0.0996
[torch.FloatTensor of size 2]

>>> torch.sparse.FloatTensor(i.t(), v, torch.Size(list(p.size()))).to_dense()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: invalid argument 2: number of dimensions must be nDimI + nDimV at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/THS/generic/THSTensor.c:169

Upvotes: 1

Views: 2013

Answers (1)

patapouf_ai
patapouf_ai

Reputation: 18743

Two things.

1) Right now p is a Tensor of rank 1. To insert something in position [1,0] it needs to be a Tensor of rank 2.

2) You don't need to do complicated things with sparse tensors. Simply p[cd[0], cd[1]] = v[0] should work. Where cd = torch.LongTensor([row_idx, col_idx])

So:

>>> cd = torch.LongTensor([1,0])
>>> gd = [0.39613232016563416]
>>> v = torch.FloatTensor(gd)
>>> p = torch.rand((2,2))
>>> p
 0.9342  0.8539
 0.7044  0.0823

[torch.FloatTensor of size 2x2]

>>> p[cd[0], cd[1]] = v[0]
>>> p
0.9342  0.8539
0.3961  0.0823

[torch.FloatTensor of size 2x2]

That simple.

Upvotes: 1

Related Questions