nn#

Module: nn.tf#

Module: nn.tf.cnn_1d_denoising#

Title : Denoising diffusion weighted imaging data using CNN#

Obtaining tissue microstructure measurements from diffusion weighted imaging (DWI) with multiple, high b-values is crucial. However, the high noise levels present in these images can adversely affect the accuracy of the microstructural measurements. In this context, we suggest a straightforward denoising technique [1] that can be applied to any DWI dataset as long as a low-noise, single-subject dataset is obtained using the same DWI sequence.

We created a simple 1D-CNN model with five layers, based on the 1D CNN for denoising speech. The model consists of two convolutional layers followed by max-pooling layers, and a dense layer. The first convolutional layer has 16 one-dimensional filters of size 16, and the second layer has 32 filters of size 8. ReLu activation function is applied to both convolutional layers. The max-pooling layer has a kernel size of 2 and a stride of 2. The dense layer maps the features extracted from the noisy image to the low-noise reference image.

Reference#

Cnn1DDenoiser(sig_length, *[, optimizer, ...])

Module: nn.tf.deepn4#

Class and helper functions for fitting the DeepN4 model.

EncoderBlock(out_channels, kernel_size, ...)

Encoder block for the 3D U-Net.

DecoderBlock(out_channels, kernel_size, ...)

Decoder block for the 3D U-Net.

DeepN4(*[, verbose])

This class is intended for the DeepN4 model.

UNet3D(input_shape)

3D U-Net architecture for the DeepN4 model.

Module: nn.tf.evac#

Class and helper functions for fitting the EVAC+ model.

Block(out_channels, kernel_size, strides, ...)

Building block for the EVAC+ model.

ChannelSum()

Layer to sum over the channel dimension.

EVACPlus(*[, verbose])

This class is intended for the EVAC+ model.

prepare_img(image)

Function to prepare image for model input Specific to EVAC+

init_model(*[, model_scale])

Function to create model for EVAC+

Module: nn.tf.histo_resdnn#

Class and helper functions for fitting the Histological ResDNN model.

HistoResDNN(*[, sh_order_max, basis_type, ...])

This class is intended for the ResDNN Histology Network model.

Module: nn.tf.model#

SingleLayerPerceptron(*[, input_shape, ...])

MultipleLayerPercepton(*[, input_shape, ...])

Module: nn.tf.synb0#

Class and helper functions for fitting the Synb0 model.

EncoderBlock(out_channels, kernel_size, ...)

Encoder block for the 3D U-Net.

DecoderBlock(out_channels, kernel_size, ...)

Decoder block for the 3D U-Net.

Synb0(*[, verbose])

This class is intended for the Synb0 model.

UNet3D(input_shape)

3D U-Net architecture for the Synb0 model.

Module: nn.torch#

Module: nn.torch.deepn4#

Class and helper functions for fitting the DeepN4 model.

UNet3D(n_in, n_out)

3D U-Net architecture for the DeepN4 model.

DeepN4(*[, verbose, use_cuda])

This class is intended for the DeepN4 model.

Module: nn.torch.evac#

Class and helper functions for fitting the EVAC+ model.

MoveDimLayer(source_dim, dest_dim)

Layer to move a dimension of a tensor.

ChannelSum()

Layer to sum over the channel dimension.

Add()

Layer to add two tensors.

Block(in_channels, out_channels, ...[, ...])

Building block for the EVAC+ model.

Model([model_scale])

The Model class for the EVAC+ architecture.

EVACPlus(*[, verbose, use_cuda])

This class is intended for the EVAC+ model.

prepare_img(image)

Function to prepare image for model input Specific to EVAC+

Module: nn.torch.histo_resdnn#

Class and helper functions for fitting the Histological ResDNN model.

DenseModel(sh_size, num_hidden)

Deep Neural Network model with several linear layers.

HistoResDNN(*[, sh_order_max, basis_type, ...])

This class is intended for the ResDNN Histology Network model.

Module: nn.torch.synthseg#

Note#

This file is a pytorch adapted version from the sources of the SynthSeg project - BBillot/SynthSeg. All weights and model artchitecture are original from the SynthSeg project. It remains licensed as the rest of SynthSeg (Apache 2.0 license as of January 2026).

# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See LICENSE.txt file distributed along with the SynthSeg package for the # copyright and license terms. # # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

Conv3dELU(in_channels, out_channels, kernel_size)

Mimics TensorFlow Conv3D + ELU fused behavior.

Block(in_channels, out_channels, ...)

Building block for the SynthSeg model.

Model(*[, model_scale, n_levels, ...])

The Model class for the SynthSeg architecture.

SynthSeg(*[, verbose, use_cuda])

This class is intended for the SynthSeg model.

Module: nn.utils#

normalize(image, *[, min_v, max_v, new_min, ...])

normalization function

unnormalize(image, norm_min, norm_max, ...)

unnormalization function

get_bounds(shape, affine, *[, considered_points])

Function to get the bounds of an image after applying affine

transform_img(image, affine, *[, ...])

Function to transform images for Deep Learning models

recover_img(image, params, *[, order])

Function to recover image from transform_img

pad_crop(image, target_shape)

Function to figure out pad and crop range to fit the target shape with the image

inv_pad_crop(image, crop_vs, pad_vs)

Function to figure out pad and crop range to fit the target shape with the image

Cnn1DDenoiser#

class dipy.nn.tf.cnn_1d_denoising.Cnn1DDenoiser(sig_length, *, optimizer='adam', loss='mean_squared_error', metrics=('accuracy',), loss_weights=None)[source]#

Bases: object

Methods

compile(*[, optimizer, loss, metrics, ...])

Configure the model for training.

evaluate(x, y, *[, batch_size, verbose, ...])

