pytorch batch sparse tensor (构建稀疏batch)
作者:互联网
直接通过scipy sparse矩阵转化, 这个方法的缺点是不能构建 batch 的sparse tensor
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
# sparse_mx = sp.coo_matrix(sparse_mx)
sparse_mx1 = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vstack((sparse_mx1.row, sparse_mx1.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx1.data)
shape = torch.Size(sparse_mx1.shape)
return torch.sparse.FloatTensor(indices, values, shape)
直接先建好densor tensor, 再用 to_sparse() 转化就可以得到batch 的sparse
a = torch.randn(10, 2, 3).to_sparse().requires_grad_(True)
b = torch.randn(10, 3, 2)
torch.bmm(a,b)
这个在GNN 中构 建一个batch的邻接矩阵(batch adjcancy matrix)会有用,
https://github.com/pytorch/pytorch/issues/14489
标签:tensor,torch,batch,mx1,pytorch,sparse,mx 来源: https://blog.csdn.net/weixin_40248634/article/details/121061213