文章目录
- dok_array
- 初始化方案
- 内置方法
dok_array
dok
数组就是通过键值对存储的数组,其中key
就是矩阵中的坐标元组,value
就是对应坐标中的值,是最容易理解的稀疏矩阵存储方案。
>>> import numpy as np
>>> from scipy.sparse import dok_array
>>> dok = dok_array((5, 5), dtype=np.float32)
>>> for i in range(5):
... for j in range(5):
... dok[i, j] = i + j # Update element
...
>>> print(dok.toarray())
[[0. 1. 2. 3. 4.][1. 2. 3. 4. 5.][2. 3. 4. 5. 6.][3. 4. 5. 6. 7.][4. 5. 6. 7. 8.]]
得到结果为
[0.1.2.3.4.1.2.3.4.5.2.3.4.5.6.3.4.5.6.7.4.5.6.7.8.]\begin{bmatrix} 0.&1.&2.&3.&4.\\1.&2.&3.&4.&5.\\ 2.&3.&4.&5.&6.\\3.&4.&5.&6.&7.\\ 4.&5.&6.&7.&8.\\\end{bmatrix} 0.1.2.3.4.1.2.3.4.5.2.3.4.5.6.3.4.5.6.7.4.5.6.7.8.
从上面的代码来看,其等价形式如下,唯一的区别是,对于一个全0的矩阵,array
必须将所有0都存储下来,而dok
数组可以不存储任何有效值。但对于全都不是0的矩阵,dok
除了存储矩阵的值之外,还要将矩阵的坐标重新写一边,相当于数据量翻了三倍。
>>> Z = np.zeros([5,5])
>>> for i in range(5):
... for j in range(5):
... Z[i, j] = i + j # Update element
...
>>> print(Z)
[[0. 1. 2. 3. 4.][1. 2. 3. 4. 5.][2. 3. 4. 5. 6.][3. 4. 5. 6. 7.][4. 5. 6. 7. 8.]]
初始化方案
dok
仅支持三种初始化方案:
dok_array(D)
D是一个稀疏数组或2×D2\times D2×D数组dok_array(S)
S是另一种稀疏数组。dok_array((M, N),dtype='d')
创建一个shape为(M,N)(M, N)(M,N)的空数组,dtype为数据类型
内置方法
稀疏数组在计算上并不便捷,所以dok_array
中内置了下列函数,可以高效地完成计算。
函数 | expm1 , log1p , sqrt , pow , sign |
三角函数 | sin , tan , arcsin , arctan , deg2rad , rad2deg |
双曲函数 | sinh , tanh , arcsinh , arctanh |
索引 | getcol , getrow , nonzero , argmax , argmin , max , min |
舍入 | ceil , floor , trunc |
变换 | conj , conjugate , getH |
统计 | count_nonzero , getnnz , mean , sum |
矩阵 | diagonal , trace |
获取属性 | get_shape , getformat |
计算比较 | multiply , dot , maximum , minimum |
转换 | asformat , asfptype , astype , toarray , todense |
转换 | tobsr , tocoo , tocsc , tocsr , todia , todok , tolil |
更改维度 | set_shape , reshape , resize , transpose |
排序 | sort_indices , sorted_indices |
移除元素 | eliminate_zeros , prune , sum_duplicates |
其他 | copy , check_format , getmaxprint , rint , setdiag |