Network architectures¶
Blocks¶
Convolution¶
-
class
monai.networks.blocks.
Convolution
(dimensions, in_channels, out_channels, strides=1, kernel_size=3, act='PRELU', norm='INSTANCE', dropout=None, dilation=1, bias=True, conv_only=False, is_transposed=False)[source]¶ Constructs a convolution with optional dropout, normalization, and activation layers.
Initializes internal Module state, shared by both nn.Module and ScriptModule.
ResidualUnit¶
-
class
monai.networks.blocks.
ResidualUnit
(dimensions, in_channels, out_channels, strides=1, kernel_size=3, subunits=2, act='PRELU', norm='INSTANCE', dropout=None, dilation=1, bias=True, last_conv_only=False)[source]¶ Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
-
Squeeze-and-Excitation¶
-
class
monai.networks.blocks.
ChannelSELayer
(spatial_dims, in_channels, r=2, acti_type_1='relu', acti_type_2='sigmoid')[source]¶ Re-implementation of the Squeeze-and-Excitation block based on: “Hu et al., Squeeze-and-Excitation Networks, https://arxiv.org/abs/1709.01507”.
- Parameters
spatial_dims (
int
) – number of spatial dimensions, could be 1, 2, or 3.in_channels (
int
) – number of input channels.r (
int
) – the reduction ratio r in the paper. Defaults to 2.acti_type_1 (
str
) – activation type of the hidden squeeze layer. Defaults to “relu”.acti_type_2 (
str
) – activation type of the output squeeze layer. Defaults to “sigmoid”.
- Raises
ValueError – r must be a positive number smaller than in_channels.
Residual Squeeze-and-Excitation¶
-
class
monai.networks.blocks.
ResidualSELayer
(spatial_dims, in_channels, r=2, acti_type_1='leakyrelu', acti_type_2='relu')[source]¶ A “squeeze-and-excitation”-like layer with a residual connection.
- Parameters
spatial_dims (
int
) – number of spatial dimensions, could be 1, 2, or 3.in_channels (
int
) – number of input channels.r (
int
) – the reduction ratio r in the paper. Defaults to 2.acti_type_1 (
str
) – defaults to “leakyrelu”.acti_type_2 (
str
) – defaults to “relu”.
See also :
monai.networks.blocks.ChannelSELayer
.
Simple ASPP¶
-
class
monai.networks.blocks.
SimpleASPP
(spatial_dims, in_channels, conv_out_channels, kernel_sizes=(1, 3, 3, 3), dilations=(1, 2, 4, 6), norm_type='BATCH', acti_type='LEAKYRELU')[source]¶ A simplified version of the atrous spatial pyramid pooling (ASPP) module.
Chen et al., Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation. https://arxiv.org/abs/1802.02611
Wang et al., A Noise-robust Framework for Automatic Segmentation of COVID-19 Pneumonia Lesions from CT Images. https://ieeexplore.ieee.org/document/9109297
- Parameters
spatial_dims (
int
) – number of spatial dimensions, could be 1, 2, or 3.in_channels (
int
) – number of input channels.conv_out_channels (
int
) – number of output channels of each atrous conv. The final number of output channels is conv_out_channels * len(kernel_sizes).kernel_sizes – a sequence of four convolutional kernel sizes. Defaults to (1, 3, 3, 3) for four (dilated) convolutions.
dilations – a sequence of four convolutional dilation parameters. Defaults to (1, 2, 4, 6) for four (dilated) convolutions.
norm_type – final kernel-size-one convolution normalization type. Defaults to batch norm.
acti_type – final kernel-size-one convolution activation type. Defaults to leaky ReLU.
- Raises
ValueError – len(kernel_sizes) and len(dilations) must be the same.
MaxAvgPooling¶
-
class
monai.networks.blocks.
MaxAvgPool
(spatial_dims, kernel_size, stride=None, padding=0, ceil_mode=False)[source]¶ Downsample with both maxpooling and avgpooling, double the channel size by concatenating the downsampled feature maps.
- Parameters
spatial_dims (
int
) – number of spatial dimensions of the input image.kernel_size – the kernel size of both pooling operations.
stride – the stride of the window. Default value is kernel_size.
padding – implicit zero padding to be added to both pooling operations.
ceil_mode (
bool
) – when True, will use ceil instead of floor to compute the output shape.
Upsampling¶
-
class
monai.networks.blocks.
UpSample
(spatial_dims, in_channels, out_channels=None, scale_factor=2, with_conv=False, mode=<UpsampleMode.LINEAR: 'linear'>, align_corners=True)[source]¶ Upsample with either kernel 1 conv + interpolation or transposed conv.
- Parameters
spatial_dims (
int
) – number of spatial dimensions of the input image.in_channels (
int
) – number of channels of the input image.out_channels (
Optional
[int
]) – number of channels of the output image. Defaults to in_channels.scale_factor – multiplier for spatial size. Has to match input size if it is a tuple. Defaults to 2.
with_conv (
bool
) – whether to use a transposed convolution for upsampling. Defaults to False.mode (
Union
[UpsampleMode
,str
]) – {"nearest"
,"linear"
,"bilinear"
,"bicubic"
,"trilinear"
} If ends with"linear"
will usespatial dims
to determine the correct interpolation. This corresponds to linear, bilinear, trilinear for 1D, 2D, and 3D respectively. The interpolation mode. Defaults to"linear"
. See also: https://pytorch.org/docs/stable/nn.html#upsamplealign_corners (
Optional
[bool
]) – set the align_corners parameter of torch.nn.Upsample. Defaults to True.
Layers¶
Factories¶
Defines factories for creating layers in generic, extensible, and dimensionally independent ways. A separate factory object is created for each type of layer, and factory functions keyed to names are added to these objects. Whenever a layer is requested the factory name and any necessary arguments are passed to the factory object. The return value is typically a type but can be any callable producing a layer object.
The factory objects contain functions keyed to names converted to upper case, these names can be referred to as members of the factory so that they can function as constant identifiers. eg. instance normalisation is named Norm.INSTANCE.
For example, to get a transpose convolution layer the name is needed and then a dimension argument is provided which is passed to the factory function:
dimension = 3
name = Conv.CONVTRANS
conv = Conv[name, dimension]
This allows the dimension value to be set in the constructor, for example so that the dimensionality of a network is parameterizable. Not all factories require arguments after the name, the caller must be aware which are required.
Defining new factories involves creating the object then associating it with factory functions:
fact = LayerFactory()
@fact.factory_function('test')
def make_something(x, y):
# do something with x and y to choose which layer type to return
return SomeLayerType
...
# request object from factory TEST with 1 and 2 as values for x and y
layer = fact[fact.TEST, 1, 2]
Typically the caller of a factory would know what arguments to pass (ie. the dimensionality of the requested type) but can be parameterized with the factory name and the arguments to pass to the created type at instantiation time:
def use_factory(fact_args):
fact_name, type_args = split_args
layer_type = fact[fact_name, 1, 2]
return layer_type(**type_args)
...
kw_args = {'arg0':0, 'arg1':True}
layer = use_factory( (fact.TEST, kwargs) )
-
class
monai.networks.layers.factories.
LayerFactory
[source]¶ Factory object for creating layers, this uses given factory functions to actually produce the types or constructing callables. These functions are referred to by name and can be added at any time.
-
add_factory_callable
(name, func)[source]¶ Add the factory function to this object under the given name.
-
get_constructor
(factory_name, *args)[source]¶ Get the constructor for the given factory name and arguments.
- Raises
ValueError – Factories must be selected by name
- Return type
Any
-
property
names
¶ Produces all factory names.
-
SkipConnection¶
-
class
monai.networks.layers.
SkipConnection
(submodule, cat_dim=1)[source]¶ Concats the forward pass input with the result from the given submodule.
Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
-
Flatten¶
-
class
monai.networks.layers.
Flatten
[source]¶ Flattens the given input in the forward pass to be [B,-1] in shape.
Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
-
GaussianFilter¶
-
class
monai.networks.layers.
GaussianFilter
(spatial_dims, sigma, truncated=4.0)[source]¶ - Parameters
spatial_dims (
int
) – number of spatial dimensions of the input image. must have shape (Batch, channels, H[, W, …]).sigma (float or sequence of floats) – std.
truncated (
float
) – spreads how many stds.
Affine Transform¶
-
class
monai.networks.layers.
AffineTransform
(spatial_size=None, normalized=False, mode=<GridSampleMode.BILINEAR: 'bilinear'>, padding_mode=<GridSamplePadMode.ZEROS: 'zeros'>, align_corners=False, reverse_indexing=True)[source]¶ Apply affine transformations with a batch of affine matrices.
When normalized=False and reverse_indexing=True, it does the commonly used resampling in the ‘pull’ direction following the
scipy.ndimage.affine_transform
convention. In this case theta is equivalent to (ndim+1, ndim+1) inputmatrix
ofscipy.ndimage.affine_transform
, operates on homogeneous coordinates. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.htmlWhen normalized=True and reverse_indexing=False, it applies theta to the normalized coordinates (coords. in the range of [-1, 1]) directly. This is often used with align_corners=False to achieve resolution-agnostic resampling, thus useful as a part of trainable modules such as the spatial transformer networks. See also: https://pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html
- Parameters
spatial_size (list or tuple of int) – output spatial shape, the full output shape will be [N, C, *spatial_size] where N and C are inferred from the src input of self.forward.
normalized (
bool
) – indicating whether the provided affine matrix theta is defined for the normalized coordinates. If normalized=False, theta will be converted to operate on normalized coordinates as pytorch affine_grid works with the normalized coordinates.mode (
Union
[GridSampleMode
,str
]) – {"bilinear"
,"nearest"
} Interpolation mode to calculate output values. Defaults to"bilinear"
. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-samplepadding_mode (
Union
[GridSamplePadMode
,str
]) – {"zeros"
,"border"
,"reflection"
} Padding mode for outside grid values. Defaults to"zeros"
. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-samplealign_corners (
bool
) – see also https://pytorch.org/docs/stable/nn.functional.html#grid-sample.reverse_indexing (
bool
) – whether to reverse the spatial indexing of image and coordinates. set to False if theta follows pytorch’s default “D, H, W” convention. set to True if theta follows scipy.ndimage default “i, j, k” convention.
-
forward
(src, theta, spatial_size=None)[source]¶ theta
must be an affine transformation matrix with shape 3x3 or Nx3x3 or Nx2x3 or 2x3 for spatial 2D transforms, 4x4 or Nx4x4 or Nx3x4 or 3x4 for spatial 3D transforms, where N is the batch size. theta will be converted into float Tensor for the computation.- Parameters
src (array_like) – image in spatial 2D or 3D (N, C, spatial_dims), where N is the batch dim, C is the number of channels.
theta (array_like) – Nx3x3, Nx2x3, 3x3, 2x3 for spatial 2D inputs, Nx4x4, Nx3x4, 3x4, 4x4 for spatial 3D inputs. When the batch dimension is omitted, theta will be repeated N times, N is the batch dim of src.
spatial_size (list or tuple of int) – output spatial shape, the full output shape will be [N, C, *spatial_size] where N and C are inferred from the src.
- Raises
TypeError – both src and theta must be torch Tensor, got {type(src).__name__}, {type(theta).__name__}.
ValueError – affine must be Nxdxd or dxd.
ValueError – affine must be Nx3x3 or Nx4x4, got: {theta.shape}.
ValueError – src must be spatially 2D or 3D.
ValueError – batch dimension of affine and image does not match, got affine: {} and image: {}.
Utilities¶
-
monai.networks.layers.convutils.
same_padding
(kernel_size, dilation=1)[source]¶ Return the padding value needed to ensure a convolution using the given kernel size produces an output of the same shape as the input for a stride of 1, otherwise ensure a shape of the input divided by the stride rounded down.
- Raises
NotImplementedError – same padding not available for k={kernel_size} and d={dilation}.
-
monai.networks.layers.convutils.
calculate_out_shape
(in_shape, kernel_size, stride, padding)[source]¶ Calculate the output tensor shape when applying a convolution to a tensor of shape inShape with kernel size kernel_size, stride value stride, and input padding value padding. All arguments can be scalars or multiple values, return value is a scalar if all inputs are scalars.
Nets¶
Densenet3D¶
-
class
monai.networks.nets.
DenseNet
(spatial_dims, in_channels, out_channels, init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), bn_size=4, dropout_prob=0.0)[source]¶ Densenet based on: “Densely Connected Convolutional Networks” https://arxiv.org/pdf/1608.06993.pdf Adapted from PyTorch Hub 2D version: https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py
- Parameters
spatial_dims (
int
) – number of spatial dimensions of the input image.in_channels (
int
) – number of the input channel.out_channels (
int
) – number of the output classes.init_features (
int
) – number of filters in the first convolution layer.growth_rate (
int
) – how many filters to add each layer (k in paper).block_config (tuple) – how many layers in each pooling block.
bn_size (
int
) – multiplicative factor for number of bottle neck layers. (i.e. bn_size * k features in the bottleneck layer)dropout_prob (
float
) – dropout rate after each dense layer.
Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Highresnet¶
-
class
monai.networks.nets.
HighResNet
(spatial_dims=3, in_channels=1, out_channels=1, norm_type=<Normalisation.BATCH: 'batch'>, acti_type=<Activation.RELU: 'relu'>, dropout_prob=None, layer_params=({'name': 'conv_0', 'n_features': 16, 'kernel_size': 3}, {'name': 'res_1', 'n_features': 16, 'kernels': (3, 3), 'repeat': 3}, {'name': 'res_2', 'n_features': 32, 'kernels': (3, 3), 'repeat': 3}, {'name': 'res_3', 'n_features': 64, 'kernels': (3, 3), 'repeat': 3}, {'name': 'conv_1', 'n_features': 80, 'kernel_size': 1}, {'name': 'conv_2', 'kernel_size': 1}))[source]¶ Reimplementation of highres3dnet based on Li et al., “On the compactness, efficiency, and representation of 3D convolutional networks: Brain parcellation as a pretext task”, IPMI ‘17
Adapted from: https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/network/highres3dnet.py https://github.com/fepegar/highresnet
- Parameters
spatial_dims (
int
) – number of spatial dimensions of the input image.in_channels (
int
) – number of input channels.out_channels (
int
) – number of output channels.norm_type (
Union
[Normalisation
,str
]) – {"batch"
,"instance"
} Feature normalisation with batchnorm or instancenorm. Defaults to"batch"
.acti_type (
Union
[Activation
,str
]) – {"relu"
,"prelu"
,"relu6"
} Non-linear activation using ReLU or PReLU. Defaults to"relu"
.dropout_prob (
Optional
[float
]) – probability of the feature map to be zeroed (only applies to the penultimate conv layer).layer_params (a list of dictionaries) – specifying key parameters of each layer/block.
Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
-
class
monai.networks.nets.
HighResBlock
(spatial_dims, in_channels, out_channels, kernels=(3, 3), dilation=1, norm_type=<Normalisation.INSTANCE: 'instance'>, acti_type=<Activation.RELU: 'relu'>, channel_matching=<ChannelMatching.PAD: 'pad'>)[source]¶ - Parameters
kernels (list of int) – each integer k in kernels corresponds to a convolution layer with kernel size k.
norm_type (
Union
[Normalisation
,str
]) – {"batch"
,"instance"
} Feature normalisation with batchnorm or instancenorm. Defaults to"instance"
.acti_type (
Union
[Activation
,str
]) – {"relu"
,"prelu"
,"relu6"
} Non-linear activation using ReLU or PReLU. Defaults to"relu"
.channel_matching (
Union
[ChannelMatching
,str
]) –{
"pad"
,"project"
} Specifies handling residual branch and conv branch channel mismatches. Defaults to"pad"
."pad"
: with zero padding."project"
: with a trainable conv with kernel size.
- Raises
ValueError – channel matching must be pad or project, got {channel_matching}.
ValueError – in_channels > out_channels is incompatible with channel_matching=pad.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Unet¶
-
class
monai.networks.nets.
UNet
(dimensions, in_channels, out_channels, channels, strides, kernel_size=3, up_kernel_size=3, num_res_units=0, act='PRELU', norm='INSTANCE', dropout=0)[source]¶ Initializes internal Module state, shared by both nn.Module and ScriptModule.
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
-
-
monai.networks.nets.
Unet
¶ alias of
monai.networks.nets.unet.UNet
-
monai.networks.nets.
unet
¶ alias of
monai.networks.nets.unet.UNet
Generator¶
-
class
monai.networks.nets.
Generator
(latent_shape, start_shape, channels, strides, kernel_size=3, num_res_units=2, act='PRELU', norm='INSTANCE', dropout=None, bias=True)[source]¶ Defines a simple generator network accepting a latent vector and through a sequence of convolution layers constructs an output tensor of greater size and high dimensionality. The method _get_layer is used to create each of these layers, override this method to define layers beyond the default Convolution or ResidualUnit layers.
For example, a generator accepting a latent vector if shape (42,24) and producing an output volume of shape (1,64,64) can be constructed as:
gen = Generator((42, 24), (64, 8, 8), (32, 16, 1), (2, 2, 2))
Construct the generator network with the number of layers defined by channels and strides. In the forward pass a nn.Linear layer relates the input latent vector to a tensor of dimensions start_shape, this is then fed forward through the sequence of convolutional layers. The number of layers is defined by the length of channels and strides which must match, each layer having the number of output channels given in channels and an upsample factor given in strides (ie. a transpose convolution with that stride size).
- Parameters
latent_shape – tuple of integers stating the dimension of the input latent vector (minus batch dimension)
start_shape – tuple of integers stating the dimension of the tensor to pass to convolution subnetwork
channels – tuple of integers stating the output channels of each convolutional layer
strides – tuple of integers stating the stride (upscale factor) of each convolutional layer
kernel_size – integer or tuple of integers stating size of convolutional kernels
num_res_units – integer stating number of convolutions in residual units, 0 means no residual units
act – name or type defining activation layers
norm – name or type defining normalization layers
dropout – optional float value in range [0, 1] stating dropout probability for layers, None for no dropout
bias – boolean stating if convolution layers should have a bias component
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Regressor¶
-
class
monai.networks.nets.
Regressor
(in_shape, out_shape, channels, strides, kernel_size=3, num_res_units=2, act='PRELU', norm='INSTANCE', dropout=None, bias=True)[source]¶ This defines a network for relating large-sized input tensors to small output tensors, ie. regressing large values to a prediction. An output of a single dimension can be used as value regression or multi-label classification prediction, an output of a single value can be used as a discriminator or critic prediction.
Construct the regressor network with the number of layers defined by channels and strides. Inputs are first passed through the convolutional layers in the forward pass, the output from this is then pass through a fully connected layer to relate them to the final output tensor.
- Parameters
in_shape – tuple of integers stating the dimension of the input tensor (minus batch dimension)
out_shape – tuple of integers stating the dimension of the final output tensor
channels – tuple of integers stating the output channels of each convolutional layer
strides – tuple of integers stating the stride (downscale factor) of each convolutional layer
kernel_size – integer or tuple of integers stating size of convolutional kernels
num_res_units – integer stating number of convolutions in residual units, 0 means no residual units
act – name or type defining activation layers
norm – name or type defining normalization layers
dropout – optional float value in range [0, 1] stating dropout probability for layers, None for no dropout
bias – boolean stating if convolution layers should have a bias component
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Classifier¶
-
class
monai.networks.nets.
Classifier
(in_shape, classes, channels, strides, kernel_size=3, num_res_units=2, act='PRELU', norm='INSTANCE', dropout=None, bias=True, last_act=None)[source]¶ Defines a classification network from Regressor by specifying the output shape as a single dimensional tensor with size equal to the number of classes to predict. The final activation function can also be specified, eg. softmax or sigmoid.
Construct the regressor network with the number of layers defined by channels and strides. Inputs are first passed through the convolutional layers in the forward pass, the output from this is then pass through a fully connected layer to relate them to the final output tensor.
- Parameters
in_shape – tuple of integers stating the dimension of the input tensor (minus batch dimension)
out_shape – tuple of integers stating the dimension of the final output tensor
channels – tuple of integers stating the output channels of each convolutional layer
strides – tuple of integers stating the stride (downscale factor) of each convolutional layer
kernel_size – integer or tuple of integers stating size of convolutional kernels
num_res_units – integer stating number of convolutions in residual units, 0 means no residual units
act – name or type defining activation layers
norm – name or type defining normalization layers
dropout – optional float value in range [0, 1] stating dropout probability for layers, None for no dropout
bias – boolean stating if convolution layers should have a bias component
Discriminator¶
-
class
monai.networks.nets.
Discriminator
(in_shape, channels, strides, kernel_size=3, num_res_units=2, act='PRELU', norm='INSTANCE', dropout=0.25, bias=True, last_act='SIGMOID')[source]¶ Defines a discriminator network from Classifier with a single output value and sigmoid activation by default. This is meant for use with GANs or other applications requiring a generic discriminator network.
Construct the regressor network with the number of layers defined by channels and strides. Inputs are first passed through the convolutional layers in the forward pass, the output from this is then pass through a fully connected layer to relate them to the final output tensor.
- Parameters
in_shape – tuple of integers stating the dimension of the input tensor (minus batch dimension)
out_shape – tuple of integers stating the dimension of the final output tensor
channels – tuple of integers stating the output channels of each convolutional layer
strides – tuple of integers stating the stride (downscale factor) of each convolutional layer
kernel_size – integer or tuple of integers stating size of convolutional kernels
num_res_units – integer stating number of convolutions in residual units, 0 means no residual units
act – name or type defining activation layers
norm – name or type defining normalization layers
dropout – optional float value in range [0, 1] stating dropout probability for layers, None for no dropout
bias – boolean stating if convolution layers should have a bias component
Critic¶
-
class
monai.networks.nets.
Critic
(in_shape, channels, strides, kernel_size=3, num_res_units=2, act='PRELU', norm='INSTANCE', dropout=0.25, bias=True)[source]¶ Defines a critic network from Classifier with a single output value and no final activation. The final layer is nn.Flatten instead of nn.Linear, the final result is computed as the mean over the first dimension. This is meant to be used with Wassertein GANs.
Construct the regressor network with the number of layers defined by channels and strides. Inputs are first passed through the convolutional layers in the forward pass, the output from this is then pass through a fully connected layer to relate them to the final output tensor.
- Parameters
in_shape – tuple of integers stating the dimension of the input tensor (minus batch dimension)
out_shape – tuple of integers stating the dimension of the final output tensor
channels – tuple of integers stating the output channels of each convolutional layer
strides – tuple of integers stating the stride (downscale factor) of each convolutional layer
kernel_size – integer or tuple of integers stating size of convolutional kernels
num_res_units – integer stating number of convolutions in residual units, 0 means no residual units
act – name or type defining activation layers
norm – name or type defining normalization layers
dropout – optional float value in range [0, 1] stating dropout probability for layers, None for no dropout
bias – boolean stating if convolution layers should have a bias component
-
forward
(x)[source]¶ Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Utilities¶
Utilities and types for defining networks, these depend on PyTorch.
-
monai.networks.utils.
normal_init
(m, std=0.02, normal_func=<function normal_>)[source]¶ Initialize the weight and bias tensors of m’ and its submodules to values from a normal distribution with a stddev of `std’. Weight tensors of convolution and linear modules are initialized with a mean of 0, batch norm modules with a mean of 1. The callable `normal_func’, used to assign values, should have the same arguments as its default normal_(). This can be used with `nn.Module.apply to visit submodules of a network.
-
monai.networks.utils.
normalize_transform
(shape, device=None, dtype=None, align_corners=False)[source]¶ Compute an affine matrix according to the input shape. The transform normalizes the homogeneous image coordinates to the range of [-1, 1].
- Parameters
shape (sequence of int) – input spatial shape
device (torch device) – device on which the returned affine will be allocated.
dtype (torch dtype) – data type of the returned affine
align_corners (
bool
) – if True, consider -1 and 1 to refer to the centers of the corner pixels rather than the image corners. See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample
-
monai.networks.utils.
one_hot
(labels, num_classes, dtype=torch.float32)[source]¶ For a tensor labels of dimensions B1[spatial_dims], return a tensor of dimensions BN[spatial_dims] for num_classes N number of classes.
Example
For every value v = labels[b,1,h,w], the value in the result at [b,v,h,w] will be 1 and all others 0. Note that this will include the background label, thus a binary mask should be treated as having 2 classes.
-
monai.networks.utils.
predict_segmentation
(logits, mutually_exclusive=False, threshold=0.0)[source]¶ Given the logits from a network, computing the segmentation by thresholding all values above 0 if multi-labels task, computing the argmax along the channel axis if multi-classes task, logits has shape BCHW[D].
- Parameters
logits (Tensor) – raw data of model output.
mutually_exclusive (
bool
) – if True, logits will be converted into a binary matrix using a combination of argmax, which is suitable for multi-classes task. Defaults to False.threshold (
float
) – thresholding the prediction values if multi-labels task.
-
monai.networks.utils.
to_norm_affine
(affine, src_size, dst_size, align_corners=False)[source]¶ Given
affine
defined for coordinates in the pixel space, compute the corresponding affine for the normalized coordinates.- Parameters
affine (torch Tensor) – Nxdxd batched square matrix
src_size (sequence of int) – source image spatial shape
dst_size (sequence of int) – target image spatial shape
align_corners (
bool
) – if True, consider -1 and 1 to refer to the centers of the corner pixels rather than the image corners. See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample
- Raises
ValueError – affine must be a tensor
ValueError – affine must be Nxdxd, got {tuple(affine.shape)}
ValueError – affine suggests a {sr}-D transform, but the sizes are src_size={src_size}, dst_size={dst_size}