Python scipy中的dia_matrix详解

官方文档解释如下

最难理解的是最终一种初始化方式:
dia_matrix((data,offsets),shape = (M,N))
where the data[k,:] stores the diagonal entries for diagonal offsets[k].
这句话很难看懂

个人举例

1. 代码

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)

2.output

[[1 0 4 0]
[4 2 0 5]
[0 2 3 0]
[0 0 3 4]]

解释

1.需要明白的概念

offset for each diagonal

  • 0 is the main diagonal
  • negative offset = below
  • positive offset = above

2.详细解释

首先按照对角线将所有的元素排列好:
(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}

按照上面的概念形象化展示如下
在这里插入图片描述
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

猜你喜欢

转载自blog.csdn.net/ChenglinBen/article/details/84424379
今日推荐