如何将PyTorch sparse_coo_tensor转换为PyTorch密集张量?

问题描述

我在PyTorch中创建了一个sparse_coo张量:

import torch

# create indices
i = torch.tensor([[0,1,1],[2,2]])
# create values
v = torch.tensor([3,4,5],dtype=torch.float32)

# create sparse_coo_tensor
sparse_tensor = torch.sparse_coo_tensor(i,v,4])

现在,我想将PyTorch稀疏张量转换为PyTorch密集张量。可以使用哪个功能

解决方法

您可以按照this example中的建议使用to_dense

s = torch.sparse_coo_tensor(i,v,[2,4])
s_dense = s.to_dense()

顺便说一下,文档是here