Evaluate the model on a test dataset.

fit(x, y, *[, batch_size, epochs, verbose, ...])

Train the model on train dataset.

load_weights(filepath)

Load the model weights from the specified file path.

predict(x, *[, batch_size, verbose, steps, ...])

Generate predictions for input samples.

save_weights(filepath, *[, overwrite])

Save the weights of the model to HDF5 file format.

summary()

Get the summary of the model.

train_test_split(x, y, *[, test_size, ...])

Split the input data into random train and test subsets.

compile(*, optimizer='adam', loss=None, metrics=None, loss_weights=None)[source]#

Configure the model for training.

Parameters:
optimizerstr or optimizer object, optional

Name of optimizer or optimizer object.

lossstr or objective function, optional

Name of objective function or objective function itself. If ‘None’, the model will be compiled without any loss function and can only be used to predict output.

metricslist of metrics, optional

List of metrics to be evaluated by the model during training and testing.

loss_weightslist or dict, optional

Optional list or dictionary specifying scalar coefficients(floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses. If a list, it is expected to have a 1:1 mapping to the model’s outputs. If a dict, it is expected to map output names (strings) to scalar coefficients.

evaluate(x, y, *, batch_size=None, verbose=1, steps=None, callbacks=None, return_dict=False)[source]#

Evaluate the model on a test dataset.

Parameters:
xndarray

Test dataset (high-noise data). If 4D, it will be converted to 1D.

yndarray

Labels of the test dataset (low-noise data). If 4D, it will be converted to 1D.

batch_sizeint, optional

Number of samples per gradient update.

verboseint, optional

Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.

stepsint, optional

Total number of steps (batches of samples) before declaring the evaluation round finished.

callbackslist, optional

List of callbacks to apply during evaluation.

max_queue_sizeint, optional

Maximum size for the generator queue.

workersint, optional

Maximum number of processes to spin up when using process-based threading.

use_multiprocessingbool, optional

If True, use process-based threading.

return_dictbool, optional

If True, loss and metric results are returned as a dictionary.

Returns:
List or dict

If return_dict is False, returns a list of [loss, metrics] values on the test dataset. If return_dict is True, returns a dictionary of metric names and their corresponding values.

fit(x, y, *, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1)[source]#

Train the model on train dataset.

The fit method will train the model for a fixed number of epochs (iterations) on a dataset. If given data is 4D it will convert it into 1D.

Parameters:
xndarray

The input data, as an ndarray.

yndarray

The target data, as an ndarray.

batch_sizeint or None, optional

Number of samples per batch of computation.

epochsint, optional

The number of epochs.

verbose‘auto’, 0, 1, or 2, optional

Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.

callbackslist of keras.callbacks.Callback instances, optional

List of callbacks to apply during training.

validation_splitfloat between 0 and 1, optional

Fraction of the training data to be used as validation data.

validation_datatuple (x_val, y_val) or None, optional

Data on which to evaluate the loss and any model metrics at the end of each epoch.

shuffleboolean, optional

This argument is ignored when x is a generator or an object of tf.data.Dataset.

initial_epochint, optional

Epoch at which to start training.

steps_per_epochint or None, optional

Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch.

validation_batch_sizeint or None, optional

Number of samples per validation batch.

validation_stepsint or None, optional

Only relevant if validation_data is provided and is a tf.data dataset.

validation_freqint or list/tuple/set, optional

Only relevant if validation data is provided. If an integer, specifies how many training epochs to run before a new validation run is performed. If a list, tuple, or set, specifies the epochs on which to run validation.

max_queue_sizeint, optional

Used for generator or keras.utils.Sequence input only.

workersinteger, optional

Used for generator or keras.utils.Sequence input only.

use_multiprocessingboolean, optional

Used for generator or keras.utils.Sequence input only.

Returns:
histobject

A History object. Its History.history attribute is a record of training loss values and metrics values at successive epochs.

load_weights(filepath)[source]#

Load the model weights from the specified file path.

Parameters:
filepathstr

The file path from which to load the weights.

predict(x, *, batch_size=None, verbose=0, steps=None, callbacks=None)[source]#

Generate predictions for input samples.

Parameters:
xndarray

Input samples.

batch_sizeint, optional

Number of samples per batch.

verboseint, optional

Verbosity mode.

stepsint, optional

Total number of steps (batches of samples) before declaring the prediction round finished.

callbackslist, optional

List of Keras callbacks to apply during prediction.

max_queue_sizeint, optional

Maximum size for the generator queue.

workersint, optional

Maximum number of processes to spin up when using process-based threading.

use_multiprocessingbool, optional

If True, use process-based threading. If False, use thread-based threading.

Returns:
ndarray

Numpy array of predictions.

save_weights(filepath, *, overwrite=True)[source]#

Save the weights of the model to HDF5 file format.

Parameters:
filepathstr

The path where the weights should be saved.

overwritebool,optional

If True, overwrites the file if it already exists. If False, raises an error if the file already exists.

summary()[source]#

Get the summary of the model.

The summary is textual and includes information about: The layers and their order in the model. The output shape of each layer.

Returns:
summaryNoneType

the summary of the model

train_test_split(x, y, *, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)[source]#

Split the input data into random train and test subsets.

Parameters:
x: numpy array

input data.

y: numpy array

target data.

test_size: float or int, optional

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.25.

train_size: float or int, optional

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.

random_state: int, np.random.Generator instance or None, optional

Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls. See Glossary.

shuffle: bool, optional

Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.

stratify: array-like, optional

If not None, data is split in a stratified fashion, using this as the class labels. Read more in the User Guide.

Returns:
Tuple of four numpy arrays: x_train, x_test, y_train, y_test.

EncoderBlock#

class dipy.nn.tf.deepn4.EncoderBlock(out_channels, kernel_size, strides, padding)[source]#

Bases: Layer

Encoder block for the 3D U-Net.

Parameters:
out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingstr

Padding for the convolution (‘same’ or ‘valid’).

Methods

call(input)

Forward pass of the EncoderBlock.

call(input)[source]#

Forward pass of the EncoderBlock.

Parameters:
inputtf.Tensor

Input tensor.

Returns:
tf.Tensor

Output tensor.

DecoderBlock#

class dipy.nn.tf.deepn4.DecoderBlock(out_channels, kernel_size, strides, padding)[source]#

Bases: Layer

Decoder block for the 3D U-Net.

Parameters:
out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingstr

Padding for the convolution (‘same’ or ‘valid’).

Methods

call(input)

Forward pass of the DecoderBlock.

call(input)[source]#

Forward pass of the DecoderBlock.

Parameters:
inputtf.Tensor

Input tensor.

Returns:
tf.Tensor

Output tensor.

DeepN4#

class dipy.nn.tf.deepn4.DeepN4(*, verbose=False)[source]#

Bases: object

This class is intended for the DeepN4 model.

The DeepN4 model [2] predicts the bias field for magnetic field inhomogeneity correction on T1-weighted images.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

load_resample(subj)

Preprocess the subject image for the model.

pad(img, sz)

Pad or crop the image to the specified size.

predict(img, img_affine, *[, threshold])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights (hdf5, saved by tensorflow)

load_resample(subj)[source]#

Preprocess the subject image for the model.

This includes padding, normalization, and converting to a tensor.

Parameters:
subjnp.ndarray

The subject image.

Returns:
tuple

A tuple containing the processed tensor and auxiliary parameters.

pad(img, sz)[source]#

Pad or crop the image to the specified size.

Parameters:
imgnp.ndarray

The image to pad or crop.

szint

The target size for each dimension.

Returns:
tmpnp.ndarray

The padded or cropped image.

indiceslist

A list of indices used for padding and cropping.

predict(img, img_affine, *, threshold=0.5)[source]#

Wrapper function to facilitate prediction of larger dataset. The function will mask, normalize, split, predict and ‘re-assemble’ the data as a volume.

Parameters:
imgnp.ndarray

T1 image to predict and apply bias field

img_affinenp.ndarray (4, 4)

Affine matrix for the T1 image

thresholdfloat, optional

Threshold for cleaning the final correction field

Returns:
final_correctednp.ndarray (x, y, z)

Predicted bias corrected image. The volume has matching shape to the input data

UNet3D#

dipy.nn.tf.deepn4.UNet3D(input_shape)[source]#

3D U-Net architecture for the DeepN4 model.

Parameters:
input_shapetuple

Shape of the input tensor.

Returns:
tf.keras.Model

The 3D U-Net model.

Block#

class dipy.nn.tf.evac.Block(out_channels, kernel_size, strides, padding, drop_r, n_layers, *, layer_type='down')[source]#

Bases: Layer

Building block for the EVAC+ model.

Parameters:
out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingstr

Padding for the convolution (‘same’ or ‘valid’).

drop_rfloat

Dropout rate.

n_layersint

Number of convolutional layers in the block.

layer_typestr, optional

Type of the block: ‘down’ or ‘up’.

Methods

call(input, passed)

Forward pass of the Block.

call(input, passed)[source]#

Forward pass of the Block.

Parameters:
inputtf.Tensor

Input tensor.

passedtf.Tensor

Tensor from skipped connection.

Returns:
fwdtf.Tensor

Output of the convolutional layers after adding the passed tensor.

xtf.Tensor

Output of the downsampling or upsampling layer.

ChannelSum#

class dipy.nn.tf.evac.ChannelSum[source]#

Bases: Layer

Layer to sum over the channel dimension.

Methods

call(inputs)

Forward pass of the ChannelSum layer.

call(inputs)[source]#

Forward pass of the ChannelSum layer.

Parameters:
inputstf.Tensor

Input tensor.

Returns:
tf.Tensor

Summed tensor over the channel dimension.

EVACPlus#

class dipy.nn.tf.evac.EVACPlus(*, verbose=False)[source]#

Bases: object

This class is intended for the EVAC+ model.

The EVAC+ model [3] is a deep learning neural network for brain extraction. It uses a V-net architecture combined with multi-resolution input data, an additional conditional random field (CRF) recurrent layer and supplementary Dice loss term for this recurrent layer.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(T1, affine, *[, batch_size, ...])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting. While the user can load different weights, the function is mainly intended for the class function ‘predict’.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights (hdf5, saved by tensorflow)

predict(T1, affine, *, batch_size=None, return_prob=False, finalize_mask=True)[source]#

Wrapper function to facilitate prediction of larger dataset.

Parameters:
T1np.ndarray or list of np.ndarray

For a single image, input should be a 3D array. If multiple images, it should be a a list or tuple. or list of np.ndarrays with len of batch_size

affinenp.ndarray (4, 4) or (batch, 4, 4)

Affine matrix for the T1 image. Should have batch dimension if T1 has one.

batch_sizeint, optional

Number of images per prediction pass. Only available if data is provided with a batch dimension. Consider lowering it if you get an out of memory error. Increase it if you want it to be faster and have a lot of data. If None, batch_size will be set to 1 if the provided image has a batch dimension.

return_probbool, optional

Whether to return the probability map instead of a binary mask. Useful for testing.

finalize_maskbool, optional

Whether to remove potential holes or islands. Useful for solving minor errors.

Returns:
pred_outputnp.ndarray (…) or (batch, …)

Predicted brain mask

affinenp.ndarray (…) or (batch, …)

affine matrix of mask only if return_affine is True

prepare_img#

dipy.nn.tf.evac.prepare_img(image)[source]#

Function to prepare image for model input Specific to EVAC+

Parameters:
imagenp.ndarray

Input image

Returns:
input_datadict

init_model#

dipy.nn.tf.evac.init_model(*, model_scale=16)[source]#

Function to create model for EVAC+

Parameters:
model_scaleint, optional

The scale of the model Should match the saved weights from fetcher Default is 16

Returns:
modeltf.keras.Model

HistoResDNN#

class dipy.nn.tf.histo_resdnn.HistoResDNN(*, sh_order_max=8, basis_type='tournier07', verbose=False)[source]#

Bases: object

This class is intended for the ResDNN Histology Network model.

ResDNN [4] is a deep neural network that employs residual blocks deep neural network to predict ground truth SH coefficients from SH coefficients computed using DWI data. To this end, authors considered histology FOD-computed SH coefficients (obtained from ex vivo non-human primate acquisitions) as their ground truth, and the DWI-computed SH coefficients as their target.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(data, gtab, *[, mask, chunk_size])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting. Will not work if the declared SH_ORDER does not match the weights expected input.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting. Will not work if the declared SH_ORDER does not match the weights expected input.

The weights for a sh_order of 8 can be obtained via the function:

get_fnames(name=’histo_resdnn_tf_weights’).

Parameters:
weights_pathstr

Path to the file containing the weights (hdf5, saved by tensorflow)

predict(data, gtab, *, mask=None, chunk_size=1000)[source]#

Wrapper function to facilitate prediction of larger dataset. The function will mask, normalize, split, predict and ‘re-assemble’ the data as a volume.

Parameters:
datanp.ndarray

DWI signal in a 4D array

gtabGradientTable class instance

The acquisition scheme matching the data (must contain at least one b0)

masknp.ndarray, optional

Binary mask of the brain to avoid unnecessary computation and unreliable prediction outside the brain. Default: Compute prediction only for nonzero voxels (with at least one nonzero DWI value).

chunk_sizeint, optional

Batch size when running model prediction.

Returns:
pred_sh_coefnp.ndarray (x, y, z, M)

Predicted fODF (as SH). The volume has matching shape to the input data, but with (sh_order_max + 1) * (sh_order_max + 2) / 2 as a last dimension.

SingleLayerPerceptron#

class dipy.nn.tf.model.SingleLayerPerceptron(*, input_shape=(28, 28), num_hidden=128, act_hidden='relu', dropout=0.2, num_out=10, act_out='softmax', optimizer='adam', loss='sparse_categorical_crossentropy')[source]#

Bases: object

Methods

evaluate(x_test, y_test, *[, verbose])

Evaluate the model on test dataset.

fit(x_train, y_train, *[, epochs])

Train the model on train dataset.

predict(x_test)

Predict the output from input samples.

summary()

Get the summary of the model.

evaluate(x_test, y_test, *, verbose=2)[source]#

Evaluate the model on test dataset.

The evaluate method will evaluate the model on a test dataset.

Parameters:
x_testndarray

the x_test is the test dataset

y_testndarray shape=(BatchSize,)

the y_test is the labels of the test dataset

verboseint (Default = 2)

By setting verbose 0, 1 or 2 you just say how do you want to ‘see’ the training progress for each epoch.

Returns:
evaluateList

return list of loss value and accuracy value on test dataset

fit(x_train, y_train, *, epochs=5)[source]#

Train the model on train dataset.

The fit method will train the model for a fixed number of epochs (iterations) on a dataset.

Parameters:
x_trainndarray

the x_train is the train dataset

y_trainndarray shape=(BatchSize,)

the y_train is the labels of the train dataset

epochsint (Default = 5)

the number of epochs

Returns:
histobject

A History object. Its History.history attribute is a record of training loss values and metrics values at successive epochs

predict(x_test)[source]#

Predict the output from input samples.

The predict method will generates output predictions for the input samples.

Parameters:
x_trainndarray

the x_test is the test dataset or input samples

Returns:
predictndarray shape(TestSize,OutputSize)

Numpy array(s) of predictions.

summary()[source]#

Get the summary of the model.

The summary is textual and includes information about: The layers and their order in the model. The output shape of each layer.

Returns:
summaryNoneType

the summary of the model

MultipleLayerPercepton#

class dipy.nn.tf.model.MultipleLayerPercepton(*, input_shape=(28, 28), num_hidden=(128,), act_hidden='relu', dropout=0.2, num_out=10, act_out='softmax', loss='sparse_categorical_crossentropy', optimizer='adam')[source]#

Bases: object

Methods

evaluate(x_test, y_test, *[, verbose])

Evaluate the model on test dataset.

fit(x_train, y_train, *[, epochs])

Train the model on train dataset.

predict(x_test)

Predict the output from input samples.

summary()

Get the summary of the model.

evaluate(x_test, y_test, *, verbose=2)[source]#

Evaluate the model on test dataset.

The evaluate method will evaluate the model on a test dataset.

Parameters:
x_testndarray

the x_test is the test dataset

y_testndarray shape=(BatchSize,)

the y_test is the labels of the test dataset

verboseint (Default = 2)

By setting verbose 0, 1 or 2 you just say how do you want to ‘see’ the training progress for each epoch.

Returns:
evaluateList

return list of loss value and accuracy value on test dataset

fit(x_train, y_train, *, epochs=5)[source]#

Train the model on train dataset.

The fit method will train the model for a fixed number of epochs (iterations) on a dataset.

Parameters:
x_trainndarray

the x_train is the train dataset

y_trainndarray shape=(BatchSize,)

the y_train is the labels of the train dataset

epochsint (Default = 5)

the number of epochs

Returns:
histobject

A History object. Its History.history attribute is a record of training loss values and metrics values at successive epochs

predict(x_test)[source]#

Predict the output from input samples.

The predict method will generates output predictions for the input samples.

Parameters:
x_trainndarray

the x_test is the test dataset or input samples

Returns:
predictndarray shape(TestSize,OutputSize)

Numpy array(s) of predictions.

summary()[source]#

Get the summary of the model.

The summary is textual and includes information about: The layers and their order in the model. The output shape of each layer.

Returns:
summaryNoneType

the summary of the model

EncoderBlock#

class dipy.nn.tf.synb0.EncoderBlock(out_channels, kernel_size, strides, padding)[source]#

Bases: Layer

Encoder block for the 3D U-Net.

Parameters:
out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingstr

Padding for the convolution (‘same’ or ‘valid’).

Methods

call(input)

Forward pass of the EncoderBlock.

call(input)[source]#

Forward pass of the EncoderBlock.

Parameters:
inputtf.Tensor

Input tensor.

Returns:
tf.Tensor

Output tensor.

DecoderBlock#

class dipy.nn.tf.synb0.DecoderBlock(out_channels, kernel_size, strides, padding)[source]#

Bases: Layer

Decoder block for the 3D U-Net.

Parameters:
out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingstr

Padding for the convolution (‘same’ or ‘valid’).

Methods

call(input)

Forward pass of the DecoderBlock.

call(input)[source]#

Forward pass of the DecoderBlock.

Parameters:
inputtf.Tensor

Input tensor.

Returns:
tf.Tensor

Output tensor.

Synb0#

class dipy.nn.tf.synb0.Synb0(*, verbose=False)[source]#

Bases: object

This class is intended for the Synb0 model.

Synb0 [5], [6] uses a neural network to synthesize a b0 volume for distortion correction in DWI images.

The model is the deep learning part of the Synb0-Disco pipeline, thus stand-alone usage is not recommended.

Methods

fetch_default_weights(idx)

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(b0, T1, *[, batch_size, average])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights(idx)[source]#

Load the model pre-training weights to use for the fitting. While the user can load different weights, the function is mainly intended for the class function ‘predict’.

Parameters:
idxint

The idx of the default weights. It can be from 0~4.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights (hdf5, saved by tensorflow)

predict(b0, T1, *, batch_size=None, average=True)[source]#

Wrapper function to facilitate prediction of larger dataset. The function will pad the data to meet the required shape of image. Note that the b0 and T1 image should have the same shape

Parameters:
b0np.ndarray (batch, 77, 91, 77) or (77, 91, 77)

For a single image, input should be a 3D array. If multiple images, there should also be a batch dimension.

T1np.ndarray (batch, 77, 91, 77) or (77, 91, 77)

For a single image, input should be a 3D array. If multiple images, there should also be a batch dimension.

batch_sizeint

Number of images per prediction pass. Only available if data is provided with a batch dimension. Consider lowering it if you get an out of memory error. Increase it if you want it to be faster and have a lot of data. If None, batch_size will be set to 1 if the provided image has a batch dimension. Default is None

averagebool

Whether the function follows the Synb0-Disco pipeline and averages the prediction of 5 different models. If False, it uses the loaded weights for prediction. Default is True.

Returns
——-
pred_outputnp.ndarray (…) or (batch, …)

Reconstructed b-inf image(s)

UNet3D#

dipy.nn.tf.synb0.UNet3D(input_shape)[source]#

3D U-Net architecture for the Synb0 model.

Parameters:
input_shapetuple

Shape of the input tensor.

Returns:
tf.keras.Model

The 3D U-Net model.

UNet3D#

class dipy.nn.torch.deepn4.UNet3D(n_in, n_out)[source]#

Bases: Module

3D U-Net architecture for the DeepN4 model.

Parameters:
n_inint

Number of input channels.

n_outint

Number of output channels.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

decoder_block(in_channels, out_channels, ...)

Decoder block for the 3D U-Net.

double()

Casts all floating point parameters and buffers to double datatype.

encoder_block(in_channels, out_channels, ...)

Encoder block for the 3D U-Net.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Forward pass of the 3D U-Net.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

decoder_block(in_channels, out_channels, kernel_size, stride, padding)[source]#

Decoder block for the 3D U-Net.

Parameters:
in_channelsint

Number of input channels.

out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

strideint

Stride of the convolution.

paddingint

Padding of the convolution.

Returns:
torch.nn.Sequential

The decoder block.

encoder_block(in_channels, out_channels, kernel_size, stride, padding)[source]#

Encoder block for the 3D U-Net.

Parameters:
in_channelsint

Number of input channels.

out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

strideint

Stride of the convolution.

paddingint

Padding of the convolution.

Returns:
torch.nn.Sequential

The encoder block.

forward(x)[source]#

Forward pass of the 3D U-Net.

Parameters:
xtorch.Tensor

Input tensor.

Returns:
torch.Tensor

Output tensor.

DeepN4#

class dipy.nn.torch.deepn4.DeepN4(*, verbose=False, use_cuda=False)[source]#

Bases: object

This class is intended for the DeepN4 model.

The DeepN4 model [2] predicts the bias field for magnetic field inhomogeneity correction on T1-weighted images.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

load_resample(subj)

Preprocess the subject image for the model.

pad(img, sz)

Pad or crop the image to the specified size.

predict(img, img_affine, *[, threshold])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights

load_resample(subj)[source]#

Preprocess the subject image for the model.

This includes padding, normalization, and converting to a tensor.

Parameters:
subjnp.ndarray

The subject image.

Returns:
tuple

A tuple containing the processed tensor and auxiliary parameters.

pad(img, sz)[source]#

Pad or crop the image to the specified size.

Parameters:
imgnp.ndarray

The image to pad or crop.

szint

The target size for each dimension.

Returns:
tmpnp.ndarray

The padded or cropped image.

indiceslist

A list of indices used for padding and cropping.

predict(img, img_affine, *, threshold=0.5)[source]#

Wrapper function to facilitate prediction of larger dataset. The function will mask, normalize, split, predict and ‘re-assemble’ the data as a volume.

Parameters:
imgnp.ndarray

T1 image to predict and apply bias field

img_affinenp.ndarray (4, 4)

Affine matrix for the T1 image

thresholdfloat, optional

Threshold for cleaning the final correction field

Returns:
final_correctednp.ndarray (x, y, z)

Predicted bias corrected image. The volume has matching shape to the input data

MoveDimLayer#

class dipy.nn.torch.evac.MoveDimLayer(source_dim, dest_dim)[source]#

Bases: Module

Layer to move a dimension of a tensor.

Parameters:
source_dimint

The dimension to move.

dest_dimint

The dimension to move to.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Forward pass of the MoveDimLayer.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(x)[source]#

Forward pass of the MoveDimLayer.

Parameters:
xtorch.Tensor

Input tensor.

Returns:
torch.Tensor

Tensor with moved dimension.

ChannelSum#

class dipy.nn.torch.evac.ChannelSum[source]#

Bases: Module

Layer to sum over the channel dimension.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(inputs)

Forward pass of the ChannelSum layer.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(inputs)[source]#

Forward pass of the ChannelSum layer.

Parameters:
inputstorch.Tensor

Input tensor.

Returns:
torch.Tensor

Summed tensor over the channel dimension.

Add#

class dipy.nn.torch.evac.Add[source]#

Bases: Module

Layer to add two tensors.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x, passed)

