torch.sparse_coo_tensor()函数-创建稀疏张量

案例:

import torch

t = torch.tensor(data=[2, 2], dtype=torch.float32, device=torch.device('cpu'))
print(t)

# 创建稀疏张量
# 指定坐标
i = torch.tensor([[0,1,2], [0,1,2]])

# 指定坐标上的值
v = torch.tensor([1,2,3])

a = torch.sparse_coo_tensor(indices=i, values=v, size=[4, 4])
print(a)

# 稀疏转为稠密
a = torch.sparse_coo_tensor(indices=i, values=v, size=[4, 4], dtype=torch.float32).to_dense()
print(a)


"""
tensor([2., 2.])

tensor(indices=tensor([[0, 1, 2],
                       [0, 1, 2]]),
       values=tensor([1, 2, 3]),
       size=(4, 4), nnz=3, layout=torch.sparse_coo)

tensor([[1., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 3., 0.],
        [0., 0., 0., 0.]])



"""

你可能感兴趣的:(Pytorch系列,python,pytorch)