pytorch中的稀疏矩阵 2021-09-07

pytorch的系数矩阵结构包括:

  • torch_sparse.tensor.SparseTensor: 该结构非pytorch官方给出的数据结构,在torch_geometric等包中使用。可以通过.to_torch_sparse_coo_tensor()转换为下面的COO tensor(coordinate)结构。
  • torch.sparse包中存在的几种数据结构,详情见 https://pytorch.org/docs/stable/sparse.html 。包括torch.sparse_coo_tensor等。

torch.sparse中COO tensor相关运算:

  • 提取indices、修改values:先进行.coalesce(),再调用.indices().values(),获取结果后修改。将计算结果直接通过torch.sparse_coo_tensor(得到的.indices(), new_values)创建一个新的COO tensor。
  • 加法:构造一个新的coo tensor,直接用+即可。
  • 获取度数:用torch.sparse.sum(你的sparse_tensor, dim=0).values()
  • 矩阵乘法:目前(2021.09.07)只能算稀疏矩阵和稠密矩阵的乘法,不能算稀疏矩阵之间的乘法!需要特别注意!调用的函数是.matmul(稠密矩阵)
  • 计算对称形式拉普拉斯:
    sparse_tensor = adj_t.detach().to_torch_sparse_coo_tensor()
    length = len(x)
    sparse_tensor += torch.sparse_coo_tensor((range(length), range(length)),
                                            [1.] * length)
    degrees = torch.sparse.sum(sparse_tensor, dim=0).values()
    deg_inv_sqrt = degrees.pow(-0.5)
    s2 = sparse_tensor.coalesce()
    new_values = s2.values() * deg_inv_sqrt[s2.indices()[0]] * deg_inv_sqrt[s2.indices()[1]]
    result = torch.sparse_coo_tensor(s2.indices(), new_values)
    

你可能感兴趣的:(pytorch,python,DeepLearning,pytorch,矩阵,数学,python)