smartyfy.mrindigi.com

AI & Machine Learning Master Course — 058. Class weights and asymmetric errors

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 058: Class weights and asymmetric errors

Prerequisites: Lesson 057. Learning outcome: Relate weighted fitting and threshold choice to error consequences.

1. Weighted learning and decision costs are different layers

Class weighting changes how training observations contribute to an optimization objective. Threshold selection changes how a fitted score becomes an action. Both can respond to asymmetric errors, but they are not interchangeable operations in every model. Combining them without a clear rationale can count the same preference twice.

Suppose missing a damaged parcel is considered four times as costly as an unnecessary inspection. One approach estimates relevant probabilities and applies a cost-derived threshold. Another gives positive training examples greater weight. Their consequences depend on model capacity, optimization, probability calibration, and the population being assessed. Write down which part of the system encodes which objective.

2. Derive the probability shift under weighted log loss

Let the original conditional positive probability be p. Weight positive examples by w₁ and negative examples by w₀. If a flexible model minimizes population weighted binary log loss exactly, its optimum is q=w₁p/[w₁p+w₀(1−p)]. This q is a tilted probability under the weighting scheme, not automatically the original population probability.

With p=0.2,w₁=4,w₀=1, the weighted optimum is 0.8/(0.8+0.8)=0.5. The underlying event rate has not changed; the training objective has. In log-odds terms, weighting adds log(w₁/w₀) under this idealized calculation. Finite model classes and regularization can change the practical relationship.

The ideal formula can be inverted: p=qw₀/[w₁(1−q)+qw₀]. At q=0.5, the inverse recovers 0.2. This algebra is a useful diagnostic, not a universal promise that analytically correcting any fitted weighted classifier produces calibrated probabilities. Real calibration must still be checked on suitable representative data.

3. Relate weighting to a threshold under stated assumptions

A 0.5 threshold on q corresponds, under the ideal formula, to an original-probability threshold w₀/(w₀+w₁). For weights one and four, that is 0.2. This resembles the simple false-positive/false-negative cost threshold when those weights reflect the corresponding costs.

If the weighting already encodes the desired asymmetry, applying the same cost ratio again to q can make the decision overly aggressive relative to the original objective. For q≥0.2 with weights four-to-one, solving the inverse threshold gives original p≥1/17≈0.0588, not 0.2. The combined policy therefore needs its own interpretation and evaluation.

This example concerns a binary log-loss population optimum. Weighted support-vector losses, tree impurity, resampling, and constrained models need not reproduce the same formula exactly. Avoid presenting a special-case equivalence as a theorem about all classifiers.

The ideal curve q = 4p/(1+3p) lies above the unchanged-scale diagonal. It maps original probability 0.2 to weighted optimum 0.5. A weighted threshold of 0.2 instead corresponds to original probability 1/17, about 0.0588. A proportional count strip retains 80 negatives and 20 positives out of 100 observations.
A weighted objective can encode asymmetry by changing the fitted probability scale. Applying another cost threshold requires checking the combined policy in the original probability space. Open full-size diagram

4. Distinguish class balance from business value

Balanced class weights are often based on inverse training frequencies, giving classes similar total influence. That is a statistical heuristic, not a measured cost of an error. A rare event may be cheap or expensive, and a common event may carry large consequences. Frequencies alone cannot determine the appropriate action policy.

Sample weights can also represent a sampling design rather than a business preference. For example, an intentionally oversampled subgroup may require weights to estimate a target-population quantity. Mixing sampling correction with error costs requires careful bookkeeping. Document what each weight means and whether it changes fitting, reporting, or both.

Evaluation should generally reflect the intended population and decision costs. Do not rebalance the final test merely to obtain a flattering precision score. Report actual counts, prevalence, and the chosen cost aggregation. If review capacity is limited, the policy must also describe what happens when the number of alerts exceeds available resources.

5. Select and assess the complete policy

Use development data to compare a probability-based threshold policy, weighted fitting, or a justified combination. Keep preprocessing and any weights derived from observed training frequencies inside the relevant folds. Probability calibration data should be representative of the population whose probabilities the policy needs.

Freeze the model, calibration, threshold, and action costs before final assessment. A low realized cost on a small sample can be noisy, especially when expensive events are rare. Report the number of such events and uncertainty appropriate to the sampling design, rather than hiding them behind a single mean cost.

CPU lab: weighting without new information

