Skip to content

napari_cellseg3d.code_models.models.model_WNet

Wrapper for the W-Net model, with the decoder weights removed.

.. important:: Used for inference only. For training the base class is used.

Classes:

Name Description
WNet_

W-Net wrapper for napari_cellseg3d.

Attributes:

Name Type Description
NUM_CLASSES_KEY

State-dict key of the encoder's final conv bias, whose length is the number of classes.

NUM_CLASSES_KEY module-attribute

NUM_CLASSES_KEY = 'encoder.out_b.module.8.bias'

State-dict key of the encoder's final conv bias, whose length is the number of classes.

WNet_

Bases: WNet_encoder

W-Net wrapper for napari_cellseg3d.

..important:: Used for inference only, therefore only the encoder is used. For training the base class is used.

Methods:

Name Description
__init__

Create a W-Net model.

forward

Forward pass of the W-Net model.

load_state_dict

Load the model state dict for inference, without the decoder weights.

num_classes_from_weights

Number of encoder output classes stored in a .pth weights file, or None if it cannot be read.

Attributes:

Name Type Description
default_channel

Foreground channel of the pretrained weights.

Source code in napari_cellseg3d/code_models/models/model_WNet.py
21
22
23
24
25
26
27
28
29
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
class WNet_(WNet_encoder):
    """W-Net wrapper for napari_cellseg3d.

    ..important:: Used for inference only, therefore only the encoder is used. For training the base class is used.
    """

    weights_file = "wnet_latest.pth"
    default_threshold = 0.6
    default_channel = 1
    """Foreground channel of the pretrained weights."""

    def __init__(
        self,
        in_channels=1,
        out_channels=2,
        # num_classes=2,
        **kwargs,
    ):
        """Create a W-Net model.

        Args:
            in_channels (int): number of input channels
            out_channels (int): number of output channels.
            **kwargs: additional arguments to WNet_encoder.
        """
        super().__init__(
            in_channels=in_channels,
            out_channels=out_channels,
            # num_classes=num_classes,
            softmax=False,
        )

    # def train(self: T, mode: bool = True) -> T:
    #     raise NotImplementedError("Training not implemented for WNet")

    def forward(self, x):
        """Forward pass of the W-Net model."""
        norm_x = remap_image(x)
        return super().forward(norm_x)

    @staticmethod
    def num_classes_from_weights(weights_path) -> Optional[int]:
        """Number of encoder output classes stored in a .pth weights file, or None if it cannot be read."""
        if Path(weights_path).suffix != ".pth":
            return None
        try:
            state_dict = torch.load(weights_path, map_location="cpu", weights_only=True)
            return int(state_dict[NUM_CLASSES_KEY].shape[0])
        except (
            OSError,
            RuntimeError,
            KeyError,
            AttributeError,
            pickle.UnpicklingError,
        ) as e:
            logger.debug(f"Could not read number of classes from {weights_path}: {e}")
            return None

    def load_state_dict(self, state_dict, strict=True):
        """Load the model state dict for inference, without the decoder weights."""
        encoder_checkpoint = state_dict.copy()
        for k in state_dict:
            if k.startswith("decoder"):
                encoder_checkpoint.pop(k)
        # print(encoder_checkpoint.keys())
        super().load_state_dict(encoder_checkpoint, strict=strict)

default_channel class-attribute instance-attribute

default_channel = 1

Foreground channel of the pretrained weights.

__init__

__init__(in_channels=1, out_channels=2, **kwargs)

Create a W-Net model.

Parameters:

Name Type Description Default
in_channels int

number of input channels

1
out_channels int

number of output channels.

2
**kwargs

additional arguments to WNet_encoder.

{}
Source code in napari_cellseg3d/code_models/models/model_WNet.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def __init__(
    self,
    in_channels=1,
    out_channels=2,
    # num_classes=2,
    **kwargs,
):
    """Create a W-Net model.

    Args:
        in_channels (int): number of input channels
        out_channels (int): number of output channels.
        **kwargs: additional arguments to WNet_encoder.
    """
    super().__init__(
        in_channels=in_channels,
        out_channels=out_channels,
        # num_classes=num_classes,
        softmax=False,
    )

forward

forward(x)

Forward pass of the W-Net model.

Source code in napari_cellseg3d/code_models/models/model_WNet.py
56
57
58
59
def forward(self, x):
    """Forward pass of the W-Net model."""
    norm_x = remap_image(x)
    return super().forward(norm_x)

load_state_dict

load_state_dict(state_dict, strict=True)

Load the model state dict for inference, without the decoder weights.

Source code in napari_cellseg3d/code_models/models/model_WNet.py
79
80
81
82
83
84
85
86
def load_state_dict(self, state_dict, strict=True):
    """Load the model state dict for inference, without the decoder weights."""
    encoder_checkpoint = state_dict.copy()
    for k in state_dict:
        if k.startswith("decoder"):
            encoder_checkpoint.pop(k)
    # print(encoder_checkpoint.keys())
    super().load_state_dict(encoder_checkpoint, strict=strict)

num_classes_from_weights staticmethod

num_classes_from_weights(weights_path) -> Optional[int]

Number of encoder output classes stored in a .pth weights file, or None if it cannot be read.

Source code in napari_cellseg3d/code_models/models/model_WNet.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@staticmethod
def num_classes_from_weights(weights_path) -> Optional[int]:
    """Number of encoder output classes stored in a .pth weights file, or None if it cannot be read."""
    if Path(weights_path).suffix != ".pth":
        return None
    try:
        state_dict = torch.load(weights_path, map_location="cpu", weights_only=True)
        return int(state_dict[NUM_CLASSES_KEY].shape[0])
    except (
        OSError,
        RuntimeError,
        KeyError,
        AttributeError,
        pickle.UnpicklingError,
    ) as e:
        logger.debug(f"Could not read number of classes from {weights_path}: {e}")
        return None