我有一个非常大的稀疏矩阵(100000列和100000行)。我想选择此稀疏矩阵的某些行,然后使用它们形成一个新的稀疏矩阵。我尝试通过首先将它们转换为密集矩阵,然后再次将其转换为稀疏矩阵来做到这一点。但是当我这样做时,python会引发“内存错误”。然后,我尝试了另一种方法,即我选择稀疏矩阵的行,然后将它们放入数组,但是当我尝试将此数组转换为稀疏矩阵时,它说:'ValueError:数组的真值大于一个要素是模棱两可的。使用a.any()或a.all()。” 那么如何将列表稀疏矩阵转换为单个大稀疏矩阵?
# X_train is a sparse matrix of size 100000x100000, it is in sparse form
# y_train is a 1 denmentional array with length 100000
# I try to get a new sparse matrix by using some rows of X_train, the
#selection criteria is sum of the sparse row = 0
#y_train_new = []
#X_train_new = []
for i in range(len(y_train)):
if np.sum(X_train[i].toarray()[0]) == 0:
X_train_new.append(X_train[i])
y_train_new.append(y_train[i])
当我这样做时:
X_train_new = scipy.sparse.csr_matrix(X_train_new)
我收到错误消息:
'ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all().'
答案 0 :(得分:0)
我添加了一些标签,这些标签可以帮助我更快地看到您的问题。
在询问错误时,提供部分或全部回溯是一个好主意,因此我们可以看到错误发生的位置。问题函数调用的输入信息也可以提供帮助。
幸运的是,我可以很容易地重现该问题-并且具有合理的大小示例。无需制作一个没人看的100000 x10000矩阵!
制作大小适中的稀疏矩阵:
In [126]: M = sparse.random(10,10,.1,'csr')
In [127]: M
Out[127]:
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
我可以进行整个矩阵行求和,就像使用密集数组一样。稀疏代码实际上使用矩阵矢量乘法来执行此操作,从而生成密集矩阵。
In [128]: M.sum(axis=1)
Out[128]:
matrix([[0.59659958],
[0.80390719],
[0.37251645],
[0. ],
[0.85766909],
[0.42267366],
[0.76794737],
[0. ],
[0.83131054],
[0.46254634]])
它非常稀疏,因此某些行没有零。对于浮点数,尤其是在0-1范围内,我不会获得非零值抵消掉的行。
或使用逐行计算:
In [133]: alist = [np.sum(row.toarray()[0]) for row in M]
In [134]: alist
Out[134]:
[0.5965995802776853,
0.8039071870427961,
0.37251644566924424,
0.0,
0.8576690924353791,
0.42267365715276595,
0.7679473651419432,
0.0,
0.8313105376003095,
0.4625463360625408]
并选择总和为零的行(在本例中为空):
In [135]: alist = [row for row in M if np.sum(row.toarray()[0])==0]
In [136]: alist
Out[136]:
[<1x10 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>,
<1x10 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>]
请注意,这是稀疏矩阵的列表。那也是你得到的,对吗?
现在,如果我尝试以此做矩阵,我会得到您的错误:
In [137]: sparse.csr_matrix(alist)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-137-5e20e6fc2524> in <module>
----> 1 sparse.csr_matrix(alist)
/usr/local/lib/python3.6/dist-packages/scipy/sparse/compressed.py in __init__(self, arg1, shape, dtype, copy)
86 "".format(self.format))
87 from .coo import coo_matrix
---> 88 self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype)))
89
90 # Read matrix dimensions given, if any
/usr/local/lib/python3.6/dist-packages/scipy/sparse/coo.py in __init__(self, arg1, shape, dtype, copy)
189 (shape, self._shape))
190
--> 191 self.row, self.col = M.nonzero()
192 self.data = M[self.row, self.col]
193 self.has_canonical_format = True
/usr/local/lib/python3.6/dist-packages/scipy/sparse/base.py in __bool__(self)
285 return self.nnz != 0
286 else:
--> 287 raise ValueError("The truth value of an array with more than one "
288 "element is ambiguous. Use a.any() or a.all().")
289 __nonzero__ = __bool__
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
好的,这个错误不会告诉我很多(至少在没有更多阅读代码的情况下),但是显然输入列表存在问题。但是,请再次阅读csr_matrix
文档!它说我们可以给它一个稀疏矩阵列表吗?
但是有一个sparse.vstack
函数可以使用一系列矩阵(在np.vstack
上建模):
In [140]: sparse.vstack(alist)
Out[140]:
<2x10 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
如果选择不加总为零的行,我们将得到更有趣的结果:
In [141]: alist = [row for row in M if np.sum(row.toarray()[0])!=0]
In [142]: M1=sparse.vstack(alist)
In [143]: M1
Out[143]:
<8x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
但是我之前展示过,我们无需迭代就可以获得行总和。将where
应用于Out[128]
,我得到(非零行的)行索引:
In [151]: idx=np.where(M.sum(axis=1))
In [152]: idx
Out[152]: (array([0, 1, 2, 4, 5, 6, 8, 9]), array([0, 0, 0, 0, 0, 0, 0, 0]))
In [153]: M2=M[idx[0],:]
In [154]: M2
Out[154]:
<8x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
In [155]: np.allclose(M1.A, M2.A)
Out[155]: True
====
我怀疑生成了In[137]
,试图查找输入的nonzero
(np.where
)元素,或将输入强制转换为numpy数组:
In [159]: alist = [row for row in M if np.sum(row.toarray()[0])==0]
In [160]: np.array(alist)
Out[160]:
array([<1x10 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>,
<1x10 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>], dtype=object)
In [161]: np.array(alist).nonzero()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-161-832a25987c15> in <module>
----> 1 np.array(alist).nonzero()
/usr/local/lib/python3.6/dist-packages/scipy/sparse/base.py in __bool__(self)
285 return self.nnz != 0
286 else:
--> 287 raise ValueError("The truth value of an array with more than one "
288 "element is ambiguous. Use a.any() or a.all().")
289 __nonzero__ = __bool__
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
稀疏矩阵列表上的 np.array
会生成这些矩阵的对象dtype数组。