Home Knowledge Base Class Weights

Class Weights is a technique for handling imbalanced datasets that modifies the loss function to penalize misclassifying the minority class more heavily — instead of manipulating the data (oversampling or undersampling), class weights make the model "care more" about getting minority examples right by multiplying their loss contribution by a factor inversely proportional to their frequency, so misclassifying 1 fraud case costs as much as misclassifying 100 legitimate ones.

What Are Class Weights?

How Class Weights Work

ClassCountStandard Loss WeightBalanced WeightEffect
Legitimate10,0001.00.05Low penalty per error
Fraud1001.05.0100× higher penalty per error

The Balanced Weight Formula: $w_c = frac{N}{k imes n_c}$ where N = total samples, k = number of classes, $n_c$ = samples in class c.

For the example above: $w_{fraud} = frac{10100}{2 imes 100} = 50.5$ and $w_{legit} = frac{10100}{2 imes 10000} = 0.505$.

Implementation Across Frameworks

FrameworkCodeNotes
Scikit-learnLogisticRegression(class_weight='balanced')Automatic weight calculation
XGBoostscale_pos_weight=100Ratio of negative to positive
PyTorchnn.CrossEntropyLoss(weight=torch.tensor([0.05, 5.0]))Manual weight tensor
Kerasmodel.fit(class_weight={0: 0.05, 1: 5.0})Dict per class
LightGBMis_unbalance=TrueAutomatic handling

Class Weights vs Other Imbalance Techniques

TechniqueModifies Data?Modifies Loss?ProsCons
Class WeightsNoYesSimplest, no data changeCan't add new information
SMOTEYes (adds synthetic)NoExpands decision boundaryCan create noisy examples
UndersamplingYes (removes majority)NoReduces training timeLoses information
Focal LossNoYes (down-weights easy examples)Focuses on hard examplesMore complex to tune
Threshold TuningNoNo (post-processing)Adjusts precision/recall after trainingModel unchanged

The Precision-Recall Trade-off

Higher Minority WeightEffect on RecallEffect on Precision
More aggressive weightRecall ↑ (catches more minority examples)Precision ↓ (more false positives)
Less aggressive weightRecall ↓Precision ↑
Balanced weightGood balanceGood balance

Class Weights is the simplest and most universally supported technique for handling imbalanced datasets — requiring just one parameter change (class_weight="balanced") to make any classifier treat minority examples as equally important as majority examples, with the trade-off that it increases recall for the minority class at the cost of some precision, and cannot add new information the way oversampling techniques can.

class weightimbalancedloss

Related Topics

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.