我的代码如下所示:
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 进行训练)。
我该如何解决这个问题?
最佳答案
在这种情况下,通常可以避免将稀疏矩阵转换为密集格式。
例如,您可以 do the permutation并使用 CSR 或 CSC 稀疏格式轻松切片。
您还没有发布后面的代码,但我怀疑也可以用来处理稀疏输入。如果这是真的,您的内存力问题将不再是问题。
关于python - Python 转换为数组时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879139/