我使用scipy.sparse.lil_matrix
创建了一个稀疏矩阵:
import scipy.sparse as sp
test = sp.lil_matrix((3,3))
test[0,0]=1
我可以通过执行以下操作循环并打印非零元素:
for el in test:
print(el)
打印出(0, 0) 1.0
。如何在不打印的情况下访问这两条信息?换句话说,返回索引和值的lil_matrix
元素的适当方法是什么?执行el.data
返回array([list([])], dtype=object)
注意,我使用的是lil_matrix
,因为我需要在一个非常大的双for循环中为它分配非零值
您寻找的显示非常类似于
str
稀疏矩阵的coo
显示稀疏矩阵有一种
nonzero
方法来显示非零元素的坐标对于
coo
,值存储为3个数组:这些元素在
coo
格式中的顺序没有限制。甚至可能存在重复项,尽管这些项在转换为显示或csr
格式时被求和当我们将其转换为
lil
格式时,数据现在存储在两个列表数组中,每行一个列表:它也有
nonzero
,但看看代码(它使用coo
格式):实际上,这是所有稀疏格式的通用
nonzero
。nz_mask
部分允许矩阵可能有0个尚未清理的值虽然
lil
是为方便逐元素更新而设计的,但如果可能,我们通常建议从输入数组的coo
样式创建一个矩阵。通常可以更有效地创建这些阵列。即使是列表附加或扩展也可以更快进一步查看
Ml
矩阵上的迭代-它为每一行创建一个lil
:我们可以显示每行的数据:
或者过滤掉空行:
我们需要另一次迭代来分离每行中的元素
关于稀疏数组与密集数组的使用,一条经验法则是稀疏度(%非零元素)应该小于10%,这样才值得使用稀疏格式。但这在很大程度上取决于你的使用和关注
从简单的数据存储角度来看,请注意
coo
格式必须为每个非零项使用3个数字,而密集数组仅使用1个数字。稀疏矩阵乘法对于csr
格式比较好。其他只关注data
值(例如sin
)的计算也相对有效。但是,如果数学必须比较两个矩阵的稀疏性,例如加法和元素乘法,稀疏性会更差索引、切片和求和实际上可能使用矩阵乘法
coo
格式没有实现这些功能lil
可以很好地执行一些面向行的操作。创建稀疏矩阵的基本动作需要时间都在
.data
和.rows
对于此包含25个元素的10x5阵列:
.data
数组的每个元素都是一个列表,其中包含该行的值.rows
数组的每个元素都是.data
中每个非零值的列索引列表这几乎肯定不是一个好主意。
lil_matrix
的开销意味着,如果它的稀疏度不小于5%,那么填充密集数组几乎肯定会更好。即使这样,也很不确定。这是一种非常糟糕的数据存储格式编辑:
编辑2:
我不知道你的实际功能或目标是什么,但如果你知道你有多少非零项,你可以预先分配你需要的数组,跳过整个lil的事情
相关问题 更多 >
编程相关推荐