【问题标题】:Unexpected behaviour from scipy.sparse.csr_matrix data来自 scipy.sparse.csr_matrix 数据的意外行为
【发布时间】:2018-02-23 00:10:48
【问题描述】:

这里的数据有些奇怪。

如果我创建一个 data 属性只包含 0 和 1 的 scipy.sparse.csr_matrix,然后要求它打印数据属性,有时输出中有 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)?

【问题讨论】:

    标签: python scipy


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 是的,当我打印 rowcol 时,我得到了一些重复的条目,它们对应于数据中 2 的实例。
    • 感谢您的检查!
    • 谢谢!我快疯了>
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多