unet package

unet.unet module

class unet.unet.ConvBlock(layer_idx, filters_root, kernel_size, dropout_rate, padding, activation, **kwargs)[source]

Bases: tensorflow.python.keras.engine.base_layer.Layer

call(inputs, training=None, **kwargs)[source]

This is where the layer’s logic lives.

Note here that call() method in tf.keras is little bit different from keras API. In keras API, you can pass support masking for layers as additional arguments. Whereas tf.keras has compute_mask() method to support masking.

Parameters:
  • inputs – Input tensor, or list/tuple of input tensors.
  • **kwargs – Additional keyword arguments. Currently unused.
Returns:

A tensor or list/tuple of tensors.

get_config()[source]

Returns the config of the layer.

A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration.

The config of a layer does not include connectivity information, nor the layer class name. These are handled by Network (one layer of abstraction above).

Returns:Python dictionary.
class unet.unet.CropConcatBlock(trainable=True, name=None, dtype=None, dynamic=False, **kwargs)[source]

Bases: tensorflow.python.keras.engine.base_layer.Layer

call(x, down_layer, **kwargs)[source]

This is where the layer’s logic lives.

Note here that call() method in tf.keras is little bit different from keras API. In keras API, you can pass support masking for layers as additional arguments. Whereas tf.keras has compute_mask() method to support masking.

Parameters:
  • inputs – Input tensor, or list/tuple of input tensors.
  • **kwargs – Additional keyword arguments. Currently unused.
Returns:

A tensor or list/tuple of tensors.

class unet.unet.UpconvBlock(layer_idx, filters_root, kernel_size, pool_size, padding, activation, **kwargs)[source]

Bases: tensorflow.python.keras.engine.base_layer.Layer

call(inputs, **kwargs)[source]

This is where the layer’s logic lives.

Note here that call() method in tf.keras is little bit different from keras API. In keras API, you can pass support masking for layers as additional arguments. Whereas tf.keras has compute_mask() method to support masking.

Parameters:
  • inputs – Input tensor, or list/tuple of input tensors.
  • **kwargs – Additional keyword arguments. Currently unused.
Returns:

A tensor or list/tuple of tensors.

get_config()[source]

Returns the config of the layer.

A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration.

The config of a layer does not include connectivity information, nor the layer class name. These are handled by Network (one layer of abstraction above).

Returns:Python dictionary.
unet.unet.build_model(nx: Optional[int] = None, ny: Optional[int] = None, channels: int = 1, num_classes: int = 2, layer_depth: int = 5, filters_root: int = 64, kernel_size: int = 3, pool_size: int = 2, dropout_rate: int = 0.5, padding: str = 'valid', activation: Union[str, Callable] = 'relu') → tensorflow.python.keras.engine.training.Model[source]

Constructs a U-Net model

Parameters:
  • nx – (Optional) image size on x-axis
  • ny – (Optional) image size on y-axis
  • channels – number of channels of the input tensors
  • num_classes – number of classes
  • layer_depth – total depth of unet
  • filters_root – number of filters in top unet layer
  • kernel_size – size of convolutional layers
  • pool_size – size of maxplool layers
  • dropout_rate – rate of dropout
  • padding – padding to be used in convolutions
  • activation – activation to be used
Returns:

A TF Keras model

unet.unet.finalize_model(model: tensorflow.python.keras.engine.training.Model, loss: Union[Callable, str, None] = <function categorical_crossentropy>, optimizer: Optional = None, metrics: Optional[List[Union[Callable, str]]] = None, dice_coefficient: bool = True, auc: bool = True, mean_iou: bool = True, **opt_kwargs)[source]

Configures the model for training by setting, loss, optimzer, and tracked metrics

Parameters:
  • model – the model to compile
  • loss – the loss to be optimized. Defaults to categorical_crossentropy
  • optimizer – the optimizer to use. Defaults to Adam
  • metrics – List of metrics to track. Is extended by crossentropy and accuracy
  • dice_coefficient – Flag if the dice coefficient metric should be tracked
  • auc – Flag if the area under the curve metric should be tracked
  • mean_iou – Flag if the mean over intersection over union metric should be tracked
  • opt_kwargs – key word arguments passed to default optimizer (Adam), e.g. learning rate

unet.trainer module

class unet.trainer.Trainer(name: Optional[str] = 'unet', log_dir_path: Union[pathlib.Path, str, None] = None, checkpoint_callback: Union[tensorflow.python.keras.callbacks.TensorBoard, bool, None] = True, tensorboard_callback: Union[tensorflow.python.keras.callbacks.TensorBoard, bool, None] = True, tensorboard_images_callback: Union[unet.callbacks.TensorBoardImageSummary, bool, None] = True, callbacks: Optional[List[tensorflow.python.keras.callbacks.Callback]] = None, learning_rate_scheduler: Union[unet.schedulers.SchedulerType, tensorflow.python.keras.callbacks.Callback, None] = None, **scheduler_opts)[source]

Bases: object

Fits a given model to a datasets and configres learning rate schedulers and various callbacks

Parameters:
  • name – Name of the model, used to build the target log directory if no explicit path is given
  • log_dir_path – Path to the directory where the model and tensorboard summaries should be stored
  • checkpoint_callback – Flag if checkpointing should be enabled. Alternatively a callback instance can be passed
  • tensorboard_callback – Flag if information should be stored for tensorboard. Alternatively a callback instance can be passed
  • tensorboard_images_callback – Flag if intermediate predictions should be stored in Tensorboard. Alternatively a callback instance can be passed
  • callbacks – List of additional callbacks
  • learning_rate_scheduler – The learning rate to be used. Either None for a constant learning rate, a Callback or a SchedulerType
  • scheduler_opts – Further kwargs passed to the learning rate scheduler
