Identity weighted bce loss

From wenmin-wu/ds-skills · View interactive version

Identity weighted bce loss is an AI agent skill from the GitHub repository wenmin-wu/ds-skills. Weight BCE loss by identity subgroup membership to debias predictions — upweight samples where identity conflicts with label

How to use this skill

Skill file

Identity-Weighted BCE Loss

Overview

Toxicity classifiers often learn spurious correlations between identity terms ("gay", "muslim") and toxicity. Fix this by upweighting four sample categories: (1) any identity-mentioned sample, (2) background-positive/subgroup-negative (toxic text without identity), (3) background-negative/subgroup-positive (non-toxic text with identity). Each category adds 0.25 to the sample weight, so hard fairness cases get up to 2x weight.

Quick Start

import numpy as np
import torch.nn as nn

def compute_identity_weights(df, identity_cols, target_col, threshold=0.5):
    """Compute per-sample weights for bias-aware training.
    
    Args:
        df: DataFrame with identity columns and target
        identity_cols: list of identity attribute columns
        target_col: toxicity target column
        threshold: binarization threshold
    """
    weights = np.ones(len(df)) / 4
    has_identity = (df[identity_cols].fillna(0).values >= threshold).any(axis=1)
    is_toxic = df[target_col].values >= threshold
    
    weights += has_identity.astype(float) / 4           # subgroup
    weights += (is_toxic & ~has_identity) / 4            # BPSN
    weights += (~is_toxic & has_identity) / 4            # BNSP
    return weights

# Custom loss with sample weights
def weighted_bce(pred, target_with_weights):
    target = target_with_weights[:, 0:1]
    weight = target_with_weights[:, 1:2]
    return nn.BCEWithLogitsLoss(weight=weight)(pred, target)

weights = compute_identity_weights(train, IDENTITY_COLS, 'target')

Key Decisions

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.