neurite.nn.modules
Modules are simple operations containing learnable parameters. The modules module contains general
nD building blocks for neural networks.
Citation
If you use this code, please cite the following, and read function docs for further info/citations Dalca AV, Guttag J, Sabuncu MR Anatomical Priors in Convolutional Networks for Unsupervised Biomedical Segmentation, CVPR 2018. https://arxiv.org/abs/1903.03148
License
Copyright 2020 Adrian V. Dalca
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Seee License for the specific language governing permissions and limitations under the License.
Activation
Activation(activation_type: Union[str, Type[Module], None] = None, inplace: bool = True, negative_slope: float = 0.01, alpha: float = 1.0)
Bases: Module
Dynamically construct an activation/nonlinearity based on the specified type.
Initialize Activation.
| PARAMETER | DESCRIPTION |
|---|---|
activation_type
|
Type of activation function. Supported values: 'relu', 'leaky_relu', 'elu'.
TYPE:
|
inplace
|
Whether to perform the operation in-place. Default is True.
TYPE:
|
negative_slope
|
Negative slope for 'leaky_relu'. Default is 0.01.
TYPE:
|
alpha
|
Alpha value for 'elu'. Default is 1.0.
TYPE:
|
Source code in neurite/nn/modules.py
CategoricalCrossentropy
ContextCrossConv
ContextCrossConv(ndim: int, in_channels: Tuple[int, int], out_channels: int, kernel_size: int = 3, stride: int = 1, padding: int = 1, padding_mode: Literal['zeros', 'replicate', 'reflect'] = 'zeros', dilation: int = 1, groups: int = 1, bias: bool = True, normalization: Union[str, Module, None] = None, activation: Union[str, Module, None] = None, order: str = 'cna')
Bases: Module
nD Convolutional layer that performs cross convolutions to interact a query image with a context set (examples) defining a task.
Examples:
2D cross convolution on CPU
>>> # Create random 2D inputs: 3 sets of 2 query images and 6 context pairs.
>>> query_image = torch.randn(3, 2, 1, 64, 64)
>>> context_images = torch.randn(3, 6, 1, 64, 64)
>>> context_segmentations = ne.samplers.RandInt()((3, 6, 1, 64, 64))
>>> # Concat along the channel dimension
>>> context = torch.cat([context_images, context_segmentations], dim=1)
>>> # Define the number of query image channels and context set channels seperately:
>>> in_channels = (1, 2)
>>> # Define cross convolution block
>>> cross_conv_block = ContextCrossConv(
... ndim=2, in_channels=in_channels, out_channels=16, kernel_size=3, padding=1
... )
>>> # Forward pass of cross convolutiom block, returning new query and context representations
>>> new_query_image, new_context_image = cross_conv_block(query_image, context_image)
>>> # Expected output shapes: (3, 2, 16, 64, 64), (3, 6, 16, 64, 64)
>>> print(new_query_image.shape, new_context_image.shape)
torch.Size([3, 2, 16, 64, 64]) torch.Size([3, 6, 16, 64, 64])
3D cross convolution on GPU
>>> # Create random 3D inputs: 1 set of 1 query image and 9 context pairs.
>>> query_image = torch.randn(1, 1, 1, 128, 128, 128)
>>> context_images = torch.randn(1, 9, 1, 128, 128, 128)
>>> context_segmentations = ne.samplers.RandInt()((1, 9, 1, 128, 128, 128))
>>> # Concat along the channel dimension
>>> context = torch.cat([context_images, context_segmentations], dim=1)
>>> # Define the number of query image channels and context set channels seperately:
>>> in_channels = (1, 2)
>>> # Define cross convolution block
>>> cross_conv_block = ContextCrossConv(
... ndim=3, in_channels=in_channels, out_channels=32, kernel_size=3, padding=1
... )
>>> # Forward pass of cross convolutiom block, returning new query and context representations
>>> new_query_image, new_context_image = cross_conv_block(query_image, context_image)
>>> # Expected output shapes: (1, 1, 32, 128, 128, 128), (1, 9, 32, 128, 128, 128)
>>> print(new_query_image.shape, new_context_image.shape)
torch.Size([3, 1, 32, 128, 128, 128]) torch.Size([3, 9, 32, 128, 128, 128])
Notes
Modified from the original description on GitHub:
The pairwise convolution is computed by first forming a Cartesian product of the slices in x1
and x2. For example, if x1 has Sx1 slices and x2 has Sx2 slices, then the concatenated
tensor has shape (B, Sx1, Sx2, Cx1 + Cx2, ...). This tensor is reshaped to combine the first
three dimensions so that the standard nn.Conv*d can be applied. Finally, the output is reshaped
back to separate the batch and slice indices.
References
J. G. Ortiz et al., "UniverSeg: Universal Medical Image Segmentation," GitHub repository, 2023. Available: https://github.com/JJGO/UniverSeg
Initialize the ContextCrossConv module.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
Dimensionality of the convolution (1 for Conv1d, 2 for Conv2d, 3 for Conv3d).
TYPE:
|
in_channels
|
Number of channels in
TYPE:
|
out_channels
|
Number of output channels for the cross convolution.
TYPE:
|
kernel_size
|
Size of the convolving kernel. Default is 3.
TYPE:
|
stride
|
Stride of the convolution. Default is 1.
TYPE:
|
padding
|
Padding added to all sides of the input. Default is 1.
TYPE:
|
dilation
|
Spacing between kernel elements. Every
TYPE:
|
groups
|
Number of blocked connections from input to output channels. Default is 1.
TYPE:
|
bias
|
If True, a learnable bias is added to the output. Default is True.
TYPE:
|
normalization
|
Defines the normalization layer. Can be one of:
- A string: Supported options are 'batch', 'instance', 'layer', or 'group'.
- A
TYPE:
|
activation
|
Defines the activation layer. Can be one of:
- A string: Supported options are 'relu', 'leaky_relu', or 'elu'.
- A
TYPE:
|
order
|
The order of operations in the block. Default is 'cna'
(normalization -> convolution -> activation).
Each character in the string represents one of the following:
-
TYPE:
|
Source code in neurite/nn/modules.py
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
ConvBlock
ConvBlock(ndim: int, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, padding: int = 1, padding_mode: Literal['zeros', 'replicate', 'reflect'] = 'zeros', dilation: int = 1, groups: int = 1, bias: bool = True, normalization: Union[str, Module, None] = None, activation: Union[List, str, Module, None] = None, order: str = 'cna')
Bases: Sequential
Convolutional block comprising a conv, and optionally, an activation and/or normalization.
The default sequence of operations in this block is:
- Convolution: Apply an nD convolution over the input.
- Normalization: Normalize the output of the convolution to stabilize and accelerate training.
- Activation Function: Introduce non-linearity to the model.
| ATTRIBUTE | DESCRIPTION |
|---|---|
conv |
The convolutional layer.
TYPE:
|
batch_norm |
The batch normalization layer.
TYPE:
|
activation |
The activation function.
TYPE:
|
Examples:
>>> import torch.nn as nn
>>> conv_block = ConvBlock(
in_channels=64,
out_channels=128,
kernel_size=3,
stride=1,
padding=1,
activation=nn.ReLU()
)
>>> input_tensor = torch.randn(16, 64, 32, 32)
>>> output = conv_block(input_tensor)
>>> print(output.shape)
torch.Size([16, 128, 32, 32])
Initialize ConvBlock.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
Dimensionality of the convolution (1 for Conv1d, 2 for Conv2d, 3 for Conv3d).
TYPE:
|
in_channels
|
Number of input channels.
TYPE:
|
out_channels
|
Number of output channels.
TYPE:
|
kernel_size
|
Size of the convolving kernel. Default is 3.
TYPE:
|
stride
|
Stride of the convolution. Default is 1.
TYPE:
|
padding
|
Padding added to all sides of the input. Default is 1.
TYPE:
|
dilation
|
Spacing between kernel elements. Every
TYPE:
|
groups
|
Number of blocked connections from input to output channels. Default is 1.
TYPE:
|
bias
|
If True, a learnable bias is added to the output. Default is True.
TYPE:
|
normalization
|
Defines the normalization layer. Can be one of:
- A string: Supported options are 'batch', 'instance', 'layer', or 'group'.
- A
TYPE:
|
activation
|
Defines the activation layer. Can be one of:
- A string: Supported options are 'relu', 'leaky_relu', or 'elu'.
- A list: A list containing any of these optinons. Must have the same number of elements
as the number of activations specified in
TYPE:
|
order
|
The order of operations in the block. Default is 'cna'
(normalization -> convolution -> activation).
Each character in the string represents one of the following:
-
TYPE:
|
Examples:
Basic usage with default options
>>> conv_block = ConvBlock(
ndim=2,
in_channels=16,
out_channels=32,
normalization="batch",
activation="relu"
)
>>> input_tensor = torch.randn(1, 16, 64, 64)
>>> output_tensor = conv_block(input_tensor)
>>> print(output_tensor.shape)
torch.Size([1, 32, 64, 64])
Use pre-initialized Normalization and Activation modules
>>> norm_layer = nn.BatchNorm2d(32)
>>> activation_layer = nn.ReLU()
>>> conv_block = ConvBlock(
ndim=2,
in_channels=16,
out_channels=32,
normalization=norm_layer,
activation=activation_layer
)
>>> output_tensor = conv_block(input_tensor)
>>> print(output_tensor.shape)
torch.Size([1, 32, 64, 64])
Initialize ConvBlock without normalizations nor activations
>>> conv_block = ConvBlock(
ndim=2,
in_channels=16,
out_channels=32,
normalization=None,
activation=None
)
>>> output_tensor = conv_block(input_tensor)
>>> print(output_tensor.shape)
torch.Size([1, 32, 64, 64])
Source code in neurite/nn/modules.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
Dice
Dice(smooth_numerator: float = 1e-12, smooth_denominator: float = 1e-12, reduction: str = 'mean', reduction_dim: int = (0, 1), keepdims: bool = True)
Bases: Module
Compute the Dice score between two segmentation tensors (e.g. ground truth, predictions, etc...)
Examples:
Example 1: Computing the hard dice score with binary seg maps
>>> # Instantiate the dice score module
>>> dice_module = ne.losses.Dice()
>>> # Randomly sample binary tensors with 3 batches and 4 channels
>>> seg1 = ne.samplers.RandInt(0, 1)((3, 4, 128, 128))
>>> seg2 = ne.samplers.RandInt(0, 1)((3, 4, 128, 128))
>>> # Compute the dice score and return
>>> dice_module(seg1, seg2)
tensor([[0.5003]])
Example 2: Computing the soft dice score with continuious seg maps and no reduction
>>> dice_module = Dice(reduction=None)
>>> # Randomly sample continuious "logits"
>>> seg1 = ne.samplers.Normal(0, 1)((3, 4, 128, 128))
>>> seg2 = ne.samplers.Normal(0, 1)((3, 4, 128, 128))
>>> # Activation functions
>>> seg1 = ne.utils.logistic(seg1)
>>> seg2 = ne.utils.logistic(seg2)
>>> # Compute the dice score and return
>>> dice_module(seg1, seg2)
tensor([[0.4982, 0.5022, 0.4984, 0.5024],
[0.5016, 0.5035, 0.5021, 0.5001],
[0.5001, 0.4998, 0.4990, 0.4996]])
Initialize Dice.
| PARAMETER | DESCRIPTION |
|---|---|
smooth_numerator
|
Smoothing constant added to the numerator.
TYPE:
|
smooth_denominator
|
Smoothing constant added to the denominator.
TYPE:
|
reduction
|
The type of reduction to apply. Supported values for multidimensional reductions are: 'mean', 'sum', 'median', 'amax', 'amin', 'std', 'var', 'var_mean'; for single-dimension reductions: 'argmin', 'argmax', and all multidimensionals. Default is 'mean'.
TYPE:
|
reduction_dim
|
Dimension(s) over which to apply the reduction. For multidimensional reductions, pass a tuple of dimensions; for single-dimension reductions, pass an integer. Default is (0, 1)
TYPE:
|
keepdims
|
Whether to retain reduced dimensions as a singleton. Default is True.
TYPE:
|
Source code in neurite/nn/modules.py
DownsampleConvBlock
DownsampleConvBlock(ndim: int, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, padding: int = 1, padding_mode: Literal['zeros', 'replicate', 'reflect'] = 'zeros', normalization: Union[str, Module, None] = None, activation: Union[str, Module, None] = 'relu', pool_mode: str = 'max', pool_kernel_size: int = 2, order='nca', return_residual: bool = False)
Bases: Module
Apply ConvBlock followed by Pool to extract features and reduce spatial shape.
| ATTRIBUTE | DESCRIPTION |
|---|---|
conv_block |
The convolutional block applying a series of convolutions, normalization, and activation.
TYPE:
|
pool |
The pooling layer to downsample the feature maps.
TYPE:
|
the
Initialize DownsampleConvBlock.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
Dimensionality of the convolution (1 for Conv1d, 2 for Conv2d, 3 for Conv3d).
TYPE:
|
in_channels
|
Number of input channels.
TYPE:
|
out_channels
|
Number of output channels.
TYPE:
|
kernel_size
|
Size of the convolving kernel. Default is 3.
TYPE:
|
stride
|
Stride of the convolution. Default is 1.
TYPE:
|
padding
|
Padding added to all sides of the input. Default is 1.
TYPE:
|
normalization
|
Normalization type. Default is 'batch'.
TYPE:
|
activation
|
Activation type. Default is 'relu'.
TYPE:
|
pool_mode
|
Pooling mode ('max' or 'avg'). Default is 'max'.
TYPE:
|
pool_kernel_size
|
Kernel size for pooling. Default is 2.
TYPE:
|
order
|
The order of operations in the block. Default is 'nca' (normalization -> convolution ->
activation). Each character in the string can be specified an arbitrary number of times
in any order. Each character in the string represents one of the following:
-
TYPE:
|
return_residual
|
Optionally return a residual (skip connection) from the output of the forward pass.
TYPE:
|
Source code in neurite/nn/modules.py
GaussianBlur
Bases: Module
Apply a {1D, 2D, 3D} gaussian blur to the input tensor by convolving it with a Gaussian kernel.
Initialize GaussianBlur.
| PARAMETER | DESCRIPTION |
|---|---|
kernel_size
|
Size of the Gaussian kernel, default is 3.
TYPE:
|
sigma
|
Standard deviation of the Gaussian kernel, default is 1.
TYPE:
|
Source code in neurite/nn/modules.py
MSE
MeanSquaredErrorProb
Pool
Bases: Module
nD Pooling layer.
| ATTRIBUTE | DESCRIPTION |
|---|---|
pool |
The pooling operation to apply. It is one of
TYPE:
|
Initialize Pool.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
The spatial dimensionality of the pooling operation. Must be 1, 2, or 3.
TYPE:
|
pool_mode
|
The pooling mode to use. Options are 'max' for max pooling, 'avg' for average pooling, and 'lp' for LP pooling. Default is 'max'.
TYPE:
|
kernel_size
|
The size of the pooling kernel. Default is 2.
TYPE:
|
Source code in neurite/nn/modules.py
RandomClearLabel
RandomClearLabel(prob: Union[float, int, Sampler] = 0.5, exclude_zero: bool = True, seed: int = None)
Bases: Module
Erase regions of an image from randomly selected regions in a label map.
Identify unique labels within the label_tensor and, based on a specified probability,
designate regions of the input_tensor to be erased (set to zero).
Examples:
Clearing labels with a fixed probability
>>> clear_label = RandomClearLabel(prob=0.75)
>>> input_tensor = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> label_tensor = torch.tensor([1, 2, 3, 4, 5, 6])
>>> cleared_tensor = clear_label(input_tensor, label_tensor)
>>> print(cleared_tensor)
tensor([0.0000, 0.2000, 0.0000, 0.0000, 0.0000, 0.0000])
Reproducibility with a seed
>>> clear_label1 = RandomClearLabel(seed=32)
>>> clear_label2 = RandomClearLabel(seed=32)
>>> input_tensor = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> label_tensor = torch.tensor([1, 2, 3, 4, 5, 6])
>>> cleared_tensor1 = clear_label1(input_tensor, label_tensor)
>>> cleared_tensor2 = clear_label2(input_tensor, label_tensor)
>>> print(torch.equal(cleared_tensor1, cleared_tensor2))
True
Initialize RandomClearLabel.
| PARAMETER | DESCRIPTION |
|---|---|
prob
|
Probability of any label/region being selected for erasure as determined by iid Bernoulli trials, by default 0.5.
TYPE:
|
exclude_zero
|
Optionally exclude zero (uaually background) from the list of potential regions to clear (never clear zero labels), by default True.
TYPE:
|
seed
|
A random seed or sampler to control the randomness of label clearing operations. If provided, it ensures reproducibility of the clearing process. By default, None.
TYPE:
|
Source code in neurite/nn/modules.py
RandomClip
RandomClip(clip_min: Union[float, int, Sampler] = 0, clip_max: Union[float, int, Sampler] = 1, clip_prob: Union[float, int, Sampler] = 0.5, seed: Union[int, Sampler] = None)
Bases: Module
Randomly clip the intensities of the input tensor.
Initialize RandomClip with specified clipping bounds and sampling probability.
| PARAMETER | DESCRIPTION |
|---|---|
clip_min
|
The lower bound for clipping. Elements less than
TYPE:
|
clip_max
|
The upper bound for clipping. Elements greater than
TYPE:
|
clip_prob
|
Probability of applying this operation. Defaults to 0.5.
TYPE:
|
seed
|
Seed for random number generation to ensure reproducibility. Defaults to None.
TYPE:
|
Examples:
Initialize RandomClip and apply it deterministically to a tensor:
>>> random_clip = RandomClip(clip_min=0.1, clip_max=0.9, clip_prob=0.5)
>>> input_tensor = torch.randn(3, 3)
>>> output_tensor = random_clip(input_tensor)
>>> print(output_tensor)
Clip by sampling min/max bounds from a custom distribution:
>>> from my_samplers import UniformSampler
>>> random_clip = RandomClip(
clip_min=UniformSampler(0, 0.5),
clip_max=UniformSampler(0.5, 1.0)
)
>>> output_tensor = random_clip(input_tensor)
>>> print(output_tensor)
Source code in neurite/nn/modules.py
RandomCrop
RandomCrop(crop_proportion: Union[Sampler, float] = 0.5, prob: Union[Sampler, float] = 1, forbidden_dims: Union[Tuple, List] = (0, 1), seed: Union[int, Sampler] = None)
Bases: Module
Randomly crop the input tensor along allowed dimensions.
This module randomly selects a subset of the allowed dimensions (excluding forbidden_dims)
and crops each independently by a proportion that is randomly drawn from a distribution. The
proportion to crop can either be fixed or sampled from a specified distribution. Each allowed
dimension has a probability prob of being cropped based on the results of independent
Bernoulli trials.
Initialize the RandomCrop module.
| PARAMETER | DESCRIPTION |
|---|---|
crop_proportion
|
The proportion that is randomly cropped from any allowed dimension. By default 0.5
- If a
TYPE:
|
prob
|
The probability of cropping each allowed dimension. By default 1.0
- If a
TYPE:
|
forbidden_dims
|
Dimensions that should never be cropped. By defult
TYPE:
|
seed
|
A random seed or sampler to control the randomness of cropping operations. If provided,
it ensures reproducibility of the cropping. Defaults to
TYPE:
|
Source code in neurite/nn/modules.py
RandomGamma
RandomGamma(gamma: Union[float, int, Sampler] = 1.0, prob: Union[float, int, Sampler] = 1.0, seed: Union[int, Sampler] = None)
Bases: Module
Apply a randomized or deterministic nonlinear gamma scaling operation.
Adjust the contrast of the input tensor by applying a non-linear scaling operation.
Each element in the tensor is raised to the power of gamma, which is a quantity sampled from
a distribution.
Initialize RandomGamma.
| PARAMETER | DESCRIPTION |
|---|---|
gamma
|
The gamma value to apply for the scaling operation.
- If a
TYPE:
|
prob
|
The probability of applying the gamma operation.
- If a
TYPE:
|
seed
|
A random seed or sampler to control the randomness of the gamma scaling operation. If
provided, it ensures reproducibility of the operation. Defaults to
TYPE:
|
Examples:
Fixed gamma scaling operation
>>> gamma_module = RandomGamma(gamma=2.0, prob=1.0)
>>> tensor = torch.tensor([0.25, 0.5, 0.75])
>>> gamma_tensor = gamma_module(tensor)
>>> print(gamma_tensor)
tensor([0.0625, 0.2500, 0.5625])
Scaling with gamma ~LogNormal(0, 1)
>>> gamma_sampler = LogNormal(0.5, 1.5)
>>> gamma_module = RandomGamma(gamma=gamma_sampler, prob=0.8)
>>> tensor = torch.tensor([0.25, 0.5, 0.75])
>>> gamma_tensor = gamma_module(tensor)
>>> print(gamma_tensor)
tensor([0.1768, 0.5000, 0.8367])
Applying gamma operation with reproducibility
>>> gamma_module1 = RandomGamma(gamma=2.0, prob=1.0, seed=42)
>>> gamma_module2 = RandomGamma(gamma=2.0, prob=1.0, seed=42)
>>> tensor = torch.tensor([0.25, 0.5, 0.75])
>>> gamma_tensor1 = gamma_module1(tensor)
>>> gamma_tensor2 = gamma_module2(tensor)
>>> print(torch.equal(gamma_tensor1, gamma_tensor2))
True
Source code in neurite/nn/modules.py
RandomIntensityLookup
Bases: Module
Randomly augment the contrast of a single-channel tensor.
Compute a smoothly varying lookup table to map the original single-channel tensor (usually a greyscale image) to a tensor with a new contrast.
Initialize the RandomIntensityLookup module.
Source code in neurite/nn/modules.py
Resample
Resample(resample_dimension: Union[int, List[int]] = None, downsample_stride: Union[int, List[int]] = 2, upsample_scale_factor: Union[int, List[int]] = 2, mode: Literal['linear', 'nearest', 'bicubic', 'area', 'nearest-exact'] = 'linear', shape: tuple = None)
Bases: Module
Spatially {subsample, resample} the input tensor.
This module resamples the input tensor by a factor of stride along the specified spatial
dimension(s) by interleaving dropouts (keeping every stride'th element), then upsamples to
restore it to its original dimensions.
Initialize Resample.
| PARAMETER | DESCRIPTION |
|---|---|
resample_dimension
|
The dimension(s) that should be resampled. If None, all dimensions are resampled. Default is None. dimensions.
TYPE:
|
downsample_stride
|
Factor by which to subsample. Default is 2.
TYPE:
|
upsample_scale_factor
|
Factor by which to upsample. Default is 2.
TYPE:
|
mode
|
Interpolation mode for upsampling. Options include 'nearest', 'linear', 'bicubic', 'area', and 'nearest-exact'. Default is 'linear'.
TYPE:
|
shape
|
Spatial dimensions (without batch or channel dims) to upsample the subsampled tensor into.
TYPE:
|
Examples:
Subsample with custom stride
>>> # Make a 2D tensor ~N(0, 1) with batch and channel dims
>>> input_tensor = torch.randn(1, 1, 128, 128)
>>> # Downsample 2x in 1st dim and 4x in second dim. Upsample the same way
>>> resampled_tensor = Resample(
... downsample_stride=(2, 4),
... upsample_scale_factor=(2, 4)
... )(input_tensor)
>>> # Ensure spatial dimensions are the same
>>> print(resampled_tensor.shape)
torch.Size([1, 1, 128, 128])
Upsample with custom stride and trilinear interpolation
>>> # Make a 3D tensor ~N(0, 1) with batch and channel dims
>>> input_tensor = torch.randn(1, 1, 32, 32, 32)
>>> # Downsample 2x then upsample 6x
>>> resampled_tensor = Resample(
... downsample_stride=2,
... upsample_scale_factor=6,
... mode='trilinear'
... )(input_tensor)
>>> # Ensure dimensions are (1, 1, 96, 96, 96)
>>> print(resampled_tensor.shape)
torch.Size([1, 1, 96, 96, 96])
Source code in neurite/nn/modules.py
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 | |
RescaleValues
Bases: Module
Scale each element of the input tensor by a multiplicative factor.
Initialize the RescaleValues module.
| PARAMETER | DESCRIPTION |
|---|---|
scale_factor
|
Factor (or sampler) by which to rescale the values of the input tensor.
TYPE:
|
Source code in neurite/nn/modules.py
Resize
Resize(size: Optional[Union[int, Tuple[int, int]]] = None, scale_factor: Optional[Union[float, Tuple[float, float]]] = None, mode: Literal['linear', 'nearest', 'bicubic', 'area', 'nearest-exact'] = 'linear', align_corners: Optional[bool] = None, recompute_scale_factor: Optional[bool] = None, antialias: bool = False)
Bases: Module
Resize the input tensor.
Initialize the Resize module.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
The desired output size. If None, uses
TYPE:
|
scale_factor
|
Scaling factor for resizing. If None, uses
TYPE:
|
mode
|
Interpolation mode for upsampling. Options include 'nearest', 'linear', 'bicubic', 'area', and 'nearest-exact'. Default is 'linear'.
TYPE:
|
align_corners
|
Alignment for "linear", "bilinear", or "trilinear" modes.
TYPE:
|
recompute_scale_factor
|
If True, recomputes the scale factor for interpolation.
TYPE:
|
antialias
|
Applies anti-aliasing if
TYPE:
|
Examples:
Resize with fixed scale_factor
>>> resize_module = Resize(scale_factor=2)
>>> resized_tensor = resize_module(input_tensor)
>>> print(resized_tensor.shape)
torch.Size([1, 1, 64, 64, 64])
Resize with a sampled scale_factor
>>> resize_module = Resize(scale_factor=Uniform(0.5, 4))
>>> resized_tensor = resize_module(input_tensor)
>>> print(resized_tensor)
torch.Size([1, 1, 74, 74, 74])
Resize to a specific shape
>>> resize_module = Resize(size=(96, 96, 96))
>>> resized_tensor = resize_module(input_tensor)
>>> print(resized_tensor)
torch.Size([1, 1, 96, 96, 96])
Notes
- This class assumes the input tensor has batch and channel dimensions.
- It is not possible to define
sizeandscale_factorsimultaneously. Only one can be defined for a given instatntiation ofResize. - When defining
sizedo not include batch or channel dimensions, only spatial dims.
Source code in neurite/nn/modules.py
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 | |
SampleImageFromLabels
SampleImageFromLabels(mean_sampler: Sampler = ne.samplers.Uniform(0, 1), noise_sampler: Sampler = ne.samplers.Normal, noise_variance: Union[float, int, Sampler] = 0.25)
Bases: Module
Generate an image from a label map by sampling a random intensity for each label.
Identify all unique integer labels in label_tensor and assigns each a mean intensity in the
corresponding output image (sampled_image). The mean intensity serves as the mean for a noise
distribution modeled by noise_sampler. The variance of the noise model may be a fixed quantity
or sampled from another distribution defined by noise_variance.
Initialize SampleImageFromLabels.
| PARAMETER | DESCRIPTION |
|---|---|
mean_sampler
|
A
TYPE:
|
noise_sampler
|
A
TYPE:
|
noise_variance
|
The variance of the noise model. It can be a fixed quantity (int or float), or a sampled
quantity in the case a
TYPE:
|
Source code in neurite/nn/modules.py
SoftQuantize
SoftQuantize(nb_bins: Union[int, Sampler] = 16, softness: Union[float, int, Sampler] = 1.0, min_clip: Union[float, int, Sampler] = -float('inf'), max_clip: Union[float, int, Sampler] = float('inf'), return_log: bool = False)
Bases: Module
Map continuous values to discrete bins.
Map continuous values to discrete bins while retaining some smoothness/continuity which is parametrized by a softening parameter. It is especially useful in the context of machine learning, where it is desirable to have a differentiable version of a quantized quantity, allowing for backprop. Hard quantization is non-differentiable and creates gradients of zero, making gradient-based optimization impossible.
Initialize SoftQuantize.
| PARAMETER | DESCRIPTION |
|---|---|
nb_bins
|
The number of discrete bins to softly quantize the input values into. By default 16
TYPE:
|
softness
|
The softness factor for quantization. A higher value gives smoother quantization. By default 1.0
TYPE:
|
min_clip
|
Clip data lower than this value before calculating bin centers. By default -float('inf')
TYPE:
|
max_clip
|
Clip data higher than this value before calculating bin centers. By default float('inf')
TYPE:
|
return_log
|
Optionally return the log of the softly quantized tensor. By default False
TYPE:
|
Examples:
>>> # Make 3D tensor ~N(0, 1).
>>> input_tensor = torch.randn(1, 1, 32, 32, 32)
>>> # Initialize & apply the SoftQuantize instance.
>>> soft_quantizer = SoftQuantize(nb_bins=4, softness=0.5)
>>> softly_quantized_tensor = soft_quantizer(input_tensor)
>>> # Visualize the softly quantized tensor.
>>> plt.imshow(softly_quantized_tensor[0, 0, 16])
Softly quantize with random nb_bins and softness parameters
>>> # Get `nb_bins` ~U(3, 32), and `softness` ~U(0.001, 10)
>>> soft_quantizer = SoftQuantize(nb_bins=RandInt(3, 32), softness=Uniform(0.001, 10))
>>> softly_quantized_tensor = soft_quantizer(input_tensor)
>>> plt.imshow(softly_quantized_tensor[0, 0, 16])
Source code in neurite/nn/modules.py
TransposedConv
TransposedConv(ndim: int, in_channels: int, out_channels: int, kernel_size: int = 4, stride: int = 2, padding: int = 1, output_padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True)
Bases: Module
Dynamically construct a transposed convolution {ConvTranspose1d,
ConvTranspose2d, ConvTranspose3d} based on the number of input dimensions.
Initialize TransposedConv.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
Spatial dimensionality of the convolution (1 for Conv1d, 2 for Conv2d, 3 for Conv3d).
- 1: Uses
TYPE:
|
in_channels
|
Number of input channels.
TYPE:
|
out_channels
|
Number of output channels.
TYPE:
|
kernel_size
|
Size of the convolving kernel.
TYPE:
|
stride
|
Stride of the convolution. Default is 2.
TYPE:
|
padding
|
Padding added to all sides of the input. Default is 1.
TYPE:
|
output_padding
|
Additional size added to one side of each dimension in the output shape. Default is 0.
TYPE:
|
dilation
|
Spacing between kernel elements. Default is 1.
TYPE:
|
groups
|
Number of blocked connections from input to output channels. Default is 1.
TYPE:
|
bias
|
If True, a learnable bias is added to the output. Default is True.
TYPE:
|
Source code in neurite/nn/modules.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
UpsampleConvBlock
UpsampleConvBlock(ndim: int, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, padding: int = 1, padding_mode: Literal['zeros', 'replicate', 'reflect'] = 'zeros', upsample_mode: Literal['linear', 'transposed', 'nearest'] = 'linear', upsample_kernel_size: int = 4, upsample_stride: int = 2, upsample_padding: int = 1, scale_factor: int = 2, normalization: Union[str, Module, None] = None, activation: Union[str, Module, None] = 'relu', order: str = 'nca', accepts_residuals: bool = True)
Bases: Module
Apply ConvBlock followed by an upsampling operation to extract features and increase spatial
shape.
| ATTRIBUTE | DESCRIPTION |
|---|---|
upsample |
Module to be used for upsampling. One of:
-
TYPE:
|
conv_block |
The convolutional block applying a series of convolutions, normalizations, and activations.
TYPE:
|
Initialize UpsampleConvBlock.
| PARAMETER | DESCRIPTION |
|---|---|
ndim
|
Dimensionality of the convolution (1 for Conv1d, 2 for Conv2d, 3 for Conv3d).
TYPE:
|
in_channels
|
Number of input channels.
TYPE:
|
out_channels
|
Number of output channels.
TYPE:
|
kernel_size
|
Size of the convolving kernel. Default is 3.
TYPE:
|
stride
|
Stride of the convolution. Default is 1.
TYPE:
|
padding
|
Padding added to all sides of the input. Default is 1.
TYPE:
|
upsample_kernel_size
|
Kernel size for the transposed convolution. Default is 4.
TYPE:
|
upsample_stride
|
Stride for the transposed convolution. Default is 2.
TYPE:
|
upsample_padding
|
Padding for the transposed convolution. Default is 1.
TYPE:
|
normalization
|
Normalization type. Default is 'batch'.
TYPE:
|
activation
|
Activation type. Default is 'relu'.
TYPE:
|
order
|
The order of operations in the block. Default is 'nca' (normalization -> convolution ->
activation). Each character in the string can be specified an arbitrary number of times
in any order. Each character in the string represents one of the following:
-
TYPE:
|
accepts_residuals
|
If True, the block is configured to accept residual connections. This doubles the expected number of input channels, allowing the block to concatenate skip features with the main input.
TYPE:
|
Source code in neurite/nn/modules.py
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 | |