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]]