TFUNetHelper Module¶
Utilities and helper functions for building and working with UNet-style models in TensorFlow.
- HMB.TFUNetHelper.PreparePredTensorToNumpy(predTensor, doScale2Image=False)[source]¶
Utility to convert model output tensor after the sigmoid/softmax activation to a numpy array of class indices. It can be used also with the original mask tensor if it is already in the correct format, as it handles squeezing and type conversion.
- Short summary:
Takes the raw output tensor from a TensorFlow model (after activation) and processes it to produce a 2D or 3D numpy array of class indices or binary masks. This involves squeezing unnecessary dimensions, converting boolean masks to integers if needed, and ensuring the final output is in the correct format for evaluation or visualization.
- Parameters:
predTensor (tensorflow.Tensor) – The raw output tensor from the model after activation, expected to be of shape [B, H, W, C] or [B, H, W, 1].
doScale2Image (bool) – If True, applies a threshold to convert probabilities to binary mask and scales to 0..255. Default False.
- Returns:
Numpy array of shape [B, H, W] or [B, H, W, C] containing class indices or the scaled image.
- Return type:
- class HMB.TFUNetHelper.DoubleConv(inChannels, outChannels)[source]¶
Bases:
LayerDouble convolution block used throughout the U-Net encoder and decoder. Two consecutive 3x3 Conv2D layers each followed by normalization and ReLU activation used as a basic encoder/decoder building block.
Initializes a double convolution block with two Conv2D layers, each followed by BatchNormalization and ReLU activation.
- Parameters:
- __init__(inChannels, outChannels)[source]¶
Initializes a double convolution block with two Conv2D layers, each followed by BatchNormalization and ReLU activation.
- call(x, training=False)[source]¶
Forward pass through the double convolution block.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChannels].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Output feature map of shape [B, H, W, outChannels].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ConfigConv(inChannels, outChannels, norm='batch', dropout=0.0, residual=False)[source]¶
Bases:
LayerConfigurable double-convolution block with selectable normalization, dropout and residual option. A DoubleConv-like block with optional normalization type, dropout, and an optional residual connection when input and output channels match.
Initializes a configurable convolutional block with two Conv2D layers, optional normalization, dropout, and residual connection.
- Parameters:
- __init__(inChannels, outChannels, norm='batch', dropout=0.0, residual=False)[source]¶
Initializes a configurable convolutional block with two Conv2D layers, optional normalization, dropout, and residual connection.
- call(x, training=False)[source]¶
Forward pass through the configurable convolutional block.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChannels].
training (bool) – Whether the model is in training mode (affects normalization and dropout).
- Returns:
Output tensor of shape [B, H, W, outChannels], optionally with residual addition.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ResidualBlock(inChannels, outChannels)[source]¶
Bases:
LayerResidual convolutional block. Two conv->BatchNorm->ReLU layers with an identity skip connection. A 1x1 projection is applied to the identity when the number of channels differs.
Initializes a residual convolutional block with two Conv2D layers, each followed by BatchNormalization and ReLU activation.
- Parameters:
- __init__(inChannels, outChannels)[source]¶
Initializes a residual convolutional block with two Conv2D layers, each followed by BatchNormalization and ReLU activation.
- call(x, training=False)[source]¶
Forward pass through the residual convolutional block.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChannels].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Output tensor of shape [B, H, W, outChannels] after residual addition and activation.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.AttentionGate(F_g, F_l, F_int)[source]¶
Bases:
LayerAttention gating module for skip connections. Lightweight gating unit that computes attention coefficients for encoder skip features using a gating signal from the decoder, improving focus on relevant spatial locations.
Initializes an attention gate with convolutional layers to compute attention coefficients.
- Parameters:
- __init__(F_g, F_l, F_int)[source]¶
Initializes an attention gate with convolutional layers to compute attention coefficients.
- call(g, x, training=False)[source]¶
Forward pass through the attention gate.
- Parameters:
g (tensorflow.Tensor) – Gating signal from the decoder of shape [B, H, W, F_g].
x (tensorflow.Tensor) – Skip connection from the encoder of shape [B, H, W, F_l].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Reweighted skip features of shape [B, H, W, F_l] after applying attention coefficients.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.DepthwiseSeparableConv(inChannels, outChannels)[source]¶
Bases:
LayerDepthwise separable convolution block. Implements a depthwise convolution followed by a pointwise convolution, used to reduce parameter counts and computation in lightweight models.
Initializes a depthwise separable convolution block with a SeparableConv2D layer, BatchNormalization, and ReLU activation.
- Parameters:
- class HMB.TFUNetHelper.SEBlock(channels, reduction=16)[source]¶
Bases:
LayerSqueeze-and-Excitation (SE) block. Performs global channel-wise pooling followed by a small bottleneck MLP that produces per-channel scaling weights applied to the input.
Initializes a Squeeze-and-Excitation block with global average pooling and two dense layers for channel recalibration.
- Parameters:
- class HMB.TFUNetHelper.MultiResBlock(inChans, outChans, alpha=1.67)[source]¶
Bases:
LayerMulti-resolution convolution block capturing features at multiple receptive fields. Parallel convolutions with different receptive fields followed by channel weighting to capture multi-scale context within a single block while controlling parameter growth.
Initializes a MultiRes block with three parallel convolutional paths (3x3, 5x5, 7x7) and a shortcut connection.
- Parameters:
- __init__(inChans, outChans, alpha=1.67)[source]¶
Initializes a MultiRes block with three parallel convolutional paths (3x3, 5x5, 7x7) and a shortcut connection.
- call(x, training=False)[source]¶
Forward pass through the MultiRes block.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChans].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Output tensor of shape [B, H, W, outChans].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.DenseBlock(inChans, numLayers=4, growthRate=32, bnSize=4)[source]¶
Bases:
LayerDense connectivity block with bottleneck layers for parameter efficiency. Stacks multiple bottleneck layers where each layer receives feature maps from all preceding layers as input, promoting feature reuse and gradient flow.
Initializes a Dense block with a specified number of bottleneck layers, growth rate, and bottleneck size.
- Parameters:
- __init__(inChans, numLayers=4, growthRate=32, bnSize=4)[source]¶
Initializes a Dense block with a specified number of bottleneck layers, growth rate, and bottleneck size.
- call(x, training=False)[source]¶
Forward pass through the Dense block, progressively concatenating features from all previous layers.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChans].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Output tensor of shape [B, H, W, inChans + numLayers * growthRate].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.RecurrentConvLayer(channels, t=2)[source]¶
Bases:
LayerRecurrent convolutional layer with internal state feedback. Applies convolution repeatedly for T timesteps where each step receives feedback from its previous output, enabling iterative refinement of spatial features.
Initializes a recurrent convolutional layer with shared convolutional weights and batch normalization.
- Parameters:
- __init__(channels, t=2)[source]¶
Initializes a recurrent convolutional layer with shared convolutional weights and batch normalization.
- call(x, training=False)[source]¶
Forward pass through the recurrent convolutional layer, iteratively refining features over T timesteps.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, channels].
training (bool) – Whether the model is in training mode (affects BatchNormalization).
- Returns:
Output tensor of shape [B, H, W, channels] after T recurrent iterations.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ASPP(inChans, outChans, dilations=(1, 6, 12, 18))[source]¶
Bases:
LayerAtrous Spatial Pyramid Pooling for multi-scale context aggregation. Parallel dilated convolutions at multiple rates plus image pooling to capture objects at different scales within a single feature map.
Initializes the ASPP module with parallel convolutional branches and image pooling.
- Parameters:
- __init__(inChans, outChans, dilations=(1, 6, 12, 18))[source]¶
Initializes the ASPP module with parallel convolutional branches and image pooling.
- call(x, training=False)[source]¶
Forward pass through the ASPP module, aggregating multi-scale features and projecting to output channels.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, inChans].
training (bool) – Whether the model is in training mode (affects BatchNormalization and Dropout).
- Returns:
Output tensor of shape [B, H, W, outChans] after multi-scale feature aggregation.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.PatchEmbedding(inChans, embedDim=256, patchSize=4)[source]¶
Bases:
Layer2D image to patch embedding with optional positional encoding. Converts input image into non-overlapping patches via convolutional projection and flattens them into a sequence for transformer processing.
Initializes a patch embedding layer that projects an input image into a sequence of patch embeddings using a Conv2D layer.
- Parameters:
- __init__(inChans, embedDim=256, patchSize=4)[source]¶
Initializes a patch embedding layer that projects an input image into a sequence of patch embeddings using a Conv2D layer.
- class HMB.TFUNetHelper.TransformerBlock(embedDim, numHeads=8, mlpRatio=4.0, dropout=0.1)[source]¶
Bases:
LayerStandard transformer encoder block with pre-normalization. Multi-head self-attention followed by position-wise feed-forward network with layer normalization and residual connections before each sub-layer.
Initializes a transformer encoder block with multi-head self-attention and feed-forward MLP.
- Parameters:
- __init__(embedDim, numHeads=8, mlpRatio=4.0, dropout=0.1)[source]¶
Initializes a transformer encoder block with multi-head self-attention and feed-forward MLP.
- Parameters:
- call(x, training=False)[source]¶
Forward pass through the transformer encoder block, applying pre-normalization, multi-head self-attention, and feed-forward MLP with residual connections.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, N, embedDim].
training (bool) – Whether the model is in training mode (affects Dropout).
- Returns:
Output tensor of shape [B, N, embedDim] after attention and MLP processing.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ChannelAttn(channels, reduction=16)[source]¶
Bases:
LayerChannel attention branch of CBAM using squeeze-and-excitation. Global average and max pooling followed by shared MLP to compute channel-wise attention weights that rescale feature channels.
Initializes a channel attention block with global pooling and a two-layer MLP for channel recalibration.
- Parameters:
- class HMB.TFUNetHelper.SpatialAttn(kernelSize=7)[source]¶
Bases:
LayerSpatial attention branch of CBAM using channel aggregation. Channel-wise average and max pooling followed by convolution to compute spatial attention map that highlights important regions in feature maps.
Initializes a spatial attention block with a convolutional layer to compute spatial attention weights.
- Parameters:
kernelSize (int) – Size of the convolution kernel for spatial attention. Default 7.
- class HMB.TFUNetHelper.CBAM(channels, reduction=16)[source]¶
Bases:
LayerConvolutional Block Attention Module (channel + spatial attention). Sequential channel attention followed by spatial attention to adaptively refine feature maps along both channel and spatial dimensions.
Initializes a CBAM module with channel and spatial attention branches.
- Parameters:
- __init__(channels, reduction=16)[source]¶
Initializes a CBAM module with channel and spatial attention branches.
- call(x)[source]¶
Forward pass through the CBAM module, applying channel attention followed by spatial attention.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, channels].
- Returns:
Output tensor of shape [B, H, W, channels] after attention refinement.
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.UNet(inputChannels=3, numClasses=2, baseChannels=64, useConvTranspose2d=True)[source]¶
Bases:
ModelStandard 2D U-Net implemented with tf.keras. A typical encoder-decoder U-Net with four downsampling stages, a bottleneck, and four symmetric upsampling stages. Supports learned transpose convolution upsampling or bilinear upsampling followed by 1x1 projection.
- Parameters:
- Variables:
center (enc1..enc4,) – Encoder and bottleneck blocks.
dec1..dec4 (up1..up4,) – Upsampling and decoder blocks.
finalConv (tf.keras.layers.Layer) – 1x1 conv to map to logits.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.DynamicUNet(inputChannels=3, numClasses=2, baseChannels=64, depth=4, upMode='transpose', norm='batch', dropout=0.0, residual=False)[source]¶
Bases:
ModelConfigurable U-Net implementation with variable depth.
- Short summary:
Generalized U-Net that allows customizing depth, normalization type, dropout, residual usage and upsampling mode. Useful for experimenting with architectures without duplicating code.
- Parameters:
inputChannels (int) – Number of input channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
baseChannels (int) – Base filter count. Default 64.
depth (int) – Number of downsampling stages. Default 4.
upMode (str) – “transpose” or “bilinear” upsampling. Default “transpose”.
norm (str) – Normalization type: “batch”|”instance”|”none”. Default “batch”.
dropout (float) – Dropout probability applied inside config blocks. Default 0.0.
residual (bool) – Whether to use residual connections inside blocks. Default False.
- Variables:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.AttentionUNet(*args, **kwargs)[source]¶
Bases:
ModelAttention U-Net variant with gating on skip connections.
- Short summary:
Applies attention gating to encoder skip features before merging them into the decoder, improving localization and suppressing irrelevant responses in the skip maps.
- Parameters:
- Variables:
center (enc1..enc4,) – Encoder/bottleneck blocks.
att1..att4 (AttentionGate) – Attention gating modules for skips.
dec1..dec4 (up1..up4,) – Decoder modules.
finalConv (tf.keras.layers.Layer) – 1x1 conv mapping to logits.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.MobileUNet(*args, **kwargs)[source]¶
Bases:
ModelLightweight U-Net using depthwise separable convolutions.
- Short summary:
Efficient U-Net variant that replaces standard convolutions with depthwise separable convolutions to reduce parameters and compute.
- Parameters:
- Variables:
center (enc1..enc4,) – Encoder and bottleneck sequences.
dec1..dec4 (up1..up4,) – Decoder modules.
finalConv (tensorflow.keras.layers.Layer) – 1x1 conv for logits.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ResidualUNet(*args, **kwargs)[source]¶
Bases:
ModelResidual U-Net variant built from ResidualBlock components.
- Short summary:
A U-Net where encoder and decoder stages use residual blocks to ease optimization and improve gradient flow for deeper models.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.SEUNet(*args, **kwargs)[source]¶
Bases:
ModelU-Net with Squeeze-and-Excitation modules applied to encoder and center.
- Short summary:
Inserts SE blocks after encoder and center blocks to recalibrate channel-wise responses, improving representational expressiveness.
- Parameters:
inputChannels (int) – Number of input channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
baseChannels (int) – Base number of filters. Default 64.
useConvTranspose2d (bool) – If True use learned transpose upsampling.
seReduction (int) – Reduction ratio for SE bottleneck. Default 16.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ResidualAttentionUNet(*args, **kwargs)[source]¶
Bases:
ModelResidual U-Net combined with Attention Gates.
- Short summary:
A U-Net variant that composes residual blocks in the encoder/decoder and applies attention gating on the skip connections to focus decoder features.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.MultiResUNet(*args, **kwargs)[source]¶
Bases:
ModelMultiResUNet using MultiResBlock at each stage.
- Short summary:
Uses MultiResBlock modules to capture multi-scale features within each encoder/decoder stage while keeping parameter growth under control.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.DenseUNet(*args, **kwargs)[source]¶
Bases:
ModelDenseUNet integrating DenseBlocks and transition convolutions.
- Short summary:
Encoder built from DenseBlocks with 1x1 transition convolutions to control channel dimensionality, producing feature reuse and improved gradient flow.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.R2UNet(*args, **kwargs)[source]¶
Bases:
ModelRecurrent Residual U-Net using recurrent convolution layers.
- Short summary:
Introduces recurrent convolutional layers (RCL) that iteratively refine features inside each encoder stage, useful for capturing contextual information while keeping model size modest.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.ASPPUNet(*args, **kwargs)[source]¶
Bases:
ModelU-Net with ASPP at the bottleneck.
- Short summary:
Incorporates Atrous Spatial Pyramid Pooling (ASPP) at the bottleneck to capture multi-scale context before upsampling in the decoder.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.TransUNet(*args, **kwargs)[source]¶
Bases:
ModelTransformer-enhanced U-Net with a small transformer stack at the bottleneck.
- Short summary:
Applies a patch embedding on the bottleneck features and processes them with a small transformer encoder stack, then projects back to spatial features for decoding. Useful to capture long-range dependencies.
- Parameters:
inputChannels (int) – Number of input channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
baseChannels (int) – Base number of filters. Default 64.
embedDim (int) – Embedding dimension for transformer. Default 256.
numHeads (int) – Number of attention heads. Default 8.
numEncoders (int) – Number of transformer encoder blocks. Default 2.
useConvTranspose2d (bool) – Use Conv2DTranspose when True.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.CBAMUNet(*args, **kwargs)[source]¶
Bases:
ModelU-Net variant applying CBAM attention to encoder skip features.
- Short summary:
Uses the Convolutional Block Attention Module (CBAM) to refine encoder skip features via channel and spatial attention before merging them into the decoder.
- Parameters:
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.EfficientUNet(*args, **kwargs)[source]¶
Bases:
ModelEfficient wrapper around MobileUNet.
- Short summary:
A thin wrapper that exposes the MobileUNet as an “efficient” option in the factory while keeping the same API.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.BoundaryAwareUNet(*args, **kwargs)[source]¶
Bases:
ModelBoundary-aware U-Net with explicit boundary detection branch.
- Short summary:
A dual-branch architecture with a main segmentation decoder and a lighter boundary decoder producing an auxiliary boundary map. Useful for losses that combine segmentation and boundary supervision.
- Parameters:
inputChannels (int) – Number of input channels. Default 3.
numClasses (int) – Number of segmentation classes. Default 2.
baseChannels (int) – Base number of filters. Default 64.
useConvTranspose2d (bool) – Use Conv2DTranspose when True.
boundaryWeight (float) – Weighting factor for combining boundary predictions. Default 0.5.
- Returns:
(segmentation_logits, boundary_map)
- Return type:
Tuple[tensorflow.Tensor, tensorflow.Tensor]
- class HMB.TFUNetHelper.VNet(inputSize=(256, 256, 1), kernelInitializer='he_normal', dropoutRatio=0.0, dropoutType='spatial', activation='relu', applyBatchNorm=False, concatenateType='concatenate', noOfLevels=5, numClasses=1)[source]¶
Bases:
ModelV-Net style residual encoder-decoder implemented as a lazily-built Model subclass.
This class preserves the original functional builder behaviour but exposes it as a tf.keras.Model subclass so it matches the other model classes in this module. The internal functional model is constructed on first call using the same building logic as the previous functional VNet builder.
- Parameters:
inputSize (tuple) – Input size (H, W, C). Supports None for dynamic spatial dimensions. Default (256, 256, 1).
kernelInitializer (str) – Kernel initializer for convolutional layers. Default “he_normal”.
dropoutRatio (float) – Dropout ratio for residual blocks. Default 0.0 (no dropout).
dropoutType (str) – Type of dropout to apply (“spatial” or “standard”). Default “spatial”.
activation (str) – Activation function to use. Default “relu”.
applyBatchNorm (bool) – Whether to apply batch normalization after convolutions. Default False.
concatenateType (str) – Method to merge skip connections (“concatenate” or “add”). Default “concatenate”.
noOfLevels (int) – Number of encoder/decoder levels. Default 5.
numClasses (int) – Number of output classes for the final segmentation head. Default 1.
- Returns:
Logits tensor of shape [B, H, W, numClasses].
- Return type:
tensorflow.Tensor
- class HMB.TFUNetHelper.SegNet(*args, **kwargs)[source]¶
Bases:
ModelSegNet architecture for multi-class semantic segmentation (Class-based Implementation). Memory-efficient encoder-decoder network supporting VGG16, ResNet50, MobileNetV2, or Vanilla backbones. Uses Functional API internally for optimal graph construction and memory usage.
Initialize SegNet with specified configuration.
- Parameters:
inputChannels (int) – Number of input image channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
level (int) – Decoder starting stage (1-4). Higher levels use deeper features.
encoder (str) – Backbone type: “VGG16”, “ResNet50”, “MobileNet”, or “Vanilla”.
inputSize (tuple, Optional) – Fixed input shape (H, W, C). None = dynamic.
useBias (bool) – Whether Conv layers use bias. Default False (BN compatible).
- __init__(inputChannels=3, numClasses=2, level=3, encoder='VGG16', inputSize=None, useBias=False)[source]¶
Initialize SegNet with specified configuration.
- Parameters:
inputChannels (int) – Number of input image channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
level (int) – Decoder starting stage (1-4). Higher levels use deeper features.
encoder (str) – Backbone type: “VGG16”, “ResNet50”, “MobileNet”, or “Vanilla”.
inputSize (tuple, Optional) – Fixed input shape (H, W, C). None = dynamic.
useBias (bool) – Whether Conv layers use bias. Default False (BN compatible).
- BuildEncoderLayers()[source]¶
Initialize encoder backbone layers based on selected type.
- Raises:
ValueError – If an unsupported encoder type is specified.
- InitVggEncoder()[source]¶
VGG16-style encoder: 4 blocks returning feature levels at strides 2,4,8,16.
- RunMobilenetEncoder(x, training=False)[source]¶
Execute MobileNetV2 encoder and return 4 feature levels.
- RunDecoder(x, training=False)[source]¶
Execute decoder pathway from selected level.
- Parameters:
x (tensorflow.Tensor) – Input tensor from encoder level.
training (bool) – Whether the model is in training mode (affects BatchNorm). Default False.
- Returns:
Output tensor after decoder processing.
- Return type:
tensorflow.Tensor
r
- BuildFunctionalModel()[source]¶
Build static functional model for fixed input shapes (optimization).
- call(x, training=False)[source]¶
Forward pass: route to functional model if fixed shape, else dynamic.
- Parameters:
x (tensorflow.Tensor) – Input tensor of shape [B, H, W, C].
training (bool) – Whether the model is in training mode (affects BatchNorm and Dropout). Default False.
- Returns:
Output tensor of shape [B, H, W, numClasses] with probabilities or logits depending on configuration.
- Return type:
tensorflow.Tensor
- build(input_shape=None)[source]¶
Explicitly build model weights (useful for dynamic shapes).
- Parameters:
input_shape (tuple, Optional) – Input shape to build the model. If None, a dynamic shape with known channels is used.
- HMB.TFUNetHelper.CreateUNet(inputChannels=3, numClasses=2, baseChannels=64, depth=4, upMode='transpose', norm='batch', dropout=0.0, residual=False, modelType='dynamic')[source]¶
Extended factory that supports the UNet family and related variants.
- Short summary:
Returns an instantiated tf.keras.Model implementing the requested UNet variant selected by the case-insensitive modelType string. This factory exposes the common constructor arguments used by the various implementations and forwards them to the selected model. Models in this file follow TensorFlow’s NHWC convention (batch, height, width, channels).
- Parameters:
inputChannels (int) – Number of input image channels. Default 3.
numClasses (int) – Number of output classes. Default 2.
baseChannels (int) – Base filter count used by most architectures. Default 64.
depth (int) – Depth / number of downsampling stages for dynamic variants. Default 4.
upMode (str) – “transpose” or “bilinear” upsampling selection. Default “transpose”.
norm (str) – Normalization mode for configurable blocks: “batch” | “instance” | “none”. Default “batch”.
dropout (float) – Dropout probability passed to configurable blocks. Default 0.0.
residual (bool) – Whether to enable residual connections where supported. Default False.
modelType (str) – Case-insensitive model selection string (e.g. “dynamic”, “UNet”, “ASPPUNet”).
- Returns:
Instantiated model ready for training or inference. The returned model accepts NHWC inputs and produces logits in NHWC format (shape [B, H, W, C]).
- Return type:
tensorflow.keras.Model
Notes
If an unrecognized modelType is provided the function falls back to the DynamicUNet configuration. Use the names exposed in AVAILABLE_UNETS or the CamelCase class names when calling GetUNetModel.
- HMB.TFUNetHelper.GetUNetModel(modelName, inputChannels, numClasses, baseChannels=64)[source]¶
Factory helper to instantiate a specific UNet variant by its CamelCase class name.
- Short summary:
Convenience function that maps a model class name (exact CamelCase string) to the corresponding tf.keras.Model constructor in this module and returns an instantiated model. This is useful when model names are provided from configuration files or command-line arguments.
- Parameters:
modelName (str) – Exact CamelCase name of the desired model class (e.g. “UNet”, “TransUNet”).
inputChannels (int) – Number of input channels to construct the model with.
numClasses (int) – Number of output classes for the model.
baseChannels (int) – Base channel count used by many model constructors. Default 64.
- Returns:
Instantiated model corresponding to modelName.
- Return type:
tensorflow.keras.Model
- Raises:
ValueError – If modelName is not recognized among the known UNet class names in this module.