evaluate(model: tensorflow.python.keras.engine.training.Model, test_dataset: Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None, shape: Tuple[int, int, int] = None)[source]
fit(model: tensorflow.python.keras.engine.training.Model, train_dataset: tensorflow.python.data.ops.dataset_ops.DatasetV2, validation_dataset: Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None, test_dataset: Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None, epochs=10, batch_size=1, **fit_kwargs)[source]

Fits the model to the given data

Parameters:
  • model – The model to be fit
  • train_dataset – The dataset used for training
  • validation_dataset – (Optional) The dataset used for validation
  • test_dataset – (Optional) The dataset used for test
  • epochs – Number of epochs
  • batch_size – Size of minibatches
  • fit_kwargs – Further kwargs passd to model.fit
unet.trainer.build_log_dir_path(root: Optional[str] = 'unet') → str[source]

unet.utils module

unet.utils.crop_image_and_label_to_shape(shape: Tuple[int, int, int])[source]
unet.utils.crop_labels_to_shape(shape: Tuple[int, int, int])[source]
unet.utils.crop_to_shape(data, shape: Tuple[int, int, int])[source]

Crops the array to the given image shape by removing the border

Parameters:
  • data – the array to crop, expects a tensor of shape [batches, nx, ny, channels]
  • shape – the target shape [batches, nx, ny, channels]
unet.utils.to_rgb(img: numpy.array)[source]

Converts the given array into a RGB image and normalizes the values to [0, 1). If the number of channels is less than 3, the array is tiled such that it has 3 channels. If the number of channels is greater than 3, only the first 3 channels are used

Parameters:img – the array to convert [bs, nx, ny, channels]
Returns img:the rgb image [bs, nx, ny, 3]

Submodules

unet.callbacks module

class unet.callbacks.TensorBoardImageSummary(name, logdir: str, dataset: tensorflow.python.data.ops.dataset_ops.DatasetV2, max_outputs: int = None)[source]

Bases: tensorflow.python.keras.callbacks.Callback

combine_to_image(images: numpy.array, labels: numpy.array, predictions: numpy.array) → numpy.array[source]

Concatenates the three tensors to one RGB image

Parameters:
  • images – images tensor, shape [None, nx, ny, channels]
  • labels – labels tensor, shape [None, nx, ny, 1] for sparse or [None, nx, ny, classes] for one-hot
  • predictions – labels tensor, shape [None, nx, ny, classes]
Returns:

image tensor, shape [None, nx, 3 x ny, 3]

on_epoch_end(epoch, logs=None)[source]

Called at the end of an epoch.

Subclasses should override for any actions to run. This function should only be called during TRAIN mode.

Parameters:
  • epoch – Integer, index of epoch.
  • logs
    Dict, metric results for this training epoch, and for the
    validation epoch if validation is performed. Validation result keys are prefixed with val_. For training epoch, the values of the

    Model’s metrics are returned. Example : {‘loss’: 0.2, ‘acc’: 0.7}.

class unet.callbacks.TensorBoardWithLearningRate(log_dir='logs', histogram_freq=0, write_graph=True, write_images=False, update_freq='epoch', profile_batch=2, embeddings_freq=0, embeddings_metadata=None, **kwargs)[source]

Bases: tensorflow.python.keras.callbacks.TensorBoard

on_epoch_end(batch, logs=None)[source]

Runs metrics and histogram summaries at epoch end.

unet.metrics module

unet.metrics.dice_coefficient(y_true, y_pred, smooth=1)[source]
unet.metrics.mean_iou(y_true, y_pred)[source]

unet.schedulers module

class unet.schedulers.LearningRateScheduler(schedule: Callable[[int], float], steps_per_epoch: int, verbose=0)[source]

Bases: tensorflow.python.keras.callbacks.Callback

Learning rate scheduler. :param schedule: a function that takes an step index as input

(integer, indexed from 0) and returns a new learning rate as output (float).
Parameters:verbose – int. 0: quiet, 1: update messages.
on_epoch_end(epoch, logs=None)[source]

Called at the end of an epoch.

Subclasses should override for any actions to run. This function should only be called during TRAIN mode.

Parameters:
  • epoch – Integer, index of epoch.
  • logs
    Dict, metric results for this training epoch, and for the
    validation epoch if validation is performed. Validation result keys are prefixed with val_. For training epoch, the values of the

    Model’s metrics are returned. Example : {‘loss’: 0.2, ‘acc’: 0.7}.

on_train_batch_begin(batch, logs=None)[source]

Called at the beginning of a training batch in fit methods.

Subclasses should override for any actions to run.

Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.

Parameters:
  • batch – Integer, index of batch within the current epoch.
  • logs – Dict, contains the return value of model.train_step. Typically, the values of the Model’s metrics are returned. Example: {‘loss’: 0.2, ‘accuracy’: 0.7}.
on_train_batch_end(batch, logs=None)[source]

Called at the end of a training batch in fit methods.

Subclasses should override for any actions to run.

Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.

Parameters:
  • batch – Integer, index of batch within the current epoch.
  • logs – Dict. Aggregated metric results up until this batch.
class unet.schedulers.SchedulerType[source]

Bases: enum.Enum

An enumeration.

WARMUP_LINEAR_DECAY = 'warmup-linear-decay'
class unet.schedulers.WarmupLinearDecaySchedule(warmup_steps, total_steps, learning_rate, min_lr=0.0)[source]

Bases: object

Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over warmup_steps training steps. Linearly decreases learning rate from 1. to 0. over remaining t_total - warmup_steps steps.

unet.schedulers.get(scheduler: unet.schedulers.SchedulerType, train_dataset_size: int, learning_rate: float, **hyperparams)[source]

Module contents