Forward pass of the Add layer.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(x, passed)[source]#

Forward pass of the Add layer.

Parameters:
xtorch.Tensor

First input tensor.

passedtorch.Tensor

Second input tensor.

Returns:
torch.Tensor

Sum of the two input tensors.

Block#

class dipy.nn.torch.evac.Block(in_channels, out_channels, kernel_size, strides, padding, drop_r, n_layers, *, passed_channel=1, layer_type='down')[source]#

Bases: Module

Building block for the EVAC+ model.

Parameters:
in_channelsint

Number of input channels.

out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

stridesint

Stride of the convolution.

paddingint

Padding of the convolution.

drop_rfloat

Dropout rate.

n_layersint

Number of convolutional layers in the block.

passed_channelint, optional

Number of channels in the skipped connection.

layer_typestr, optional

Type of the block: ‘down’, ‘up’, or ‘none’.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(input, passed)

Forward pass of the Block.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(input, passed)[source]#

Forward pass of the Block.

Parameters:
inputtorch.Tensor

Input tensor.

passedtorch.Tensor

Tensor from skipped connection.

Returns:
fwdtorch.Tensor

Output of the convolutional layers after adding the passed tensor.

xtorch.Tensor

Output of the downsampling or upsampling layer.

Model#

class dipy.nn.torch.evac.Model(model_scale=16)[source]#

