scipy.sparse.csr_matrix数据的意外行为

时间:2018-02-22 15:54:56

标签: python scipy

这里的数据很奇怪。

如果我创建一个scipy.sparse.csr_matrixdata属性只包含0和1,然后要求它打印数据属性,有时输出中有2个(其他时候没有)。

您可以在此处看到此行为:

from scipy.sparse import csr_matrix
import numpy as np
from collections import OrderedDict

#Generate some fake data
#This makes an OrderedDict of 10 scipy.sparse.csr_matrix objects, 
#with 3 rows and 3 columns and binary (0/1) values

od = OrderedDict()
for i in range(10):
        row = np.random.randint(3, size=3)
        col = np.random.randint(3, size=3)
        data = np.random.randint(2, size=3)
        print 'data is: ', data
        sp_matrix = csr_matrix((data, (row, col)), shape=(3, 3))
        od[i] = sp_matrix

#Print the data in each scipy sparse matrix
for i in range(10):
        print 'data stored in sparse matrix: ',  od[i].data

它打印出这样的东西:

data is:  [1 0 1]
data is:  [0 0 1]
data is:  [0 0 0]
data is:  [0 0 0]
data is:  [1 1 1]
data is:  [0 0 0]
data is:  [1 1 0]
data is:  [1 0 1]
data is:  [0 0 0]
data is:  [0 0 1]
data stored in sparse matrix:  [1 1 0]
data stored in sparse matrix:  [0 0 1]
data stored in sparse matrix:  [0 0]
data stored in sparse matrix:  [0 0 0]
data stored in sparse matrix:  [2 1]
data stored in sparse matrix:  [0 0 0]
data stored in sparse matrix:  [1 1 0]
data stored in sparse matrix:  [1 1 0]
data stored in sparse matrix:  [0 0 0]
data stored in sparse matrix:  [1 0 0]

为什么存储在稀疏矩阵中的数据不会反映最初放在那里的数据(原始数据中没有2)?

1 个答案:

答案 0 :(得分:2)

我假设,您的矩阵创建类型:

sp_matrix = csr_matrix((data, (row, col)), shape=(3, 3))

将在引擎盖下使用coo_matrix尚未找到相关来源;见底部。)

在这种情况下,docs说(对于COO):

  

默认情况下,转换为CSR或CSC格式时,重复(i,j)条目将汇总在一起。这有利于有限元矩阵等的有效构造。 (见例)

您的随机矩阵例程不会检查重复的条目。

编辑:好的。它认为我找到了代码。

csr_matrix:没有构造函数代码 - >继承自_cs_matrix

compressed.py: _cs_matrix

there

      else:
            if len(arg1) == 2:
                # (data, ij) format
                from .coo import coo_matrix
                other = self.__class__(coo_matrix(arg1, shape=shape))
                self._set_self(other)