Skip to main content
 首页 » 编程设计

python之在大矩阵中找到满足特定条件的元素的所有索引给出 MemoryError

2025年01月19日15myhome

我的环境是 Python 3.6 64 位和 64 位 win 10 16GB 内存。

我有一个形状为 (260923,) 的 ndarray。我想找到大于阈值的所有元素的索引。我正在使用这段代码,但它给出了内存错误。在任务管理器中,我可以看到我所有的内存都用完了。

x_selected = x[:,x_attr] 
index_right = (x_selected >thres).nonzero()[0] 

我有 16GB 的 ram 并将我的 PyCharm 堆内存更改为 6GB,但问题仍然存在。 这就是 ndarray 在调试器中的样子。

这是完整的错误:

我应该怎么做才能得到所有的索引?

澄清:

x 是另一个形状为 (260923,225) 的 ndarray。 x_attr 只是一个整数。所以“x_selected = x[:,x_attr]”只是从 x(二维数组)中选择一列。这是 x 在调试器中的样子: 当我试图找到索引时发生 MemoreyError(我上面写的代码) 如果我缩小 x_selected 的行,代码就可以工作。

#This does NOT work 
index_left = (x_selected <= thres).nonzero()[0] 
#This works however 
index_left = (x_selected[0:1000] <= thres).nonzero()[0] 
#This does NOT work Error: "Comparing a sparse matrix with a scalar " 
#error:  " raise NotImplementedError(" >= and <= don't work with 0.")" 
test = list(x[:,x_attr]) 
if test[1]<=thres: 
    a=1 

请您参考如下方法:

在具有 1.25GB RAM 的 x32 机器上运行 WFM。因此,问题一定与您提供的特定代码无关。

一次一步地执行操作并检查变量、进程和对象的内部状态的内存消耗可能会给你一个线索。

(就像老问题本地化一样:如果当你扔掉代码的其他部分时它消失了,或者扔掉所有东西然后开始添加它。一次添加/删除一半的数量会给你一个结果步数的对数。)

In [41]: x=np.random.randint(2**30,size=(260923*225),dtype=np.int64).reshape( 
    ...: (260923,225)) 
 
In [42]: x.nbytes 
Out[42]: 469661400 
 
In [43]: x_selected = x[:,0] 
 
In [44]: x_selected.nbytes 
Out[44]: 2087384 
 
In [45]: from dump import dump 
 
In [46]: dump(x_selected) 
T : [ 728497578 1063110548   71820681 ...,  701362408 1030850648  908176708] 
base : [728497578 297238747 162734746 ..., 262530510 654517286 329271071] 
ctypes : <numpy.core._internal._ctypes object at 0x028DEC10> 
dtype : int64 
flags :   C_CONTIGUOUS : False 
  F_CONTIGUOUS : False 
  OWNDATA : False 
  WRITEABLE : True 
  ALIGNED : True 
  UPDATEIFCOPY : False 
flat : <numpy.flatiter object at 0x027A3C30> 
imag : [0 0 0 ..., 0 0 0] 
itemsize : 8 
nbytes : 2087384 
ndim : 1 
real : [ 728497578 1063110548   71820681 ...,  701362408 1030850648  908176708] 
shape : (260923,) 
size : 260923 
strides : (1800,) 
 
In [58]: x.base is None 
Out[58]: False    #due to .reshape(), x does not own its memory 
 
In [57]: x_selected.base is x.base 
Out[57]: True      # but they use the same memory anyway, so x_selected does not use up extra 
 
In [48]: c=(x_selected >1000000) 
 
In [49]: c.nbytes 
Out[49]: 260923     #c is an ndarray of bools, each bool is thus 1 byte 
 
In [50]: n=c.nonzero() 
 
In [59]: sys.getsizeof(n) 
Out[59]: 32     #just holds a reference to the sole element 
 
In [51]: r=n[0] 
 
In [52]: r.nbytes 
Out[52]: 1042656