Bases: Module

The Model class for the EVAC+ architecture.

Parameters:
model_scaleint, optional

The scale of the model.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(inputs, raw_input_2, raw_input_3, ...)

Forward pass of the EVAC+ model.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(inputs, raw_input_2, raw_input_3, raw_input_4, raw_input_5)[source]#

Forward pass of the EVAC+ model.

Parameters:
inputstorch.Tensor

Main input tensor.

raw_input_2torch.Tensor

Multi-resolution input tensor at scale 2.

raw_input_3torch.Tensor

Multi-resolution input tensor at scale 4.

raw_input_4torch.Tensor

Multi-resolution input tensor at scale 8.

raw_input_5torch.Tensor

Multi-resolution input tensor at scale 16.

Returns:
torch.Tensor

Predicted brain mask probability map.

EVACPlus#

class dipy.nn.torch.evac.EVACPlus(*, verbose=False, use_cuda=False)[source]#

Bases: object

This class is intended for the EVAC+ model.

The EVAC+ model [3] is a deep learning neural network for brain extraction. It uses a V-net architecture combined with multi-resolution input data, an additional conditional random field (CRF) recurrent layer and supplementary Dice loss term for this recurrent layer.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

init_model([model_scale])

Initialize the EVAC+ model.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(T1, affine, *[, batch_size, ...])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting. While the user can load different weights, the function is mainly intended for the class function ‘predict’.

