Sub topic 6
Class weights: making errors on the rare class cost more
This chapter assumes you know binary classification, scikit-learn estimators, and the confusion matrix metrics (precision, recall, F1) from earlier chapters. It uses the synthetic dataset and the stratified split from the baseline example (X_train, X_test, y_train, y_test).
The idea
Most classifiers minimize a loss summed over training samples. When 95% of the samples are negative, the loss is dominated by negatives, and the model can lower it by caring mostly about them.
A class weight multiplies the loss of every sample in a class. If a missed positive costs 19 times as much as a missed negative, the model can no longer ignore the rare class. This approach is called cost-sensitive learning. It changes the training objective and leaves the data as it is.
With class_weight="balanced", scikit-learn computes each weight as:
weight_c = n_samples / (n_classes * count_c)For 7,500 training samples with about 5% positives, the positive weight is about 10 and the negative weight is about 0.53. The ratio between them is roughly the inverse of the class frequency ratio.
Using class weights
Pass class_weight to any estimator that supports it. This includes LogisticRegression, SVC, DecisionTreeClassifier and RandomForestClassifier.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, average_precision_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,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
model = LogisticRegression(class_weight="balanced", max_iter=1000)
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test), digits=3))
scores = model.predict_proba(X_test)[:, 1]
print("average precision:", average_precision_score(y_test, scores))Read the report for the minority class, not the overall accuracy. Compared with the unweighted model, you should see recall for class 1 go up and precision go down. The model now flags more samples as positive, so it catches more true positives and also raises more false alarms.
Custom weights
"balanced" is a default, not an optimum. You can pass a dictionary that maps each class label to a weight:
from sklearn.linear_model import LogisticRegression
# Continues from the previous example (X_train, y_train).
model = LogisticRegression(class_weight={0: 1, 1: 5}, max_iter=1000)
model.fit(X_train, y_train)Use this when you know the real costs. If a missed fraud case costs 50 times a false alarm, a weight near 50 is better justified than the frequency ratio. You can also treat the weight as a hyperparameter and search over it with cross-validation, scoring with a metric such as average precision.
For per-sample control, most estimators accept sample_weight in fit. It lets you weight individual rows, for example by transaction amount.
Trade-offs and common errors
- Probabilities shift. Weighting moves predicted probabilities upward for the rare class. A score of 0.7 no longer means a 70% chance of being positive. The calibration chapter covers this.
- Weights do not add information. The model sees the same positives as before. With very few positives, weighting can overfit them.
- Not every model supports it. Gradient boosting libraries use their own parameters, such as
scale_pos_weightin XGBoost. Check the documentation for each estimator. - Judging by accuracy. Accuracy will usually drop after weighting. That is expected, and it does not mean the model got worse. Use the metrics for the rare class.
- Weights computed on the wrong data.
"balanced"uses the class counts of the data passed tofit. In cross-validation this is each training fold, which is correct.
Exercise
A training set has 9,000 negatives and 1,000 positives. What weights does class_weight="balanced" assign to each class, and what is the effect on recall and precision for the positive class?
Show answer
The formula is nsamples / (nclasses count). Negatives get 10000 / (2 9000) ≈ 0.556. Positives get 10000 / (2 * 1000) = 5.0. A missed positive costs 9 times a missed negative. Recall for the positive class typically rises, and precision typically falls, because the model predicts the positive class more often.
Exercise
A colleague compares a weighted and an unweighted logistic regression and reports that the weighted model is worse because its accuracy dropped from 0.96 to 0.88. What is wrong with this comparison, and what would you compute instead?
Show answer
Accuracy rewards predicting the majority class, so a drop is expected when the model starts flagging more positives. Compare minority-class recall, precision and F1, and average precision on the same stratified test set or cross-validation folds.