邻接矩阵转稀疏矩阵

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)

 

torch 矩阵转numpy 矩阵

A = torch.load('adj1.pt')
A = A.numpy()

numpy 矩阵转 scipy 稀疏矩阵

A = sp.coo_matrix(A)

scipy 稀疏矩阵转numpy 矩阵

A.toarray()

将 Scipy Sparse 矩阵转换成 torch sparse 矩阵

def sparse_mx_to_torch_sparse_tensor(sparse_mx):
    """Convert a scipy sparse matrix to a torch sparse tensor."""
    sparse_mx = sparse_mx.tocoo().astype(np.float32)
    indices = torch.from_numpy(
        np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
    values = torch.from_numpy(sparse_mx.data)
    shape = torch.Size(sparse_mx.shape)
    return torch.sparse.FloatTensor(indices, values, shape)

torch sparse矩阵转 torch 稠密矩阵

sparse_adj.to_dense()

 

posted @ 2022-03-15 16:11  图神经网络  阅读(387)  评论(0编辑  收藏  举报
Live2D