text
stringlengths
1
93.6k
def sparse_mx_to_sparse_tensor(sparse_mx):
"""sparse matrix to sparse tensor matrix(torch)
Args:
sparse_mx : scipy.sparse.csr_matrix
sparse matrix
"""
sparse_mx_coo = sparse_mx.tocoo().astype(np.float32)
sparse_row = torch.LongTensor(sparse_mx_coo.row).unsqueeze(1)
sparse_col = torch.LongTensor(sparse_mx_coo.col).unsqueeze(1)
sparse_indices = torch.cat((sparse_row, sparse_col), 1)
sparse_data = torch.FloatTensor(sparse_mx.data)
return torch.sparse.FloatTensor(sparse_indices.t(), sparse_data, torch.Size(sparse_mx.shape))
def to_tensor(adj, features, labels=None, device='cpu'):
"""Convert adj, features, labels from array or sparse matrix to
torch Tensor on target device.
Args:
adj : scipy.sparse.csr_matrix
the adjacency matrix.
features : scipy.sparse.csr_matrix
node features
labels : numpy.array
node labels
device : str
'cpu' or 'cuda'
"""
if sp.issparse(adj):
adj = sparse_mx_to_sparse_tensor(adj)
else:
adj = torch.FloatTensor(adj)
if sp.issparse(features):
features = sparse_mx_to_sparse_tensor(features)
else:
features = torch.FloatTensor(np.array(features))
if labels is None:
return adj.to(device), features.to(device)
else:
labels = torch.LongTensor(labels)
return adj.to(device), features.to(device), labels.to(device)
def idx_to_mask(idx, nodes_num):
"""Convert a indices array to a tensor mask matrix
Args:
idx : numpy.array
indices of nodes set
nodes_num: int
number of nodes
"""
mask = torch.zeros(nodes_num)
mask[idx] = 1
return mask.bool()
def is_sparse_tensor(tensor):
"""Check if a tensor is sparse tensor.
Args:
tensor : torch.Tensor
given tensor
Returns:
bool
whether a tensor is sparse tensor
"""
# if hasattr(tensor, 'nnz'):
if tensor.layout == torch.sparse_coo:
return True
else:
return False
def to_scipy(tensor):
"""Convert a dense/sparse tensor to scipy matrix"""
if is_sparse_tensor(tensor):
values = tensor._values()
indices = tensor._indices()
return sp.csr_matrix((values.cpu().numpy(), indices.cpu().numpy()), shape=tensor.shape)
else:
indices = tensor.nonzero().t()
values = tensor[indices[0], indices[1]]
return sp.csr_matrix((values.cpu().numpy(), indices.cpu().numpy()), shape=tensor.shape)
# <FILESEP>
# VERSION: 1.1
# AUTHORS: BurningMop (burning.mop@yandex.com)
# LICENSING INFORMATION
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR