这里的数据有些奇怪。

如果我创建的scipy.sparse.csr_matrix具有仅包含0和1的data属性,然后要求它打印data属性,则有时输出中有2s(有时不是)。

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

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]


为什么存储在稀疏矩阵中的数据不能反映原始存储在其中的数据(原始数据中没有2s)?

最佳答案

我假设您是一种矩阵创建:

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)

关于python - 来自scipy.sparse.csr_matrix数据的意外行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48931762/

10-12 22:09
查看更多