Skip to content

napari_cellseg3d.code_models.models.wnet.soft_Ncuts

Implementation of a 3D Soft N-Cuts loss based on https://arxiv.org/abs/1711.08506 and https://ieeexplore.ieee.org/document/868688.

The implementation was adapted and approximated to reduce computational and memory cost. This faster version was proposed on https://github.com/fkodom/wnet-unsupervised-image-segmentation.

Classes:

Name Description
SoftNCutsLoss

Implementation of a 3D Soft N-Cuts loss based on https://arxiv.org/abs/1711.08506 and https://ieeexplore.ieee.org/document/868688.

SoftNCutsLoss

Bases: Module

Implementation of a 3D Soft N-Cuts loss based on https://arxiv.org/abs/1711.08506 and https://ieeexplore.ieee.org/document/868688.

Parameters:

Name Type Description Default
data_shape (H, W, D)

shape of the images as a tuple.

required
intensity_sigma scalar

scale of the gaussian kernel of pixels brightness.

required
spatial_sigma scalar

scale of the gaussian kernel of pixels spacial distance.

required
radius scalar

radius of pixels for which we compute the weights

None

Methods:

Name Description
__init__

Initialize the Soft N-Cuts loss.

forward

Forward pass of the Soft N-Cuts loss.

gaussian_kernel

Computes the Gaussian kernel.

Source code in napari_cellseg3d/code_models/models/wnet/soft_Ncuts.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class SoftNCutsLoss(nn.Module):
    """Implementation of a 3D Soft N-Cuts loss based on https://arxiv.org/abs/1711.08506 and https://ieeexplore.ieee.org/document/868688.

    Args:
        data_shape (H, W, D): shape of the images as a tuple.
        intensity_sigma (scalar): scale of the gaussian kernel of pixels brightness.
        spatial_sigma (scalar): scale of the gaussian kernel of pixels spacial distance.
        radius (scalar): radius of pixels for which we compute the weights
    """

    def __init__(self, data_shape, device, intensity_sigma, spatial_sigma, radius=None):
        """Initialize the Soft N-Cuts loss.

        Args:
            data_shape (H, W, D): shape of the images as a tuple.
            device (torch.device): device on which the loss is computed.
            intensity_sigma (scalar): scale of the gaussian kernel of pixels brightness.
            spatial_sigma (scalar): scale of the gaussian kernel of pixels spacial distance.
            radius (scalar): radius of pixels for which we compute the weights
        """
        super(SoftNCutsLoss, self).__init__()
        self.intensity_sigma = intensity_sigma
        self.spatial_sigma = spatial_sigma
        self.radius = radius
        self.H = data_shape[0]
        self.W = data_shape[1]
        self.D = data_shape[2]
        self.device = device

        if self.radius is None:
            self.radius = min(
                max(5, math.ceil(min(self.H, self.W, self.D) / 20)),
                self.H,
                self.W,
                self.D,
            )
        logger.info(f"Radius set to {self.radius}")

    def forward(self, labels, inputs):
        """Forward pass of the Soft N-Cuts loss.

        Args:
            labels (torch.Tensor): Tensor of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.
            inputs (torch.Tensor): Tensor of shape (N, C, H, W, D) containing the input images.

        Returns:
            The Soft N-Cuts loss of shape (N,).
        """
        # inputs.shape[0]
        # inputs.shape[1]
        K = labels.shape[1]

        labels.to(self.device)
        inputs.to(self.device)

        loss = 0

        kernel = self.gaussian_kernel(self.radius, self.spatial_sigma).to(self.device)

        for k in range(K):
            # Compute the average pixel value for this class, and the difference from each pixel
            class_probs = labels[:, k].unsqueeze(1)
            class_mean = torch.mean(
                inputs * class_probs, dim=(2, 3, 4), keepdim=True
            ) / torch.add(torch.mean(class_probs, dim=(2, 3, 4), keepdim=True), 1e-5)
            diff = (inputs - class_mean).pow(2).sum(dim=1).unsqueeze(1)

            # Weight the loss by the difference from the class average.
            weights = torch.exp(diff.pow(2).mul(-1 / self.intensity_sigma**2))

            numerator = torch.sum(
                class_probs
                * F.conv3d(class_probs * weights, kernel, padding=self.radius),
                dim=(1, 2, 3, 4),
            )
            denominator = torch.sum(
                class_probs * F.conv3d(weights, kernel, padding=self.radius),
                dim=(1, 2, 3, 4),
            )
            loss += nn.L1Loss()(
                numerator / torch.add(denominator, 1e-6),
                torch.zeros_like(numerator),
            )

        return K - loss

    def gaussian_kernel(self, radius, sigma):
        """Computes the Gaussian kernel.

        Args:
            radius (int): The radius of the kernel.
            sigma (float): The standard deviation of the Gaussian distribution.

        Returns:
            The Gaussian kernel of shape (1, 1, 2*radius+1, 2*radius+1, 2*radius+1).
        """
        x_2 = np.linspace(-radius, radius, 2 * radius + 1) ** 2
        dist = (
            np.sqrt(
                x_2.reshape(-1, 1, 1) + x_2.reshape(1, -1, 1) + x_2.reshape(1, 1, -1)
            )
            / sigma
        )
        kernel = norm.pdf(dist) / norm.pdf(0)
        kernel = torch.from_numpy(kernel.astype(np.float32))
        return kernel.view((1, 1, kernel.shape[0], kernel.shape[1], kernel.shape[2]))

