gpt4 book ai didi

python - 检查对称稀疏矩阵时出错

转载 作者:行者123 更新时间:2023-12-05 09:17:16 25 4
gpt4 key购买 nike

 if  not (sp.csc_matrix.transpose(a) == a).all():        
a_transpose=sp.csc_matrix.transpose(a)
a=np.add(a,a_transpose)

我一直在检查稀疏矩阵是否对称,但我收到以下错误 -属性错误:全部未找到

最佳答案

对于该主题的一些随机探索:

In [77]: from scipy import sparse

制作一个稀疏矩阵

In [78]: M = sparse.random(100,100,.2, 'csr')
In [79]: M
Out[79]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
with 2000 stored elements in Compressed Sparse Row format>

它不喜欢相等性测试 - 它喜欢但给出警告,原来的 2000 个非零值增加了 3 倍

In [80]: M==M.T
/usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:226: SparseEfficiencyWarning: Comparing sparse matrices using == is inefficient, try using != instead.
" != instead.", SparseEfficiencyWarning)
Out[80]:
<100x100 sparse matrix of type '<class 'numpy.bool_'>'
with 6436 stored elements in Compressed Sparse Row format>

差异仍然增加了非零项的数量,但没有那么多

In [81]: (M-M.T)
Out[81]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
with 3564 stored elements in Compressed Sparse Row format>

Python abs 有效,因为它委托(delegate)给稀疏方法:M.__abs__

In [85]: abs(M-M.T)
Out[85]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
with 3564 stored elements in Compressed Sparse Row format>

另一个警告,如果我们问有多少是小的 - 0 的差异都是 0:

In [86]: abs(M-M.T)<1e-10
/usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:274: SparseEfficiencyWarning: Comparing a sparse matrix with a scalar greater than zero using < is inefficient, try using >= instead.
warn(bad_scalar_msg, SparseEfficiencyWarning)
Out[86]:
<100x100 sparse matrix of type '<class 'numpy.bool_'>'
with 6436 stored elements in Compressed Sparse Row format>

创建一个对称矩阵:

In [87]: Ms = (M+M.T)/2

现在所有项都变小了

In [88]: abs(Ms-Ms.T)<1e-10
/usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:274: SparseEfficiencyWarning: Comparing a sparse matrix with a scalar greater than zero using < is inefficient, try using >= instead.
warn(bad_scalar_msg, SparseEfficiencyWarning)
Out[88]:
<100x100 sparse matrix of type '<class 'numpy.bool_'>'
with 10000 stored elements in Compressed Sparse Row format>

相反,让我们检查有多少差异过大:

In [89]: abs(Ms-Ms.T)>1e-10
Out[89]:
<100x100 sparse matrix of type '<class 'numpy.bool_'>'
with 0 stored elements in Compressed Sparse Row format>
In [90]: abs(M-M.T)>1e-10
Out[90]:
<100x100 sparse matrix of type '<class 'numpy.bool_'>'
with 3564 stored elements in Compressed Sparse Row format>

所以矩阵是对称的,如果:

In [94]: (abs(Ms-Ms.T)>1e-10).nnz == 0
Out[94]: True

关于python - 检查对称稀疏矩阵时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com