Scipy的标志()不能保证有效吗?

时间:2016-05-14 16:24:53

标签: python numpy scipy sparse-matrix

我有一个图A = A.sign()的邻接矩阵。在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> 之后,仍有一些元素不是1或0或-1。

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 工作正常。

SearchFormContainer

1 个答案:

答案 0 :(得分:1)

经过一番研究后,我得到了答案。这完全取决于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个元素执行,这些元素首先都是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.]])