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

[1]

Hu Cheng, Sophia Vinci-Booher, Jian Wang, Bradley Caron, Qiuting Wen, Sharlene Newman, and Franco Pestilli. Denoising diffusion weighted imaging data using convolutional neural networks. PLOS ONE, 17(9):1–24, September 2022. URL: https://doi.org/10.1371/journal.pone.0274396, doi:10.1371/journal.pone.0274396.

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

## Module: `nn.tf.deepn4`

Class and helper functions for fitting the DeepN4 model.

`EncoderBlock`(out_channels, kernel_size, ...) |
`DecoderBlock`(out_channels, kernel_size, ...) |
`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`(out_channels, kernel_size, strides, ...) |
`ChannelSum`() |
`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, ...) |
`DecoderBlock`(out_channels, kernel_size, ...) |
`Synb0`(*[, verbose]) | This class is intended for the Synb0 model.
`UNet3D`(input_shape) |

## Module: `nn.torch`

## Module: `nn.torch.deepn4`

Class and helper functions for fitting the DeepN4 model.

`UNet3D`(n_in, n_out) |
`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) |
`ChannelSum`() |
`Add`() |
`Block`(in_channels, out_channels, ...[, ...]) |
`Model`([model_scale]) |
`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) |
`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)

  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)

    Configure the model for training.

    Parameters:
      optimizer str or optimizer object, optional

        Name of optimizer or optimizer object.

      loss str 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.

      metrics list of metrics, optional

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

      loss_weights list 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)

    Evaluate the model on a test dataset.

    Parameters:
      x ndarray

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

      y ndarray

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

      batch_size int, optional

        Number of samples per gradient update.

      verbose int, optional

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

      steps int, optional

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

      callbacks list, optional

        List of callbacks to apply during evaluation.

      max_queue_size int, optional

        Maximum size for the generator queue.

      workers int, optional

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

      use_multiprocessing bool, optional

        If True, use process-based threading.

      return_dict bool, 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)

    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:
      x ndarray

        The input data, as an ndarray.

      y ndarray

        The target data, as an ndarray.

      batch_size int or None, optional

        Number of samples per batch of computation.

      epochs int, optional

        The number of epochs.

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

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

      callbacks list of keras.callbacks.Callback instances, optional

        List of callbacks to apply during training.

      validation_split float between 0 and 1, optional

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

      validation_data tuple (x_val, y_val) or None, optional

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

      shuffle boolean, optional

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

      initial_epoch int, optional

        Epoch at which to start training.

      steps_per_epoch int or None, optional

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

      validation_batch_size int or None, optional

        Number of samples per validation batch.

      validation_steps int or None, optional

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

      validation_freq int 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_size int, optional

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

      workers integer, optional

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

      use_multiprocessing boolean, optional

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

    Returns:
      hist object

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

  load_weights(filepath)

    Load the model weights from the specified file path.

    Parameters:
      filepath str

        The file path from which to load the weights.

  predict(x, *, batch_size=None, verbose=0, steps=None, callbacks=None)

    Generate predictions for input samples.

    Parameters:
      x ndarray

        Input samples.

      batch_size int, optional

        Number of samples per batch.

      verbose int, optional

        Verbosity mode.

      steps int, optional

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

      callbacks list, optional

        List of Keras callbacks to apply during prediction.

      max_queue_size int, optional

        Maximum size for the generator queue.

      workers int, optional

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

      use_multiprocessing bool, optional

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

    Returns:
      ndarray

        Numpy array of predictions.

  save_weights(filepath, *, overwrite=True)

    Save the weights of the model to HDF5 file format.

    Parameters:
      filepath str

        The path where the weights should be saved.

      overwrite bool,optional

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

  summary()

    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:
      summary NoneType

        the summary of the model

  train_test_split(x, y, *, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)

    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)

  Bases: `Layer`

  Methods

  call |

  call(input)

### `DecoderBlock`

class dipy.nn.tf.deepn4.DecoderBlock(out_channels, kernel_size, strides, padding)

  Bases: `Layer`

  Methods

  call |

  call(input)

### `DeepN4`

