torch.sparse

1.如何构造一个稀疏矩阵呢?

indices = torch.LongTensor([[0,0], [1,1], [2,2]])#稀疏矩阵中非零元素的坐标
indices = indices.t() #一定要转置,因为后面sparse.FloatTensor的第一个参数就是该变量,要求是一个含有两个元素的列表,每个元素也是一个列表。第一个子列表是非零元素所在的行,第二个子列表是非零元素所在的列。
print(indices)
values = torch.FloatTensor([3,4,5])
mat = torch.sparse.FloatTensor(indices,values,[4,4])
print(mat)
print(mat.to_dense())

输出如下:

tensor([[0, 1, 2],
        [0, 1, 2]])
tensor(indices=tensor([[0, 1, 2],
                       [0, 1, 2]]),
       values=tensor([3., 4., 5.]),
       size=(4, 4), nnz=3, layout=torch.sparse_coo)
tensor([[3., 0., 0., 0.],
        [0., 4., 0., 0.],
        [0., 0., 5., 0.],
        [0., 0., 0., 0.]])

2.怎么获得这个稀疏矩阵的indices呢?

x = mat.coalesce().indices()
print(x)

至于为啥要coalesce我也不晓得,反正就记住呗。对了,忘了说了,上面有写到,给一个torch tensor转置用函数t()。

输出如下:

tensor([[0, 1, 2],
        [0, 1, 2]])

3.怎么给稀疏矩阵切片呢?

稀疏矩阵切片不能使用coo_matrix(三元组),可以将矩阵转化为csr_matrix,转化方式很简单

import scipy.sparse as sp
row = [0, 0, 0, 1, 1, 1, 2, 2, 2]    # 行指标
col = [0, 1, 2, 0, 1, 2, 0, 1, 2]    # 列指标
data = [1, 0, 1, 0, 1, 1, 1, 1, 0]   # 在行指标列指标下的数字
team = sp.csr_matrix((data, (row, col)), shape=(3, 3))
print(team)
print(team.todense())                #todense()与toarray()的效果一样,都是将矩阵输出.
print(team.toarray())

输出如下:

  (0, 0)    1
  (0, 1)    0
  (0, 2)    1
  (1, 0)    0
  (1, 1)    1
  (1, 2)    1
  (2, 0)    1
  (2, 1)    1
  (2, 2)    0
[[1 0 1]
 [0 1 1]
 [1 1 0]]
[[1 0 1]
 [0 1 1]
 [1 1 0]]

 

posted @ 2020-12-09 16:40  地球上最后一个直男  阅读(2876)  评论(0编辑  收藏  举报