gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:07:21 27 4
gpt4 key购买 nike

这里的数据有些奇怪。

如果我创建一个 scipy.sparse.csr_matrix ,其 data 属性仅包含 0 和 1,然后要求它打印 data 属性,有时会出现 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]

为什么稀疏矩阵中存储的数据不能反射(reflect)原来存放在那里的数据(原始数据中没有2)?

最佳答案

我假设,你的矩阵创建方式:

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

将在后台使用coo_matrix( 尚未找到相关来源 ;见底部)。

在这种情况下,docs (对于首席运营官)说:

By default when converting to CSR or CSC format, duplicate (i,j) entries will be summed together. This facilitates efficient construction of finite element matrices and the like. (see example)

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

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com