tmp_coo
=
sp
.
coo_matrix
(
a_matrix
)
values
=
tmp_coo
.
data
indices
=
np
.
vstack
(
(
tmp_coo
.
row
,
tmp_coo
.
col
)
)
i
=
torch
.
LongTensor
(
indices
)
v
=
torch
.
LongTensor
(
values
)
edge_idx
=
torch
.
sparse_coo_tensor
(
i
,
v
,
tmp_coo
.
shape
)
另:邻接矩阵和edgelist格式转换,可通过networkx来做
import networkx as nx
g=nx.from_numpy_matrix(matrix)
edge_list=nx.to_edgelist(g)
没办法直接转换,需要借助numpy转换。import numpy as npimport scipy.sparse as sp# a_matrix 是一个邻接矩阵tmp_coo=sp.coo_matrix(a_matrix)values=tmp_coo.dataindices=np.vstack((tmp_coo.row,tmp_coo.col))i=torch.LongTensor(indices)v=torch.LongTensor(values)edge_idx=torch.spar
rom torch_sparse import SparseTensor
adj = SparseTensor(row=edge_index[0], col=edge_index[1], value=...,
sparse_sizes=(num_nodes, num_nodes))
# value is optional and can b
r_arr [[ 0.65603592 0.39908438 0.44722351 0.92652759]
[ 0.32357477 0.45384697 0.31687359 0.73861219]
[ 0.3534119 0.12693696 0.1570176
col=np.array([1,3,0,2])
data=np.ones(4)
sparse_matrix=sparse.coo_matrix((data,(row,col)),shape=(4,4)).toarray()
其中包含四个参数:
(1)da
当对离散数据进行拟合预测时,往往要对特征进行onehot处理,但onehot是高度稀疏的向量,如果使用List或其他常规的存储方式,对内存占用极大。
这时稀疏矩阵类型 coo_matrix / csr_matrix 就派上用场了!
这两种稀疏矩阵类型csr_matrix存储密度更大,但不易手工构建。coo_matrix存储密度相对小,但易于手工构建,常用方法为先手工构建coo_matrix,...
一、scipy.sparse.coo_matrix是关于稀疏矩阵的类
classscipy.sparse.coo_matrix(arg1,shape=None,dtype=None,copy=False)[source]
A sparse matrix in COOrdinate format.
Also known as the ‘ijv’ or ‘triplet’ format.
This can be instantiated in several ways:
coo_matrix(D...
values =X_train.data
indices = np.vstack((X_train.row, X_train.col))
i =
torch.Long
Tensor(indices)
v =
torch.Float
Tensor(values)
shape = X_train.shape
X_train=
torch.
sparse.Float
Tensor(i, v,
torch.Size(shape))
转换为scipy.
sparse:.to
coo()即可
在使用PyG框架的时候,PyG要求输入的是 edge_index 格式,而不是我们所使用的邻接矩阵格式,即N x N。
import scipy.sparse as sp
import numpy as np
import torch
# adj_matrix 是邻接矩阵
tmp_coo = sp.coo_matrix(adj_matrix)
values = tmp_coo.data
indices = np.vstack((tmp_coo.row,tmp_coo.col))
i = torch.Lon
import scipy.
sparse as sp
import
torch
a = np.array([[1,0,0,1,0],[0,1,1,0,0],[0,0,0,0,1],[1,0,0,0,1],[0,0,1,0,0]])
a = sp.
coo_
matrix(a,shape=(5,5))
sparse_mx = a.to
coo().astype(np.f...