init_model(model_scale=16)[source]#

Initialize the EVAC+ model.

Parameters:
model_scaleint, optional

The scale of the model.

Returns:
Model

Initialized EVAC+ model.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights (pth, saved by Pytorch)

predict(T1, affine, *, batch_size=None, return_prob=False, finalize_mask=True)[source]#

Wrapper function to facilitate prediction of larger dataset.

Parameters:
T1np.ndarray or list of np.ndarray

For a single image, input should be a 3D array. If multiple images, it should be a a list or tuple.

affinenp.ndarray (4, 4) or (batch, 4, 4)

or list of np.ndarrays with len of batch Affine matrix for the T1 image. Should have batch dimension if T1 has one.

batch_sizeint, optional

Number of images per prediction pass. Only available if data is provided with a batch dimension. Consider lowering it if you get an out of memory error. Increase it if you want it to be faster and have a lot of data. If None, batch_size will be set to 1 if the provided image has a batch dimension.

return_probbool, optional

Whether to return the probability map instead of a binary mask. Useful for testing.

finalize_maskbool, optional

Whether to remove potential holes or islands. Useful for solving minor errors.

Returns:
pred_outputnp.ndarray (…) or (batch, …)

Predicted brain mask

affinenp.ndarray (…) or (batch, …)

