【pytorch】RuntimeError: number of dimensions must be sparse_dim (14) + dense_dim (0), but got 2*
写代码时遇到如标题所示报错,pytorch=1.7.1,使用torch.sprase_coo_tensor创建稀疏矩阵
indices = [[1, 2], [2, 3], [2, 4], [4, 5]]
value = [1, 1, 1, 1]
sparseSubG = torch.sparse_coo_tensor(indices, value, (10, 10))
出现如下报错:
RuntimeError: number of dimensions must be sparse_dim (4) + dense_dim (0), but got 2
解决方法:
查看pytorch文档找到sparse部分,故对indices进行一个转置即可
https://pytorch.org/docs/stable/sparse.html
假设我们要定义一个稀疏张量,其中条目 3 在位置 (0, 2),条目 4 在位置 (1, 0),条目 5 在位置 (1, 2)。假定未指定的元素具有相同的值,填充值,默认情况下为零。然后我们会写:
>>> i = [[0, 1, 1],
[2, 0, 2]]
>>> v = [3, 4, 5]
>>> s = torch.sparse_coo_tensor(i, v, (2, 3))
>>> s
tensor(indices=tensor([[0, 1, 1],
[2, 0, 2]]),
values=tensor([3, 4, 5]),
size=(2, 3), nnz=3, layout=torch.sparse_coo)
>>> s.to_dense()
tensor([[0, 0, 3],
[4, 0, 5]])
请注意,输入i不是索引元组列表。如果你想这样写你的索引,你应该在将它们传递给稀疏构造函数之前进行转置:
>>> i = [[0, 2], [1, 0], [1, 2]]
>>> v = [3, 4, 5 ]
>>> s = torch.sparse_coo_tensor(list(zip(*i)), v, (2, 3))
>>> # Or another equivalent formulation to get s
>>> s = torch.sparse_coo_tensor(torch.tensor(i).t(), v, (2, 3))
>>> torch.sparse_coo_tensor(i.t(), v, torch.Size([2,3])).to_dense()
tensor([[0, 0, 3],
[4, 0, 5]])