class dipy.nn.tf.deepn4.DeepN4(*, verbose=False)

  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, threshold]) | Wrapper function to facilitate prediction of larger dataset.

  load_resample |
  pad |

  References

  [2] (1,2)

  Praitayini Kanakaraj, Tianyuan Yao, Leon Y. Cai, Ho Hin Lee, Nancy R. Newlin, Michael E. Kim, Chenyu Gao, Kimberly R. Pechman, Derek Archer, Timothy Hohman, Angela Jefferson, Lori L. Beason-Held, Susan M. Resnick, Eleftherios Garyfallidis, Adam Anderson, Kurt G. Schilling, Bennett A. Landman, Daniel Moyer, The Alzheimer’s Disease Neuroimaging Initiative (ADNI), and The BIOCARD Study Team. DeepN4: Learning N4ITK Bias Field Correction for T1-weighted Images. Neuroinformatics, 22(2):193–205, April 2024. URL: https://doi.org/10.1007/s12021-024-09655-9, doi:10.1007/s12021-024-09655-9.

  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.

    Parameters:
      weights_path str

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

  load_resample(subj)
  pad(img, sz)
  predict(img, img_affine, *, voxsize=(1, 1, 1), threshold=0.5)

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

    Parameters:
      img np.ndarray

        T1 image to predict and apply bias field

      img_affine np.ndarray (4, 4)

        Affine matrix for the T1 image

      voxsize np.ndarray or list or tuple (3,), optional

        voxel size of the T1 image.

      threshold float, optional

        Threshold for cleaning the final correction field

    Returns:
      final_corrected np.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)

### `Block`

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

  Bases: `Layer`

  Methods

  call |

  call(input, passed)

### `ChannelSum`

class dipy.nn.tf.evac.ChannelSum

  Bases: `Layer`

  Methods

  call |

  call(inputs)

### `EVACPlus`

class dipy.nn.tf.evac.EVACPlus(*, verbose=False)

  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

  [3] (1,2)

  Jong Sung Park, Shreyas Fadnavis, and Eleftherios Garyfallidis. Multi-scale V-net architecture with deep feature CRF layers for brain extraction. Communications Medicine, 4(1):29, February 2024. URL: https://doi.org/10.1038/s43856-024-00452-8, doi:10.1038/s43856-024-00452-8.

  fetch_default_weights()

    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)

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

    Parameters:
      weights_path str

        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)

    Wrapper function to facilitate prediction of larger dataset.

    Parameters:
      T1 np.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

      affine np.ndarray (4, 4) or (batch, 4, 4)

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

      voxsize np.ndarray or list or tuple, optional

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

      batch_size int, 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_affine bool, optional

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

      return_prob bool, optional

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

      finalize_mask bool, optional

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

    Returns:
      pred_output np.ndarray (…) or (batch, …)

        Predicted brain mask

      affine np.ndarray (…) or (batch, …)

        affine matrix of mask only if return_affine is True

### prepare_img

dipy.nn.tf.evac.prepare_img(image)

  Function to prepare image for model input Specific to EVAC+

  Parameters:
    image np.ndarray

      Input image

  Returns:
    input_data dict

### init_model

dipy.nn.tf.evac.init_model(*, model_scale=16)

  Function to create model for EVAC+

  Parameters:
    model_scale int, optional

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

  Returns:
    model tf.keras.Model