affine matrix of mask only if return_affine is True

prepare_img#

dipy.nn.torch.evac.prepare_img(image)[source]#

Function to prepare image for model input Specific to EVAC+

Parameters:
imagenp.ndarray

Input image

Returns:
input_datadict

DenseModel#

class dipy.nn.torch.histo_resdnn.DenseModel(sh_size, num_hidden)[source]#

Bases: Module

Deep Neural Network model with several linear layers.

Parameters:
sh_sizeint

Size of the input spherical harmonics.

num_hiddenint

Number of units in the hidden layers.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Forward pass of the model.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(x)[source]#

Forward pass of the model.

Parameters:
xtorch.Tensor

Input tensor.

Returns:
torch.Tensor

Output tensor.

HistoResDNN#

class dipy.nn.torch.histo_resdnn.HistoResDNN(*, sh_order_max=8, basis_type='tournier07', verbose=False, use_cuda=False)[source]#

Bases: object

This class is intended for the ResDNN Histology Network model.

ResDNN [4] is a deep neural network that employs residual blocks deep neural network to predict ground truth SH coefficients from SH coefficients computed using DWI data. To this end, authors considered histology FOD-computed SH coefficients (obtained from ex vivo non-human primate acquisitions) as their ground truth, and the DWI-computed SH coefficients as their target.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(data, gtab, *[, mask, chunk_size])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting. Will not work if the declared SH_ORDER does not match the weights expected input.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting. Will not work if the declared SH_ORDER does not match the weights expected input.

