Skip to content

amc_postprocess

amc_postprocess(pred_, gt)

Post-process predictions by aligning labels and computing confusion matrix. This function performs Align-Mask-Confusion (AMC) post-processing on predicted labels to optimally align them with ground truth labels and compute the confusion matrix.

Parameters:

Name Type Description Default
pred_ ndarray

Array of predicted labels

required
gt ndarray

Array of ground truth labels

required

Returns:

Name Type Description
aligned_pred ndarray

Predictions with labels optimally aligned to ground truth

conf_mat ndarray

Confusion matrix computed from aligned predictions

conf_mat_labels ndarray

Union of unique labels from ground truth and predictions

Notes

The function assumes zero values represent unlabeled data points. Prediction labels are automatically shifted by +1 during processing to avoid conflicts with the zero-value convention for unlabeled points.

Examples:

>>> import numpy as np
>>> # Example with 3 classes and some unlabeled points (zeros)
>>> gt = np.array([1, 2, 0, 3, 1, 2])
>>> pred = np.array([2, 3, 0, 1, 2, 3])
>>> aligned_pred, conf_mat, labels = amc_postprocess(pred, gt)
>>> print("Aligned predictions:", aligned_pred)
Aligned predictions: [1 2 0 3 1 2]
>>> print("Confusion matrix:")
>>> print(conf_mat)
[[2 0 0]
 [0 2 0]
 [0 0 1]]
>>> print("Labels:", labels)
Labels: [1 2 3]
Source code in mheatmap/_amc_postprocess.py
def amc_postprocess(
    pred_: np.ndarray, gt: np.ndarray
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """`amc_postprocess(pred_, gt)`

    Post-process predictions by aligning labels and computing confusion matrix.
    This function performs Align-Mask-Confusion (AMC) post-processing on predicted labels
    to optimally align them with ground truth labels and compute the confusion matrix.

    Parameters
    ----------
    pred_ : np.ndarray
        Array of predicted labels
    gt : np.ndarray
        Array of ground truth labels

    Returns
    -------
    aligned_pred : np.ndarray
        Predictions with labels optimally aligned to ground truth

    conf_mat : np.ndarray
        Confusion matrix computed from aligned predictions

    conf_mat_labels : np.ndarray
        Union of unique labels from ground truth and predictions

    Notes
    -----
    The function assumes zero values represent unlabeled data points. Prediction
    labels are automatically shifted by +1 during processing to avoid conflicts
    with the zero-value convention for unlabeled points.

    Examples
    --------
    >>> import numpy as np
    >>> # Example with 3 classes and some unlabeled points (zeros)
    >>> gt = np.array([1, 2, 0, 3, 1, 2])
    >>> pred = np.array([2, 3, 0, 1, 2, 3])
    >>> aligned_pred, conf_mat, labels = amc_postprocess(pred, gt)
    >>> print("Aligned predictions:", aligned_pred)
    Aligned predictions: [1 2 0 3 1 2]
    >>> print("Confusion matrix:")
    >>> print(conf_mat)
    [[2 0 0]
     [0 2 0]
     [0 0 1]]
    >>> print("Labels:", labels)
    Labels: [1 2 3]
    """
    amc = _AMCPostprocess(pred_, gt)
    pr = amc.get_aligned_pred()
    C = amc.get_C()
    C_labels = amc.get_C_labels()
    return pr, C, C_labels

mask_zeros_from_gt(labels, gt, mode="labels")

Mask unlabeled points (zeros) from ground truth labels.

This function handles both 1D and 2D label arrays by masking points that correspond to zeros in the ground truth labels. For image mode, it preserves the 2D spatial structure of the input.

Parameters:

Name Type Description Default
labels ndarray

Labels to be masked. Can be either: - 1D array of shape (n_samples,) - 2D array of shape (height, width) for image mode

required
gt ndarray

Ground truth labels of shape (n_samples,) containing zeros for unlabeled points

required
mode (labels, image)

Operating mode: - 'labels': Returns 1D masked array - 'image': Returns 2D masked array preserving spatial structure

'labels'

Returns:

Type Description
MaskedArray

Masked array where unlabeled points (zeros in ground truth) are masked. Shape matches input labels.

Raises:

Type Description
ValueError

If labels dimensions don't match the mode or ground truth shape

Examples:

>>> import numpy as np
>>> # Example with 1D labels
>>> labels = np.array([1, 2, 3, 4, 5])
>>> gt = np.array([1, 0, 3, 0, 5])
>>> masked = mask_zeros_from_gt(labels, gt)
>>> print(masked)
[1 3 5]
>>> # Example with 2D image labels
>>> img_labels = np.array([[1, 2], [3, 4]])
>>> img_gt = np.array([[1, 0], [3, 0]])
>>> masked_img = mask_zeros_from_gt(img_labels, img_gt, mode='image')
>>> print(masked_img)
[[1 --]
 [3 --]]
Source code in mheatmap/_amc_postprocess.py
def mask_zeros_from_gt(labels, gt, mode="labels"):
    """`mask_zeros_from_gt(labels, gt, mode="labels")`

    Mask unlabeled points (zeros) from ground truth labels.

    This function handles both 1D and 2D label arrays by masking points that correspond
    to zeros in the ground truth labels. For image mode, it preserves the 2D spatial
    structure of the input.

    Parameters
    ----------
    labels : numpy.ndarray
        Labels to be masked. Can be either:
        - 1D array of shape (n_samples,)
        - 2D array of shape (height, width) for image mode
    gt : numpy.ndarray
        Ground truth labels of shape (n_samples,) containing zeros for unlabeled points
    mode : {'labels', 'image'}, default='labels'
        Operating mode:
        - 'labels': Returns 1D masked array
        - 'image': Returns 2D masked array preserving spatial structure

    Returns
    -------
    numpy.ma.MaskedArray
        Masked array where unlabeled points (zeros in ground truth) are masked.
        Shape matches input labels.

    Raises
    ------
    ValueError
        If labels dimensions don't match the mode or ground truth shape

    Examples
    --------
    >>> import numpy as np
    >>> # Example with 1D labels
    >>> labels = np.array([1, 2, 3, 4, 5])
    >>> gt = np.array([1, 0, 3, 0, 5])
    >>> masked = mask_zeros_from_gt(labels, gt)
    >>> print(masked)
    [1 3 5]

    >>> # Example with 2D image labels
    >>> img_labels = np.array([[1, 2], [3, 4]])
    >>> img_gt = np.array([[1, 0], [3, 0]])
    >>> masked_img = mask_zeros_from_gt(img_labels, img_gt, mode='image')
    >>> print(masked_img)
    [[1 --]
     [3 --]]
    """
    if mode == "image":
        if len(labels.shape) != 2:
            raise ValueError("Labels must be 2D array for image mode")

        gt_image = gt.reshape(labels.shape) if labels.shape != gt.shape else gt
        mask = gt_image != 0
        return np.ma.masked_where(~mask, labels)

    elif mode == "labels":
        if labels.shape != gt.shape:
            labels = labels.reshape(-1)
            if labels.shape != gt.shape:
                raise ValueError(
                    "Labels shape must match ground truth after flattening"
                )

        mask = gt != 0
        return labels[mask]

    else:
        raise ValueError("Mode must be either 'labels' or 'image'")