### `HistoResDNN`

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

  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

  [4] (1,2)

  Vishwesh Nath, Kurt G. Schilling, Prasanna Parvathaneni, Colin B. Hansen, Allison E. Hainline, Yuankai Huo, Justin A. Blaber, Ilwoo Lyu, Vaibhav Janve, Yurui Gao, Iwona Stepniewska, Adam W. Anderson, and Bennett A. Landman. Deep learning reveals untapped information for local white-matter fiber reconstruction in diffusion-weighted MRI. Magnetic Resonance Imaging, 62:220–227, 2019. URL: https://doi.org/10.1016/j.mri.2019.07.012, doi:10.1016/j.mri.2019.07.012.

  fetch_default_weights()

    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)

    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_path str

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

  predict(data, gtab, *, mask=None, chunk_size=1000)

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

    Parameters:
      data np.ndarray

        DWI signal in a 4D array

      gtab GradientTable class instance

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

      mask np.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_size int, optional

        Batch size when running model prediction.

    Returns:
      pred_sh_coef np.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')

  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)

    Evaluate the model on test dataset.

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

    Parameters:
      x_test ndarray

        the x_test is the test dataset

      y_test ndarray shape=(BatchSize,)

        the y_test is the labels of the test dataset

      verbose int (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:
      evaluate List

        return list of loss value and accuracy value on test dataset

  fit(x_train, y_train, *, epochs=5)

    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_train ndarray

        the x_train is the train dataset

      y_train ndarray shape=(BatchSize,)

        the y_train is the labels of the train dataset

      epochs int (Default = 5)

        the number of epochs

    Returns:
      hist object

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

  predict(x_test)

    Predict the output from input samples.

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

    Parameters:
      x_train ndarray

        the x_test is the test dataset or input samples

    Returns:
      predict ndarray shape(TestSize,OutputSize)

        Numpy array(s) of predictions.

  summary()

    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:
      summary NoneType

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

  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)

    Evaluate the model on test dataset.

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

    Parameters:
      x_test ndarray

        the x_test is the test dataset

      y_test ndarray shape=(BatchSize,)

        the y_test is the labels of the test dataset

      verbose int (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:
      evaluate List

        return list of loss value and accuracy value on test dataset

  fit(x_train, y_train, *, epochs=5)

    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_train ndarray

        the x_train is the train dataset

      y_train ndarray shape=(BatchSize,)

        the y_train is the labels of the train dataset

      epochs int (Default = 5)

        the number of epochs

    Returns:
      hist object

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

  predict(x_test)

    Predict the output from input samples.

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

    Parameters:
      x_train ndarray

        the x_test is the test dataset or input samples

    Returns:
      predict ndarray shape(TestSize,OutputSize)

        Numpy array(s) of predictions.

  summary()

    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:
      summary NoneType

        the summary of the model

### `EncoderBlock`

class dipy.nn.tf.synb0.EncoderBlock(out_channels, kernel_size, strides, padding)

  Bases: `Layer`

  Methods

  call |

  call(input)

### `DecoderBlock`

class dipy.nn.tf.synb0.DecoderBlock(out_channels, kernel_size, strides, padding)

  Bases: `Layer`

  Methods

  call |

  call(input)

### `Synb0`

class dipy.nn.tf.synb0.Synb0(*, verbose=False)

  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

  [5]

  Kurt G. Schilling, Justin Blaber, Yuankai Huo, Allen Newton, Colin Hansen, Vishwesh Nath, Andrea T. Shafer, Owen Williams, Susan M. Resnick, Baxter Rogers, Adam W. Anderson, and Bennett A. Landman. Synthesized b0 for diffusion distortion correction (Synb0-DisCo). Magnetic Resonance Imaging, 64:62–70, 2019. Artificial Intelligence in MRI. URL: https://doi.org/10.1016/j.mri.2019.05.008, doi:10.1016/j.mri.2019.05.008.

  [6]

  Kurt G. Schilling, Justin Blaber, Colin Hansen, Leon Cai, Baxter Rogers, Adam W. Anderson, Seth Smith, Praitayini Kanakaraj, Tonia Rex, Susan M. Resnick, Andrea T. Shafer, Laurie E. Cutting, Neil Woodward, David Zald, and Bennett A. Landman. Distortion correction of diffusion weighted MRI without reverse phase-encoding scans or field-maps. PLOS ONE, 15(7):1–15, July 2020. URL: https://doi.org/10.1371/journal.pone.0236418, doi:10.1371/journal.pone.0236418.

  fetch_default_weights(idx)

    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:
      idx int

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

  load_model_weights(weights_path)

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

    Parameters:
      weights_path str

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

  predict(b0, T1, *, batch_size=None, average=True)

    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:
      b0 np.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.

      T1 np.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_size int

        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

      average bool

        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_output np.ndarray (…) or (batch, …)

        Reconstructed b-inf image(s)

### UNet3D

dipy.nn.tf.synb0.UNet3D(input_shape)

### `UNet3D`

class dipy.nn.torch.deepn4.UNet3D(n_in, n_out)

  Bases: `Module`

  Methods

  decoder_block |
  encoder_block |
  forward |

  decoder_block(in_channels, out_channels, kernel_size, stride, padding)
  encoder_block(in_channels, out_channels, kernel_size, stride, padding)
  forward(x)

### `DeepN4`

class dipy.nn.torch.deepn4.DeepN4(*, verbose=False, use_cuda=False)

  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, threshold]) | Wrapper function to facilitate prediction of larger dataset.

  load_resample |
  pad |

  References

  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.

    Parameters:
      weights_path str

        Path to the file containing the weights

  load_resample(subj)
  pad(img, sz)
  predict(img, img_affine, *, voxsize=(1, 1, 1), threshold=0.5)

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

    Parameters:
      img np.ndarray

        T1 image to predict and apply bias field

      img_affine np.ndarray (4, 4)

        Affine matrix for the T1 image

      voxsize np.ndarray or list or tuple (3,), optional

        voxel size of the T1 image.

      threshold float, optional

        Threshold for cleaning the final correction field

    Returns:
      final_corrected np.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)

  Bases: `Module`

  Methods

  forward |

  forward(x)

