Skip to content
Advertisement

How to convert a PyTorch sparse_coo_tensor into a PyTorch dense tensor?

I create a sparse_coo tensor in PyTorch:

import torch

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

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

Now I want to convert a PyTorch sparse tensor into a PyTorch dense tensor. Which function can be used?

Advertisement

Answer

you can use to_dense as suggested in this example :

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

And by the way, the documentation is here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement