转换为数组时Python出现内存错误

2024-06-25 07:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下所示:

from sklearn.datasets import load_svmlight_files
import numpy as np

perm1 =np.random.permutation(25000)
perm2 = np.random.permutation(25000)

X_tr, y_tr, X_te, y_te = load_svmlight_files(("dir/file.feat", "dir/file.feat"))

#randomly shuffle data
X_train = X_tr[perm1,:].toarray()[:,0:2000]
y_train = y_tr[perm1]>5 #turn into binary problem

在这里之前,代码还可以正常工作,但是当我试图将另一个对象转换为数组时,我的程序返回一个内存错误。

代码:

X_test = X_te[perm2,:].toarray()[:,0:2000]

错误:

---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-7-31f5e4f6b00c> in <module>()
----> 1 X_test = X_test.toarray()

C:\Users\Asq\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\sparse\compressed.pyc in toarray(self, order, out)
    788     def toarray(self, order=None, out=None):
    789         """See the docstring for `spmatrix.toarray`."""
--> 790         return self.tocoo(copy=False).toarray(order=order, out=out)
    791 
    792     ##############################################################

C:\Users\Asq\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\sparse\coo.pyc in toarray(self, order, out)
    237     def toarray(self, order=None, out=None):
    238         """See the docstring for `spmatrix.toarray`."""
--> 239         B = self._process_toarray_args(order, out)
    240         fortran = int(B.flags.f_contiguous)
    241         if not fortran and not B.flags.c_contiguous:

C:\Users\Asq\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\sparse\base.pyc in _process_toarray_args(self, order, out)
    697             return out
    698         else:
--> 699             return np.zeros(self.shape, dtype=self.dtype, order=order)
    700 
    701 

MemoryError: 

我是python新手,我不知道是否需要手动修复内存错误。

我的代码的其他部分返回相同的错误(例如使用knn或ann进行训练)。

我该怎么解决?


Tags: 代码intestselfnone错误nporder
2条回答

使用numpy.asarray()就地转换,而不是需要新内存的toarray()。

在这种情况下,通常可以避免将稀疏矩阵转换为密集格式。

例如,可以使用CSR或CSC稀疏格式轻松地do the permutation和切片。

您还没有发布下面的代码,但我怀疑这也可以用来处理稀疏输入。如果这是真的,你的内存问题将不再是一个问题。

相关问题 更多 >