### `ChannelSum`

class dipy.nn.torch.evac.ChannelSum

  Bases: `Module`

  Methods

  forward |

  forward(inputs)

### `Add`

class dipy.nn.torch.evac.Add

  Bases: `Module`

  Methods

  forward |

  forward(x, passed)

### `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')

  Bases: `Module`

  Methods

  forward |

  forward(input, passed)

### `Model`

class dipy.nn.torch.evac.Model(model_scale=16)

  Bases: `Module`

  Methods

  forward |

  forward(inputs, raw_input_2, raw_input_3, raw_input_4, raw_input_5)

### `EVACPlus`

class dipy.nn.torch.evac.EVACPlus(*, verbose=False, use_cuda=False)

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

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

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

    Parameters:
      weights_path str

        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)

    Wrapper function to facilitate prediction of larger dataset.

    Parameters:
      T1 np.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.

      affine np.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.

      voxsize np.ndarray or list or tuple, optional

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

      batch_size int, 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_affine bool, optional

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

      return_prob bool, optional

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

      finalize_mask bool, optional

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

    Returns:
      pred_output np.ndarray (…) or (batch, …)

        Predicted brain mask

      affine np.ndarray (…) or (batch, …)

        affine matrix of mask only if return_affine is True

### prepare_img

dipy.nn.torch.evac.prepare_img(image)

  Function to prepare image for model input Specific to EVAC+

  Parameters:
    image np.ndarray

      Input image

  Returns:
    input_data dict

### `DenseModel`

class dipy.nn.torch.histo_resdnn.DenseModel(sh_size, num_hidden)

  Bases: `Module`

  Methods

  forward |

  forward(x)

### `HistoResDNN`

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

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

    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)

    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_path str

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

  predict(data, gtab, *, mask=None, chunk_size=1000)

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

    Parameters:
      data np.ndarray

        DWI signal in a 4D array

      gtab GradientTable class instance

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

      mask np.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_size int, optional

        Batch size when running model prediction.

    Returns:
      pred_sh_coef np.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)

  normalization function

  Parameters:
    image np.ndarray

      Image to be normalized.

    min_v int 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_v int 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_min int or float, optional

      new minimum value after normalization Default : 0

    new_max int 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)

  unnormalization function

  Parameters:
    image np.ndarray
    norm_min int or float

      minimum value of normalized image

    norm_max int or float

      maximum value of normalized image

    min_v int or float

      minimum value of unnormalized image

    max_v int 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)

  Function to reshape image as an input to the model

  Parameters:
    image np.ndarray

      Image to transform to voxelspace

    affine np.ndarray

      Affine matrix provided by the file

    voxsize np.ndarray (3,), optional

      Voxel size of the image

    considered_points str, 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_shape list, tuple or numpy array (3,), optional

      Initial shape to transform the image to

    scale float, 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)

  Function to recover image from transform_img

  Parameters:
    image np.ndarray

      Image to recover

    inv_affine np.ndarray

      Affine matrix returned from transform_img

    mid_shape np.ndarray (3,)

      shape of image returned from transform_img

    ori_shape tuple (3,)

      original shape of the image

    offset_array np.ndarray

      Affine matrix that was used in transform_img to translate the center

    voxsize np.ndarray (3,)

      Voxel size used in transform_img

    scale float

      Scale used in transform_img

    crop_vs np.ndarray (3,2)

      crop range used in transform_img

    pad_vs np.ndarray (3,2)

      pad range used in transform_img

  Returns:
    image2 np.ndarray

      Recovered image

### pad_crop

dipy.nn.utils.pad_crop(image, target_shape)

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

  Parameters:
    image np.ndarray

      Target image

    target_shape(3,)

      Target shape

  Returns:
    image np.ndarray

      Padded/cropped image

    pad_vs np.ndarray (3,2)

      Pad range used

    crop_vs np.ndarray (3,2)

      Crop range used