我正在实现一个涉及对numpy数组进行操作的函数,并且正在获得Memory Error
。我明确指出了正在创建问题的numpy数组的尺寸。
a = np.random.rand(15239,1)
b = np.random.rand(1,329960)
c = np.subtract(a,b)**2
d = np.random.rand(15239,1)
e = np.random.rand(1,329960)
del a
gc.collect()
f = np.subtract(d,e)**2
del d
gc.collect()
g = np.sqrt(c + f).min(axis=0)
del c,f
gc.collect()
我在运行它们时得到Memory Error
。
尽管,使用它们的功能在下面给出-
def make_weight_map(masks):
"""
Generate the weight maps as specified in the UNet paper
for a set of binary masks.
Parameters
----------
masks: array-like
A 3D array of shape (n_masks, image_height, image_width),
where each slice of the matrix along the 0th axis represents one binary mask.
Returns
-------
array-like
A 2D array of shape (image_height, image_width)
"""
masks = masks.numpy()
nrows, ncols = masks.shape[1:]
masks = (masks > 0).astype(int)
distMap = np.zeros((nrows * ncols, masks.shape[0]))
X1, Y1 = np.meshgrid(np.arange(nrows), np.arange(ncols))
X1, Y1 = np.c_[X1.ravel(), Y1.ravel()].T
for i, mask in enumerate(masks):
# find the boundary of each mask,
# compute the distance of each pixel from this boundary
bounds = find_boundaries(mask, mode='inner')
X2, Y2 = np.nonzero(bounds)
xSum = (X2.reshape(-1, 1) - X1.reshape(1, -1)) ** 2
ySum = (Y2.reshape(-1, 1) - Y1.reshape(1, -1)) ** 2
distMap[:, i] = np.sqrt(xSum + ySum).min(axis=0)
ix = np.arange(distMap.shape[0])
if distMap.shape[1] == 1:
d1 = distMap.ravel()
border_loss_map = w0 * np.exp((-1 * (d1) ** 2) / (2 * (sigma ** 2)))
else:
if distMap.shape[1] == 2:
d1_ix, d2_ix = np.argpartition(distMap, 1, axis=1)[:, :2].T
else:
d1_ix, d2_ix = np.argpartition(distMap, 2, axis=1)[:, :2].T
d1 = distMap[ix, d1_ix]
d2 = distMap[ix, d2_ix]
border_loss_map = w0 * np.exp((-1 * (d1 + d2) ** 2) / (2 * (sigma ** 2)))
xBLoss = np.zeros((nrows, ncols))
xBLoss[X1, Y1] = border_loss_map
# class weight map
loss = np.zeros((nrows, ncols))
w_1 = 1 - masks.sum() / loss.size
w_0 = 1 - w_1
loss[masks.sum(0) == 1] = w_1
loss[masks.sum(0) == 0] = w_0
ZZ = xBLoss + loss
return ZZ
在函数中使用时错误的跟踪低于-我正在使用32 GB RAM的系统,我也在61 GB RAM上测试了代码-
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-32-0f30ef7dc24d> in <module>
----> 1 img = make_weight_map(img)
<ipython-input-31-e75a6281476f> in make_weight_map(masks)
34 xSum = (X2.reshape(-1, 1) - X1.reshape(1, -1)) ** 2
35 ySum = (Y2.reshape(-1, 1) - Y1.reshape(1, -1)) ** 2
---> 36 distMap[:, i] = np.sqrt(xSum + ySum).min(axis=0)
37 ix = np.arange(distMap.shape[0])
38 if distMap.shape[1] == 1:
MemoryError:
我已经检查了以下问题,但找不到解决问题的方法-Python/Numpy Memory ErrorMemory growth with broadcast operations in NumPy
这是Memmap方法的另一个问题,但我不知道如何在用例中应用。
没什么神秘的,这些都是很大的阵列。以64位精度,形状为(15239,329960)
的数组需要...
>>> np.product((15239,329960)) * 8 / 2**30
37.46345967054367
...大约37GiB!可以尝试的事情:
np.float16
,需要25%的内存。scipy.sparse
?scipy.sparse
了?