Keras图像分割的像素加权损失法

2024-06-28 10:58:28 发布

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

我目前正在使用一个改进版的U-Net(https://arxiv.org/pdf/1505.04597.pdf)来分割显微镜图像中的细胞器。因为我使用Keras,所以我从https://github.com/zhixuhao/unet获取代码。然而,在这个版本中没有实现权重映射来强制网络学习边界像素。在

到目前为止,我得到的结果是相当好的,但网络无法分离彼此靠近的对象。所以我想试着利用文中提到的权重图。我已经能够为每个标签图像生成权重图(基于给定的公式),但是我无法找到如何使用该权重图来训练我的网络,从而解决上述问题。在

权重图和标签图像必须以某种方式组合起来,还是有一个Keras函数可以让我使用权重图?我是生物学家,最近才开始研究神经网络,所以我的理解还是有限的。任何帮助或建议将不胜感激。在


Tags: httpsorg图像网络githubcomunetnet
2条回答

我想你应该在Keras中使用class_weight。如果已经计算了类权重,那么在模型中引入这一点非常简单。在

  1. 创建一个包含类标签及其关联权重的词典。例如

    class_weight = {0: 10.9,
            1: 20.8,
            2: 1.0,
            3: 50.5}
    
  2. 或者创建一个1D Numpy数组,其长度与类的数量相同。例如

    class_weight = [10.9, 20.8, 1.0, 50.5]
    
  3. 在您的model.fitmodel.fit_generator中的培训期间传递此参数

    model.fit(x, y, batch_size=batch_size, epochs=num_epochs, verbose=1, class_weight=class_weight)
    

您可以查阅Keras文档以了解更多细节here。在

以防它仍然相关:我最近需要解决这个问题。您可以将下面的代码粘贴到Jupyter笔记本中,以查看它是如何工作的。在

%matplotlib inline
import numpy as np
from skimage.io import imshow
from skimage.measure import label
from scipy.ndimage.morphology import distance_transform_edt
import numpy as np

def generate_random_circles(n = 100, d = 256):
    circles = np.random.randint(0, d, (n, 3))
    x = np.zeros((d, d), dtype=int)
    f = lambda x, y: ((x - x0)**2 + (y - y0)**2) <= (r/d*10)**2
    for x0, y0, r in circles:
        x += np.fromfunction(f, x.shape)
    x = np.clip(x, 0, 1)

    return x

def unet_weight_map(y, wc=None, w0 = 10, sigma = 5):

    """
    Generate weight maps as specified in the U-Net paper
    for boolean mask.

    "U-Net: Convolutional Networks for Biomedical Image Segmentation"
    https://arxiv.org/pdf/1505.04597.pdf

    Parameters
         
    mask: Numpy array
        2D array of shape (image_height, image_width) representing binary mask
        of objects.
    wc: dict
        Dictionary of weight classes.
    w0: int
        Border weight parameter.
    sigma: int
        Border width parameter.

    Returns
       -
    Numpy array
        Training weights. A 2D array of shape (image_height, image_width).
    """

    labels = label(y)
    no_labels = labels == 0
    label_ids = sorted(np.unique(labels))[1:]

    if len(label_ids) > 1:
        distances = np.zeros((y.shape[0], y.shape[1], len(label_ids)))

        for i, label_id in enumerate(label_ids):
            distances[:,:,i] = distance_transform_edt(labels != label_id)

        distances = np.sort(distances, axis=2)
        d1 = distances[:,:,0]
        d2 = distances[:,:,1]
        w = w0 * np.exp(-1/2*((d1 + d2) / sigma)**2) * no_labels
    else:
        w = np.zeros_like(y)
    if wc:
        class_weights = np.zeros_like(y)
        for k, v in wc.items():
            class_weights[y == k] = v
        w = w + class_weights
    return w

y = generate_random_circles()

wc = {
    0: 1, # background
    1: 5  # objects
}

w = unet_weight_map(y, wc)

imshow(w)

相关问题 更多 >