【pytorch】RuntimeError: number of dimensions must be sparse_dim (14) + dense_dim (0), but got 2

【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]])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值