(y, y_true, scale_by_total=True)
return weights, confusion_counts
Compute class weights from a confusion matrix.
Compute class weights from a confusion matrix.
Compute class weights from a confusion matrix .
def balanced_confusion_weights(y, y_true, scale_by_total=True):
    """Compute class weights from a confusion matrix."""
    y = y.astype(np.bool)
    y_true = y_true.astype(np.bool)

    # Assuming labels in {0, 1}, count entries from confusion matrix
    TP = (y & y_true).sum()
    TN = (~y & ~y_true).sum()
    FP = (y & ~y_true).sum()
    FN = (~y & y_true).sum()
    confusion_counts = np.array([[TN, FN], [FP, TP]])

    # Scale up each sample by inverse of confusion weight
    weights = np.ones_like(y, dtype=float)
    weights[y & y_true] /= TP
    weights[~y & ~y_true] /= TN
    weights[y & ~y_true] /= FP
    weights[~y & y_true] /= FN
    if scale_by_total:
        weights *= y.size

    return weights, confusion_counts
def balanced_confusion_weights ( y , y_true , scale_by_total = True ) : y = y . astype ( np . bool ) y_true = y_true . astype ( np . bool ) # Assuming labels in {0, 1}, count entries from confusion matrix TP = ( y & y_true ) . sum ( ) TN = ( ~ y & ~ y_true ) . sum ( ) FP = ( y & ~ y_true ) . sum ( ) FN = ( ~ y & y_true ) . sum ( ) confusion_counts = np . array ( [ [ TN , FN ] , [ FP , TP ] ] ) # Scale up each sample by inverse of confusion weight weights = np . ones_like ( y , dtype = float ) weights [ y & y_true ] /= TP weights [ ~ y & ~ y_true ] /= TN weights [ y & ~ y_true ] /= FP weights [ ~ y & y_true ] /= FN if scale_by_total : weights *= y . size return weights , confusion_counts