官方文档解释如下
最难理解的是最终一种初始化方式:
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.详细解释
首先按照对角线将所有的元素排列好:
按照上面的概念形象化展示如下
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