The weights for a sh_order of 8 can be obtained via the function:

get_fnames(‘histo_resdnn_torch_weights’).

Parameters:
weights_pathstr

Path to the file containing the weights (pth, saved by Pytorch)

predict(data, gtab, *, mask=None, chunk_size=1000)[source]#

Wrapper function to facilitate prediction of larger dataset. The function will mask, normalize, split, predict and ‘re-assemble’ the data as a volume.

Parameters:
datanp.ndarray

DWI signal in a 4D array

gtabGradientTable class instance

The acquisition scheme matching the data (must contain at least one b0)

masknp.ndarray, optional

Binary mask of the brain to avoid unnecessary computation and unreliable prediction outside the brain. Default: Compute prediction only for nonzero voxels (with at least one nonzero DWI value).

chunk_sizeint, optional

Batch size when running model prediction.

Returns:
pred_sh_coefnp.ndarray (x, y, z, M)

Predicted fODF (as SH). The volume has matching shape to the input data, but with (sh_order_max + 1) * (sh_order_max + 2) / 2 as a last dimension.

Conv3dELU#

class dipy.nn.torch.synthseg.Conv3dELU(in_channels, out_channels, kernel_size, padding=0, stride=1, dilation=1, bias=True)[source]#

Bases: Module

Mimics TensorFlow Conv3D + ELU fused behavior.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Forward pass of the Conv3dELU layer.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(x)[source]#

Forward pass of the Conv3dELU layer.

Parameters:
xtorch.Tensor

Input tensor.

Returns:
torch.Tensor

Output tensor after convolution and ELU activation.

Block#

class dipy.nn.torch.synthseg.Block(in_channels, out_channels, kernel_size, padding, n_layers, layer_type)[source]#

Bases: Module

Building block for the SynthSeg model.

Parameters:
in_channelsint

Number of input channels.

out_channelsint

Number of output channels.

kernel_sizeint

Size of the convolutional kernel.

paddingint

Padding of the convolution.

n_layersint

Number of convolutional layers in the block.

layer_typestr

Type of the block: ‘down’, ‘down2’, or ‘up’.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(input, passed)

Forward pass of the Block.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(input, passed)[source]#

Forward pass of the Block.

Parameters:
inputtorch.Tensor

Input tensor.

passedtorch.Tensor

Tensor from skipped connection.

Returns:
xtorch.Tensor

Output of the convolutional layers.

skiptorch.Tensor, optional

Output of the convolutional layers before downsampling. Only returned if layer_type is ‘down’.

Model#

class dipy.nn.torch.synthseg.Model(*, model_scale=24, n_levels=5, output_channels=33)[source]#

Bases: Module

The Model class for the SynthSeg architecture.

Parameters:
model_scaleint, optional

The scale of the model.

n_levelsint, optional

Number of levels in the U-Net.

output_channelsint, optional

Number of output channels.

Methods

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(inputs)

Forward pass of the SynthSeg model.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

__call__

forward(inputs)[source]#

Forward pass of the SynthSeg model.

Parameters:
inputstorch.Tensor

Input tensor.

Returns:
torch.Tensor

Predicted brain segmentation probability map.

SynthSeg#

class dipy.nn.torch.synthseg.SynthSeg(*, verbose=False, use_cuda=False)[source]#

Bases: object

This class is intended for the SynthSeg model.

The SynthSeg model [7] is a deep learning neural network for brain segmentation. It uses a U-net architecture and was trained on synthetic images generated from label maps. The model is robust to variations in contrast and resolution, making it suitable for segmenting a wide range of brain scans.

Note that we are not saving any PVE maps here, only the hard segmentation due to the size of the output probability maps.

Methods

fetch_default_weights()

Load the model pre-training weights to use for the fitting.

init_model([model_scale, n_levels, ...])

Initialize the SynthSeg model.

load_model_weights(weights_path)

Load the custom pre-training weights to use for the fitting.

predict(T1, affine, *[, batch_size, return_prob])

