Example:
import scipy.sparse as sp
import numpy as np
import torch
adj_matrix = torch.randint(0,2,(4,4))
print(adj_matrix)
tensor([[1, 1, 0, 0],
[0, 1, 0, 1],
[0, 0, 1, 1],
[1, 0, 0, 0]])
# adj_matrix 是邻接矩阵
tmp_coo = sp.coo_matrix(adj_matrix)
values = tmp_coo.data
indices = np.vstack((tmp_coo.row,tmp_coo.col))
i = torch.LongTensor(indices)
v = torch.LongTensor(values)
edge_index=torch.sparse_coo_tensor(i,v,tmp_coo.shape)
print(edge_index)
tensor(indices=tensor([[0, 0, 1, 1, 2, 2, 3],
[0, 1, 1, 3, 2, 3, 0]]),
values=tensor([1, 1, 1, 1, 1, 1, 1]),
size=(4, 4), nnz=7, layout=torch.sparse_coo)