Skip to content

normalize_weights

yohou.utils.weighting.normalize_weights(weights)

Normalize weights so they sum to the number of elements.

Applies the convention weights * (n / sum(weights)) so the sum of the returned array equals len(weights). This preserves scale when weights are used as multiplicative factors on scores or loss values.

Parameters

Name Type Description Default
weights ndarray

Weight array. Must not sum to zero.

required

Returns

Type Description
ndarray

Normalized weight array with sum == len(weights).

Raises

Type Description
ValueError

If weights sums to zero.

Source Code

Show/Hide source
def normalize_weights(weights: np.ndarray) -> np.ndarray:
    """Normalize weights so they sum to the number of elements.

    Applies the convention ``weights * (n / sum(weights))`` so the sum of
    the returned array equals ``len(weights)``.  This preserves scale when
    weights are used as multiplicative factors on scores or loss values.

    Parameters
    ----------
    weights : numpy.ndarray
        Weight array. Must not sum to zero.

    Returns
    -------
    numpy.ndarray
        Normalized weight array with ``sum == len(weights)``.

    Raises
    ------
    ValueError
        If ``weights`` sums to zero.

    """
    total = weights.sum()
    if total == 0:
        raise ValueError("Cannot normalize weights: sum is zero")
    return weights * (len(weights) / total)