Python 在numpy阵列上执行操作时获取内存错误

Python 在numpy阵列上执行操作时获取内存错误,python,arrays,numpy,bigdata,Python,Arrays,Numpy,Bigdata,我正在对更高维的numpy数组执行一个包含不同操作(减法、平方、广播)的操作。我的代码在执行此类操作时出现内存错误 下面是我的代码- from skimage.segmentation import find_boundaries w0 = 10 sigma = 5 def make_weight_map(masks): """ Generate the weight maps as specified in the UNet paper for a set of b

我正在对更高维的numpy数组执行一个包含不同操作(减法、平方、广播)的操作。我的代码在执行此类操作时出现
内存错误

下面是我的代码-

from skimage.segmentation import find_boundaries

w0 = 10
sigma = 5

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

    #In the below for loop, I am getting the Memory Error
    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
为了重现问题,维度的numpy数组
4584565
可以重新创建问题

错误的回溯-

---------------------------------------------------------------------------
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:
主要问题出现在这一行中,因为X2的形状是
(15239,1)
,X1的形状是
(1329960)
,所以首先它必须执行一个庞大的广播操作

distmap,我无法计算,因为在此之前我的代码暂停。
另外,如果我尝试对上述维度执行以下减法操作,代码也会在那里停止

X2.reshape(-1, 1) - X1.reshape(1, -1)
我使用的是32 Gb内存的系统,我还尝试在64 Gb内存的云上运行。 我已经检查了以下问题,要么它们没有提供我问题的解决方案,要么我无法应用到我的用例中




错误在哪里?回溯?如果您告诉我们此时数组的大小,
distMap
X2
,等等,这会有所帮助。考虑到错误表达式,我怀疑问题只是许多大型数组的累积,有些是暂时的。此时您没有创建过大的数组。您好,我在问题中添加了一些其他信息,请检查。
X2.reshape(-1, 1) - X1.reshape(1, -1)