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(*args, **kwargs)

DecoderBlock(*args, **kwargs)

DeepN4(*[, verbose])

This class is intended for the DeepN4 model.

UNet3D(input_shape)

Module: nn.tf.evac#

Class and helper functions for fitting the EVAC+ model.

Block(*args, **kwargs)

ChannelSum(*args, **kwargs)

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(*args, **kwargs)

DecoderBlock(*args, **kwargs)

Synb0(*[, verbose])

This class is intended for the Synb0 model.

UNet3D(input_shape)

Module: nn.torch#

Module: nn.torch.evac#

Class and helper functions for fitting the EVAC+ model.

MoveDimLayer(source_dim, dest_dim)

ChannelSum()

Add()

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

Model([model_scale])

EVACPlus(*[, verbose])

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)

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

This class is intended for the ResDNN Histology Network model.

Module: nn.utils#

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

normalization function

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

unnormalization function

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

Function to reshape image as an input to the model

recover_img(image, inv_affine, mid_shape, ...)

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

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, RandomState 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(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(input)[source]#

DecoderBlock#

class dipy.nn.tf.deepn4.DecoderBlock(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(input)[source]#

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.

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

Wrapper function to facilitate prediction of larger dataset.

load_resample

pad

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. get_fnames(‘deepn4_default_weights’).

Parameters:
weights_pathstr

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

load_resample(subj)[source]#
pad(img, sz)[source]#
predict(img, img_affine, *, voxsize=(1, 1, 1))[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:
input_filestring

Path to the T1 scan

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]#

Block#

class dipy.nn.tf.evac.Block(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(input, passed)[source]#

ChannelSum#

class dipy.nn.tf.evac.ChannelSum(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(inputs)[source]#

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, *[, voxsize, ...])

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, *, voxsize=(1, 1, 1), batch_size=None, return_affine=False, 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.

voxsizenp.ndarray or list or tuple, optional

(3,) or (batch, 3) voxel size of the T1 image.

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_affinebool, optional

Whether to return the affine matrix. Useful if the input was a file path.

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).

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(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(input)[source]#

DecoderBlock#

class dipy.nn.tf.synb0.DecoderBlock(*args, **kwargs)[source]#

Bases: Layer

Attributes:
compute_dtype

The dtype of the computations performed by the layer.

dtype

Alias of layer.variable_dtype.

dtype_policy
input

Retrieves the input tensor(s) of a symbolic operation.

input_dtype

The dtype layer inputs should be converted to.

input_spec
losses

List of scalar losses from add_loss, regularizers and sublayers.

metrics

List of all metrics.

metrics_variables

List of all metric variables.

non_trainable_variables

List of all non-trainable layer state.

non_trainable_weights

List of all non-trainable weight variables of the layer.

output

Retrieves the output tensor(s) of a layer.

path

The path of the layer.

quantization_mode

The quantization mode of this layer, None if not quantized.

supports_masking

Whether this layer supports computing a mask using compute_mask.

trainable

Settable boolean, whether this layer should be trainable or not.

trainable_variables

List of all trainable layer state.

trainable_weights

List of all trainable weight variables of the layer.

variable_dtype

The dtype of the state (weights) of the layer.

variables

List of all layer state, including random seeds.

weights

List of all weight variables of the layer.

Methods

__call__(*args, **kwargs)

Call self as a function.

add_loss(loss)

Can be called inside of the call() method to add a scalar loss.

add_variable(shape, initializer[, dtype, ...])

Add a weight variable to the layer.

add_weight([shape, initializer, dtype, ...])

Add a weight variable to the layer.

build_from_config(config)

Builds the layer's states with the supplied config dict.

count_params()

Count the total number of scalars composing the weights.

from_config(config)

Creates an operation from its config.

get_build_config()

Returns a dictionary with the layer's input shape.

get_config()

Returns the config of the object.

get_weights()

Return the values of layer.weights as a list of NumPy arrays.

load_own_variables(store)

Loads the state of the layer.

save_own_variables(store)

Saves the state of the layer.

set_weights(weights)

Sets the values of layer.weights from a list of NumPy arrays.

stateless_call(trainable_variables, ...[, ...])

Call the layer without any side effects.

add_metric

build

call

compute_mask

compute_output_shape

compute_output_spec

quantize

quantized_build

quantized_call

symbolic_call

call(input)[source]#

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]#

MoveDimLayer#

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

Bases: Module

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()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

ChannelSum#

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

Bases: Module

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()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(inputs)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Add#

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

Bases: Module

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()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x, passed)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

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

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()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(input, passed)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Model#

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

Bases: Module

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()

Set 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, ...)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

EVACPlus#

class dipy.nn.torch.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, *[, voxsize, ...])

Wrapper function to facilitate prediction of larger dataset.

init_model

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]#
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, *, voxsize=(1, 1, 1), batch_size=None, return_affine=False, 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.

voxsizenp.ndarray or list or tuple, optional

(3,) or (batch, 3) voxel size of the T1 image.

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_affinebool, optional

Whether to return the affine matrix. Useful if the input was a file path.

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

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()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(x)

Define the computation performed at every call.

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)

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]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

HistoResDNN#

class dipy.nn.torch.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(‘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).

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.

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 Default : None

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 Default : None

new_minint or float, optional

new minimum value after normalization Default : 0

new_maxint or float, optional

new maximum value after normalization Default : 1

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

transform_img#

dipy.nn.utils.transform_img(image, affine, *, voxsize=None, considered_points='corners', init_shape=(256, 256, 256), scale=2)[source]#

Function to reshape image as an input to the model

Parameters:
imagenp.ndarray

Image to transform to voxelspace

affinenp.ndarray

Affine matrix provided by the file

voxsizenp.ndarray (3,), optional

Voxel size of the image

considered_pointsstr, optional

which points to consider when calculating the boundary of the image. If there is shearing in the affine, ‘all’ might be more accurate

init_shapelist, tuple or numpy array (3,), optional

Initial shape to transform the image to

scalefloat, optional

How much we want to scale the image

Returns:
tuple

Tuple with variables for recover_img

recover_img#

dipy.nn.utils.recover_img(image, inv_affine, mid_shape, ori_shape, offset_array, voxsize, scale, crop_vs, pad_vs)[source]#

Function to recover image from transform_img

Parameters:
imagenp.ndarray

Image to recover

inv_affinenp.ndarray

Affine matrix returned from transform_img

mid_shapenp.ndarray (3,)

shape of image returned from transform_img

ori_shapetuple (3,)

original shape of the image

offset_arraynp.ndarray

Affine matrix that was used in transform_img to translate the center

voxsizenp.ndarray (3,)

Voxel size used in transform_img

scalefloat

Scale used in transform_img

crop_vsnp.ndarray (3,2)

crop range used in transform_img

pad_vsnp.ndarray (3,2)

pad range used in transform_img

Returns:
image2np.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