Class weights and fold-only resampling
Quick answer
Class weighting changes the contribution of examples to the training loss. Resampling changes the training data distribution. Both are strategies for imbalance, not substitutes for valid evaluation. Static examples tested locally with Python 3.13.5, scikit-learn 1.8.0 SciPy 1.17.0 and NumPy 2.3.5 where imported. ByteMind package execution is unverified.
Calculate balanced weights
import numpy as npfrom sklearn.utils.class_weight import compute_class_weighty=[0]*8+[1]*2w=compute_class_weight("balanced",classes=np.array([0,1]),y=y)print(w.tolist())Observed local output:
[0.625, 2.5]The two classes contribute equal total weight before model-specific adjustments.
How it works
Balanced class weights for K classes use w_c = n/(K*n_c) on unweighted training labels with every class present. For 8 negatives and 2 positives the weights are 0.625 and 2.5. Weighted losses increase minority influence but can alter probability calibration. Random oversampling repeats minority examples; undersampling removes majority examples, risking information loss. Synthetic interpolation such as SMOTE requires meaningful geometry and must be applied only to a training fold. Split original rows first. In each CV fold fit preprocessing on training rows, resample only training rows, then fit; score untouched validation rows. An imbalanced-learn pipeline can automate this where that dependency is approved; here we demonstrate index resampling explicitly in NumPy. Keep IDs to audit duplicates, preserve natural validation/test prevalence, and fit any calibrator on representative independent predictions. Class weights and oversampling need not yield identical regularized models.
Oversample inside each training fold
import numpy as npfrom sklearn.model_selection import StratifiedKFoldy=np.array([0]*8+[1]*4);rng=np.random.default_rng(7)for tr,va in StratifiedKFold(2).split(y,y): pos=tr[y[tr]==1];neg=tr[y[tr]==0];ids=np.r_[tr,rng.choice(pos,len(neg)-len(pos),replace=True)] assert not set(ids)&set(va) print(np.bincount(y[ids]).tolist(),np.bincount(y[va]).tolist())Observed local output:
[4, 4] [4, 2][4, 4] [4, 2]Duplicate IDs stay within training; validation retains original prevalence.
Common mistakes
Never resample the full dataset before cross-validation. Never balance the test set to inflate precision. Do not assume weighted probabilities reflect natural prevalence.
Practice and next steps
Use a stratified split on 20 unique IDs with four positives. Verify oversampled IDs remain inside training and report the unchanged validation counts. Complete the knowledge check and staged exercise. Next: Calibration and Brier score.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Class weights and fold-only resampling — knowledge check
Apply class weights and fold-only resampling to new scenarios.
When should oversampling occur?
Balanced weights for 8 negative and 2 positive?
Undersampling can lose what?
Weighted probabilities necessarily calibrated?
SMOTE on categorical integer codes is automatically valid?