Skip to main content
 首页 » 编程设计

python之Scipy 的 sign() 不能保证有效吗

2025年04月02日13birdshome

我有一个图 A 的邻接矩阵。在 A = A.sign() 之后还有一些元素不是 1 或 0 或 -1。

In [35]: A = A.sign() 
 
In [36]: A.getcol(0).data 
Out[36]:  
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1., 
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,     
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1., 
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1., 
        1.,  1.,  1.,  1.,  2.]) 
 
In [37]: A 
Out[37]:  
<519403x519403 sparse matrix of type '<type 'numpy.float64'>' 
    with 3819116 stored elements in COOrdinate format> 

另一方面,numpy.sign() 工作正常。

In [50]: a = A.getcol(0) 
 
In [51]: np.sum(a.todense()) 
Out[51]: 58.0 
 
In [52]: np.sum(np.sign(a.todense())) 
Out[52]: 57.0 

请您参考如下方法:

经过一些研究,我得到了答案。都是内部数据结构Scipy用途。

import numpy as np 
from scipy.sparse import coo_matrix 
 
xs = np.array([1, 2, 3, 3, 2]) 
ys = np.array([2, 3, 1, 1, 1]) 
A = coo_matrix((np.ones((5,)), (xs, ys))) 

此时A是 <4x4 sparse matrix of type '<type numpy.float64'>' with 5 stored elements in COOrdinate format> , 尽管我们在同一坐标中有两个元素 (3, 1) .和 A = A.sign()只对 5 个元素执行,这 5 个元素首先都是 1。

>>> A.data 
array([ 1.,  1.,  1.,  1.,  1.]) 
 
>>> A.todense() 
matrix([[ 0.,  0.,  0.,  0.], 
        [ 0.,  0.,  1.,  0.], 
        [ 0.,  1.,  0.,  1.], 
        [ 0.,  2.,  0.,  0.]]) 
 
>>> A = A.sign() 
>>> A.todense() 
matrix([[ 0.,  0.,  0.,  0.], 
        [ 0.,  0.,  1.,  0.], 
        [ 0.,  1.,  0.,  1.], 
        [ 0.,  2.,  0.,  0.]])