__init__

__init__(data_shape, device, intensity_sigma, spatial_sigma, radius=None)

Initialize the Soft N-Cuts loss.

Parameters:

Name Type Description Default
data_shape (H, W, D)

shape of the images as a tuple.

required
device device

device on which the loss is computed.

required
intensity_sigma scalar

scale of the gaussian kernel of pixels brightness.

required
spatial_sigma scalar

scale of the gaussian kernel of pixels spacial distance.

required
radius scalar

radius of pixels for which we compute the weights

None
Source code in napari_cellseg3d/code_models/models/wnet/soft_Ncuts.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(self, data_shape, device, intensity_sigma, spatial_sigma, radius=None):
    """Initialize the Soft N-Cuts loss.

    Args:
        data_shape (H, W, D): shape of the images as a tuple.
        device (torch.device): device on which the loss is computed.
        intensity_sigma (scalar): scale of the gaussian kernel of pixels brightness.
        spatial_sigma (scalar): scale of the gaussian kernel of pixels spacial distance.
        radius (scalar): radius of pixels for which we compute the weights
    """
    super(SoftNCutsLoss, self).__init__()
    self.intensity_sigma = intensity_sigma
    self.spatial_sigma = spatial_sigma
    self.radius = radius
    self.H = data_shape[0]
    self.W = data_shape[1]
    self.D = data_shape[2]
    self.device = device

    if self.radius is None:
        self.radius = min(
            max(5, math.ceil(min(self.H, self.W, self.D) / 20)),
            self.H,
            self.W,
            self.D,
        )
    logger.info(f"Radius set to {self.radius}")

forward

forward(labels, inputs)

Forward pass of the Soft N-Cuts loss.

Parameters:

Name Type Description Default
labels Tensor

Tensor of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.

required
inputs Tensor

Tensor of shape (N, C, H, W, D) containing the input images.

required

Returns:

Type Description

The Soft N-Cuts loss of shape (N,).

Source code in napari_cellseg3d/code_models/models/wnet/soft_Ncuts.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def forward(self, labels, inputs):
    """Forward pass of the Soft N-Cuts loss.

    Args:
        labels (torch.Tensor): Tensor of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.
        inputs (torch.Tensor): Tensor of shape (N, C, H, W, D) containing the input images.

    Returns:
        The Soft N-Cuts loss of shape (N,).
    """
    # inputs.shape[0]
    # inputs.shape[1]
    K = labels.shape[1]

    labels.to(self.device)
    inputs.to(self.device)

    loss = 0

    kernel = self.gaussian_kernel(self.radius, self.spatial_sigma).to(self.device)

    for k in range(K):
        # Compute the average pixel value for this class, and the difference from each pixel
        class_probs = labels[:, k].unsqueeze(1)
        class_mean = torch.mean(
            inputs * class_probs, dim=(2, 3, 4), keepdim=True
        ) / torch.add(torch.mean(class_probs, dim=(2, 3, 4), keepdim=True), 1e-5)
        diff = (inputs - class_mean).pow(2).sum(dim=1).unsqueeze(1)

        # Weight the loss by the difference from the class average.
        weights = torch.exp(diff.pow(2).mul(-1 / self.intensity_sigma**2))

        numerator = torch.sum(
            class_probs
            * F.conv3d(class_probs * weights, kernel, padding=self.radius),
            dim=(1, 2, 3, 4),
        )
        denominator = torch.sum(
            class_probs * F.conv3d(weights, kernel, padding=self.radius),
            dim=(1, 2, 3, 4),
        )
        loss += nn.L1Loss()(
            numerator / torch.add(denominator, 1e-6),
            torch.zeros_like(numerator),
        )

    return K - loss

gaussian_kernel

gaussian_kernel(radius, sigma)

Computes the Gaussian kernel.

Parameters:

Name Type Description Default
radius int

The radius of the kernel.

required
sigma float

The standard deviation of the Gaussian distribution.

required

Returns:

Type Description

The Gaussian kernel of shape (1, 1, 2radius+1, 2radius+1, 2*radius+1).

Source code in napari_cellseg3d/code_models/models/wnet/soft_Ncuts.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def gaussian_kernel(self, radius, sigma):
    """Computes the Gaussian kernel.

    Args:
        radius (int): The radius of the kernel.
        sigma (float): The standard deviation of the Gaussian distribution.

    Returns:
        The Gaussian kernel of shape (1, 1, 2*radius+1, 2*radius+1, 2*radius+1).
    """
    x_2 = np.linspace(-radius, radius, 2 * radius + 1) ** 2
    dist = (
        np.sqrt(
            x_2.reshape(-1, 1, 1) + x_2.reshape(1, -1, 1) + x_2.reshape(1, 1, -1)
        )
        / sigma
    )
    kernel = norm.pdf(dist) / norm.pdf(0)
    kernel = torch.from_numpy(kernel.astype(np.float32))
    return kernel.view((1, 1, kernel.shape[0], kernel.shape[1], kernel.shape[2]))