pytorch 中稀疏矩阵和 dense 矩阵互转

import torch

index = torch.Tensor([[0, 1, 2], [1, 2, 3]])  # index:shape为[2,n],代表着行下标向量和列下标向量
value = torch.ones((index.shape[1]))  # value:shape为[n],代表着非零元素的值
N = 4  # 节点总数

adj = torch.sparse_coo_tensor(index, value, (N, N))

print(adj)
print(adj.to_dense(), adj.to_dense().shape)

【pytorch】稀疏矩阵 sparse_coo_tensor_稀疏矩阵

value 还可以是高维的

import torch

index = torch.Tensor([[0, 1, 2], [1, 2, 3]])  # index:shape为[2,n],代表着行下标向量和列下标向量
value = torch.randn((3, 5))  
N = 4  # 节点总数

adj = torch.sparse_coo_tensor(index, value, (N, N, 5))  # size 也要对应改变

print(adj)
print(adj.to_dense(), adj.to_dense().shape)

【pytorch】稀疏矩阵 sparse_coo_tensor_pytorch_02