Skip to content
Back to skills

Identity Weighted Bce Loss

ASecurity

Weight BCE loss by identity subgroup membership to debias predictions — upweight samples where identity conflicts with label

  • 61 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added September 12, 2026
developmentpythongogit

Security analysis

A100/100

Scanned September 12, 2026

npx -y skills add wenmin-wu/ds-skills --skill identity-weighted-bce-loss --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Identity Weighted Bce Loss?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Identity Weighted Bce Loss
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/wenmin-wu-identity-weighted-bce-loss/badge)](https://www.skillsdirectory.com/skills/wenmin-wu-identity-weighted-bce-loss)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: nlp-identity-weighted-bce-loss
description: Weight BCE loss by identity subgroup membership to debias predictions — upweight samples where identity conflicts with label
domain: nlp
---

# 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

```python
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

- **Equal 0.25 splits**: each bias category contributes equally; tune if one matters more
- **Threshold 0.5**: binarizes soft identity labels; lower for more aggressive debiasing
- **Combine with auxiliary targets**: pair with multi-task heads on identity subtypes for best results
- **Normalize weights**: divide by mean to keep effective batch size stable

## References

- Source: [simple-lstm-with-identity-parameters-fastai](https://www.kaggle.com/code/kunwar31/simple-lstm-with-identity-parameters-fastai)
- Competition: Jigsaw Unintended Bias in Toxicity Classification

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.