最难理解的是最终一种初始化方式:
dia_matrix((data,offsets),shape = (M,N))
where the data[k,:] stores the diagonal entries for diagonal offsets[k].
这句话很难看懂:
from scipy.sparse import dia_matrix
import numpy as np
if __name__ == '__main__':
data = np.array([[1,2,3,4],
[4,2,3,8],
[7,2,4,5]])
offsets = np.array([0,-1,2])
a = dia_matrix((data,offsets),shape=(4,4)).toarray()
print(a)
[[1 0 4 0]
[4 2 0 5]
[0 2 3 0]
[0 0 3 4]]
offset for each diagonal
首先按照对角线将所有的元素排列好:
(1) d i a g o n a l o f f s e t ∣ r o w 2 : 7 1 : 2 0 : 1 4 − 1 : 4 2 5 − 2 : 2 3 3 4 8 \begin{matrix} diagonal\ offset| &row&&&\\ 2:&7&&&\\ 1:&&2&&\\ 0:&1&&4&\\ -1:&4&2&&5\\ -2:&&2&3&\\ &&&3&4\\ &&&&8\\ &&&&\\ &&&&\\ &&&&\\ \end{matrix} \tag{1} diagonal offset∣2:1:0:−1:−2:row714222433548(1)
按照上面的概念形象化展示如下
Then
因为最终的形状是:4x4.
所以以主对角线即:1 2 3 4这一斜着的数据为参考,得到一个矩阵。
1 0 4 0
4 2 0 5
0 2 3 0
参考连接:
https://www.scipy-lectures.org/advanced/scipy_sparse/dia_matrix.html