Sub topic 6
Class weights: making errors on the rare class cost more
This chapter assumes you can fit a scikit-learn classifier, read a confusion matrix, and compute precision and recall. It also assumes you know why accuracy misleads on imbalanced data. Here you will learn how class weights change training, how to set them, and what they do to your metrics and probabilities.
The idea: unequal costs for unequal classes
A standard classifier treats every training row the same. When 95% of rows are negative, the loss is dominated by negatives, and the model can lower its loss by getting the common class right and mostly ignoring the rare one.
Class weights change this by multiplying each row's loss by a factor that depends on its class. This is called cost-sensitive learning. A mistake on a rare-class row then costs more than a mistake on a common-class row, so the optimizer spends more effort on the rare class.
The training objective becomes:
weighted loss = sum over rows of w[class of row] * loss(row)You do not add, remove, or copy any rows. The data stays as it is, and only the loss changes.
What "balanced" computes
Setting class_weight="balanced" gives each class the weight n_samples / (n_classes * count_of_class). Each class then contributes the same total weight to the loss. You can check this with compute_class_weight.
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
y = np.array([0] * 950 + [1] * 50)
classes = np.array([0, 1])
weights = compute_class_weight(class_weight="balanced", classes=classes, y=y)
print(dict(zip(classes.tolist(), weights.tolist())))This prints a weight of about 0.526 for class 0 and 10.0 for class 1. Each positive row counts about 19 times as much as a negative row. The 50 positives carry a total weight of 500, and the 950 negatives also carry 500.
Using class_weight in scikit-learn
Many estimators accept a class_weight argument. It takes one of three values:
| Value | Meaning |
|---|---|
| `None` | All classes have weight 1. This is the default. |
| `"balanced"` | Weights are computed from the class counts in the data passed to `fit`. |
| A dict such as `{0: 1, 1: 20}` | You set the weights yourself. |
Estimators that support it include LogisticRegression, SVC, LinearSVC, SGDClassifier, DecisionTreeClassifier, RandomForestClassifier, and HistGradientBoostingClassifier. Random forests also accept "balanced_subsample", which recomputes the weights inside each bootstrap sample. Some estimators, such as KNeighborsClassifier, have no weight support at all.
The next script compares no weighting, balanced weighting, and a manual weight on the same data.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
settings = [
("none", None),
("balanced", "balanced"),
("manual 1:5", {0: 1, 1: 5}),
]
for name, cw in settings:
model = LogisticRegression(class_weight=cw, max_iter=1000)
model.fit(X_train, y_train)
pred = model.predict(X_test)
scores = model.predict_proba(X_test)[:, 1]
print(
f"{name:11s}"
f" precision={precision_score(y_test, pred, zero_division=0):.3f}"
f" recall={recall_score(y_test, pred):.3f}"
f" AP={average_precision_score(y_test, scores):.3f}"
)Expect a consistent pattern, though the exact numbers depend on your library versions. Recall rises as the positive weight grows. Precision falls, because the model now flags more rows as positive, and some of them are wrong. Average precision (AP) changes little, because it measures how well the model ranks rows and does not depend on where the cutoff sits.
What weights do to the decision boundary
Weighting moves the decision boundary toward the majority class, so more borderline rows are labeled positive. The model's ranking of rows changes only slightly. Most of the effect is a shift in the operating point.
This has three consequences.
- Weights and thresholds overlap. For a model that outputs probabilities, raising the positive weight has an effect similar to lowering the decision threshold. Both trade precision for recall. If you only need a different operating point, tuning the threshold (a later chapter) can give you the same result without retraining.
- Weights can still change the model. The weights change which parameters minimize the loss, so a weighted model is not just the unweighted model with a different cutoff. This matters most for flexible models, where the extra attention on the rare class changes which patterns they learn.
- Probabilities are no longer calibrated. A weighted logistic regression reports
predict_probavalues that overstate the true chance of the rare class. Do not read 0.7 as "70% likely" without checking calibration, which a later chapter covers.
Choosing weights from costs
"balanced" is a reasonable default, but it is not tied to your application. If a missed fraud case costs 200 and a false alarm costs 5, the cost ratio is 40 to 1, and a dict states that directly.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for positive_weight in [1, 2, 5, 10, 19, 40, 100]:
model = LogisticRegression(class_weight={0: 1, 1: positive_weight}, max_iter=1000)
f1 = cross_val_score(model, X, y, cv=cv, scoring="f1").mean()
print(f"positive weight {positive_weight:>3}: mean F1 = {f1:.3f}")Treat the positive weight as a hyperparameter and pick it with cross-validation. Score it with a metric that reflects your goal, such as F1, recall at a fixed precision, or total cost. Do not score it with AP alone, because AP barely responds to the weight. Do not use accuracy either.
Per-row weights with sample_weight
class_weight gives one weight per class. For more control, many estimators accept sample_weight in fit, with one weight per row. This works for estimators that have no class_weight argument, and it lets you weight individual rows, for example by transaction value. The helper compute_sample_weight converts class weights into per-row weights.
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import recall_score
from sklearn.model_selection import train_test_split
from sklearn.utils.class_weight import compute_sample_weight
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
sample_weight = compute_sample_weight(class_weight="balanced", y=y_train)
plain = GradientBoostingClassifier(random_state=42).fit(X_train, y_train)
weighted = GradientBoostingClassifier(random_state=42).fit(
X_train, y_train, sample_weight=sample_weight
)
print("recall without weights:", recall_score(y_test, plain.predict(X_test)))
print("recall with weights: ", recall_score(y_test, weighted.predict(X_test)))GradientBoostingClassifier has no class_weight argument, so sample_weight is the way to weight it. Gradient boosting libraries outside scikit-learn have their own options. XGBoost and LightGBM offer scale_pos_weight, which multiplies the weight of the positive class in binary problems.
Gotchas and edge cases
- Weights are computed from the data passed to
fit. With"balanced"inside cross-validation or a pipeline, each training fold gets its own weights. This is correct and causes no leakage. If you compute weights by hand withcompute_class_weight, compute them from the training labels only. - Weights interact with regularization. In regularized models such as logistic regression and SVMs, the weights scale the data-fit term against the penalty. A large positive weight makes the penalty relatively weaker for the rare class. When you change the weight, you may need to retune
C. - Very large weights are unstable. With a weight of 1000, a few mislabeled or noisy positives can dominate the loss. The model then overfits them. Cap the weight, or use cross-validation to see where performance stops improving.
- Fully grown trees can ignore weights. A tree grown until every leaf is pure fits the training data regardless of the weights. Weights matter when the tree is limited, through
max_depth,min_samples_leaf, ormin_weight_fraction_leaf. The last of these counts weights instead of rows. - Evaluate on unweighted test data. Weights are a training device. Compute precision, recall, and F1 on the test set as it really is, with its natural class ratio, so the numbers reflect deployment.
- Multiclass problems work too.
"balanced"computes one weight per class from the class counts. A dict needs a key for each class you want to change, and classes you leave out get weight 1. - Weights do not create information. If the rare class is too small or too noisy to learn from, weights shift the cutoff but cannot fix a model that cannot separate the classes. Look at AP or the precision-recall curve to see whether the ranking itself is good.
Summary of when weights fit
Class weights are cheap to try. They need one argument, add no rows, and train as fast as the unweighted model. They are a strong first remedy for linear models, SVMs, and tree ensembles. They are less direct for models whose training has no per-row loss, such as nearest neighbors, and they do nothing for the calibration of probabilities. A later chapter compares them with resampling and threshold tuning.
Exercise
A training set has 5,000 rows, 100 of them positive. What are the class weights that classweight="balanced" assigns? Then describe what happens to recall, precision, and predictproba values when you train with these weights instead of no weights.
Show answer
The formula is nsamples / (nclasses count). The negative class has 4,900 rows, so its weight is 5000 / (2 4900), about 0.510. The positive class has 100 rows, so its weight is 5000 / (2 * 100) = 25. Each positive row counts about 49 times as much as a negative row. With these weights, recall usually rises because the decision boundary moves toward the majority class, and precision usually falls because more negatives are flagged. The predict_proba values become inflated, so they overstate the true chance of a positive and need calibration checks before being read as probabilities.
Exercise
You tune the positive weight of a logistic regression by cross-validation and score each candidate with average precision. The scores are almost identical for every weight from 1 to 100. Why does this happen, and what would you score with instead?
Show answer
Average precision measures how well the model ranks rows by score, and a weight mostly moves the decision boundary instead of changing the ranking. So AP barely responds to the weight. Score the candidates with a metric that depends on the chosen cutoff and matches your goal, such as F1, recall at a required precision, or expected cost from the confusion matrix.