The local example has one hundred rows with a constant feature: eighty negatives and twenty positives. No feature can distinguish cases, so the model only learns an intercept. Unweighted logistic regression predicts 0.2; four-to-one positive weighting predicts 0.5. The script verifies the algebraic forward and inverse maps.

The example was checked with NumPy 2.3.5 and scikit-learn 1.8.0. It changes only the fitting emphasis, not the observations or their prevalence. These probabilities are training-objective demonstrations rather than evidence of a useful classifier. Because all features are constant, the intercept interpretation is unusually transparent compared with a real multifeature model.

import numpy as np
from sklearn.linear_model import LogisticRegression
X=np.zeros((100,1));y=np.array([0]*80+[1]*20)
for weight in [None,{0:1,1:4}]:
    model=LogisticRegression(class_weight=weight,C=1.,tol=1e-10,max_iter=1000).fit(X,y)
    print('Weights/probability:',weight,round(model.predict_proba([[0.]])[0,1],6))
p=.2;w0,w1=1.,4.
q=w1*p/(w1*p+w0*(1-p))
recovered=q*w0/(w1*(1-q)+q*w0)
assert np.isclose(q,.5) and np.isclose(recovered,p)
print('Weighted probability/inverse:',q,recovered)
print('Original-space threshold for weighted.5:',w0/(w0+w1))

Four practice questions with worked answers

Practice 1

Compute the ideal weighted probability when p=0.1,w₁=3,w₀=1.

Answer: The numerator is 0.3 and the denominator 0.3+0.9=1.2, giving q=0.25. The value is larger than the original probability because positive outcomes receive more optimization weight. It should not be reported as the original event rate without considering the weighting and calibration.

Practice 2

For w₁=4,w₀=1, what original p corresponds to q=0.2?

Answer: Apply the inverse: p=0.2/[4×0.8+0.2]=0.2/3.4=1/17≈0.0588. Thus thresholding the weighted probability at 0.2 is more aggressive than thresholding the original probability at 0.2. This illustrates why two separate asymmetry adjustments can compound.

Practice 3

Why do balanced class weights not automatically represent error costs?

Answer: They are computed from class frequencies, whereas costs concern consequences of decisions. Two tasks with the same prevalence can have different inspection costs and missed-event harms. Use domain-defined costs or utility where available, and treat frequency-based balancing as a candidate training choice rather than a business policy.

Practice 4

A classifier was weighted on an oversampled training set. Which population should calibration and cost evaluation represent?

Answer: They should represent the explicitly intended deployment population or use a justified adjustment for the sampling design. Record both oversampling and class weighting, because their effects can compound. Do not assume the weighted training proportions describe real event probabilities or operational alert precision.

Five multiple-choice questions

Question 1

What does class weighting directly change?

  • A. The final-test class distribution automatically
  • B. Their contributions to the training objective
  • C. The observed labels themselves

Correct: B. The data can remain identical while the fitted objective emphasizes some observations more.

Question 2

Under the ideal weighted log-loss formula, is q necessarily the original p?

  • A. No, unequal weights tilt the optimum
  • B. Yes, for every positive weight
  • C. Only when training accuracy is high

Correct: A. Equal class weights leave the formula unchanged; unequal weights generally alter the probability scale.

Question 3

What original threshold corresponds to q≥0.5 with weights w₀,w₁?

  • A. Always 0.5
  • B. w₁/(w₀+w₁)
  • C. w₀/(w₀+w₁)

Correct: C. Solving the ideal tilted-probability inequality yields the displayed original-space threshold.

Question 4

Why can weighting and thresholding double-count an objective?

  • A. Weights always remove calibration needs
  • B. Thresholds refit the feature coefficients
  • C. Both can encode the same error asymmetry

Correct: C. Their combined action rule may express a different preference than intended unless derived and evaluated explicitly.

Question 5

What should a weighted-model report distinguish?

  • A. Only the final accuracy
  • B. Sampling corrections, fitting preferences, and decision costs
  • C. Only weights normalized to sum to one

Correct: B. Different reasons for weights affect interpretation and evaluation in different ways.

Common pitfalls

Do not label inverse-frequency weights as measured business costs. Do not treat weighted probability output as automatically calibrated to deployment prevalence. Avoid transferring the ideal logistic equivalence to unrelated losses without checking its assumptions.

Summary

Weights change fitting and can tilt probability estimates; thresholds change decisions. Derive their relationship under explicit assumptions, distinguish balancing from costs, and evaluate the full policy on the intended population without counting the same asymmetry twice.

Primary sources and further reading