Wrapper function to facilitate prediction of larger dataset.

References

fetch_default_weights()[source]#

Load the model pre-training weights to use for the fitting.

While the user can load different weights, the function is mainly intended for the class function ‘predict’.

init_model(model_scale=24, n_levels=5, output_channels=33)[source]#

Initialize the SynthSeg model.

Parameters:
model_scaleint, optional

The scale of the model.

n_levelsint, optional

Number of levels in the U-Net.

output_channelsint, optional

Number of output channels.

Returns:
Model

Initialized SynthSeg model.

load_model_weights(weights_path)[source]#

Load the custom pre-training weights to use for the fitting.

Parameters:
weights_pathstr

Path to the file containing the weights (pth, saved by Pytorch)

predict(T1, affine, *, batch_size=None, return_prob=False)[source]#

Wrapper function to facilitate prediction of larger dataset.

Parameters:
T1np.ndarray or list of np.ndarray

For a single image, input should be a 3D array. If multiple images, it should be a a list or tuple.

affinenp.ndarray (4, 4) or (batch, 4, 4)

or list of np.ndarrays with len of batch Affine matrix for the T1 image. Should have batch dimension if T1 has one.

batch_sizeint, optional

Number of images per prediction pass. Only available if data is provided with a batch dimension. Consider lowering it if you get an out of memory error. Increase it if you want it to be faster and have a lot of data. If None, batch_size will be set to 1 if the provided image has a batch dimension.

return_probbool, optional

Whether to return the probability map instead of a label map. Useful for testing.

Returns:
pred_outputnp.ndarray (…) or (batch, …)

Predicted brain labels. If return_prob is True, it will be a probability map instead of a label map.

label_dictdict

Dictionary mapping label indices to anatomical structure names. Only if return_prob is False.

masknp.ndarray (…) or (batch, …)

Predicted brain mask. Only if return_prob is False.

normalize#

dipy.nn.utils.normalize(image, *, min_v=None, max_v=None, new_min=-1, new_max=1)[source]#

normalization function

Parameters:
imagenp.ndarray

Image to be normalized.

min_vint or float, optional

minimum value range for normalization intensities below min_v will be clipped if None it is set to min value of image

max_vint or float, optional

maximum value range for normalization intensities above max_v will be clipped if None it is set to max value of image

new_minint or float, optional

new minimum value after normalization

new_maxint or float, optional

new maximum value after normalization

Returns:
np.ndarray

Normalized image from range new_min to new_max

unnormalize#

dipy.nn.utils.unnormalize(image, norm_min, norm_max, min_v, max_v)[source]#

unnormalization function

Parameters:
imagenp.ndarray
norm_minint or float

minimum value of normalized image

norm_maxint or float

maximum value of normalized image

min_vint or float

minimum value of unnormalized image

max_vint or float

maximum value of unnormalized image

Returns:
np.ndarray

unnormalized image from range min_v to max_v

get_bounds#

dipy.nn.utils.get_bounds(shape, affine, *, considered_points='corners')[source]#

Function to get the bounds of an image after applying affine

Parameters:
shapetuple (3,)

Shape of the image

affinenp.ndarray

Affine matrix provided by the image file.

considered_pointsstr, optional

Considered points when calculating the transformed shape. “corners” will consider only corners of the image shape. “all” will consider all voxels. Might be needed when shearing is applied.

Returns:
min_boundsnp.ndarray (3,)

Minimum bounds of the transformed image

max_boundsnp.ndarray (3,)

Maximum bounds of the transformed image

transform_img#

dipy.nn.utils.transform_img(image, affine, *, target_voxsize=None, final_size=None, order=3, considered_points='corners')[source]#

Function to transform images for Deep Learning models

Parameters:
imagenp.ndarray

Image to transform.

affinenp.ndarray

Affine matrix provided by the image file.

target_voxsizetuple (3,), optional

The voxel size we want to start from. If none is provided, we calculate the closest isotropic voxel size.

final_sizetuple (3,), optional

The final size of the image array.

orderint, optional

The order of the spline interpolation. The order has to be in the range 0-5. If transforming an int image, order 0 is recommended.

considered_pointsstr, optional

Considered points when calculating the transformed shape. “corners” will consider only corners of the image shape. “all” will consider all voxels. Might be needed when shearing is applied.

Returns:
new_imagenp.ndarray

Transformed image to be used in the Deep Learning model.

paramsdict

Parameters that are used when recovering the original image space.

recover_img#

dipy.nn.utils.recover_img(image, params, *, order=3)[source]#

Function to recover image from transform_img

Parameters:
imagenp.ndarray

Image to recover.

paramsdict

Parameters for recover_img function. Returned from transform_img.

orderint, optional

The order of the spline interpolation. The order has to be in the range 0-5. If recovering an int image, order 0 is recommended.

Returns:
recoverednp.ndarray

Recovered image

pad_crop#

dipy.nn.utils.pad_crop(image, target_shape)[source]#

Function to figure out pad and crop range to fit the target shape with the image

Parameters:
imagenp.ndarray

Target image

target_shape(3,)

Target shape

Returns:
imagenp.ndarray

Padded/cropped image

pad_vsnp.ndarray (3,2)

Pad range used

crop_vsnp.ndarray (3,2)

Crop range used

inv_pad_crop#

dipy.nn.utils.inv_pad_crop(image, crop_vs, pad_vs)[source]#

Function to figure out pad and crop range to fit the target shape with the image

Parameters:
imagenp.ndarray

Target image

crop_vsnp.ndarray (3,2)

Crop range used when padding/cropping

pad_vsnp.ndarray (3,2)

Pad range used when padding/cropping

Returns:
imagenp.ndarray

Recovered image