σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
LightGBM skill›Module 2 · Categories and imbalance›Topic 2.2·~40 minIntermediate

Imbalanced targets

Skill positionModule 2 of 4 · Topic 2 of 2
2.2 Imbalanced targets
—Lab score— / 100Total XP—Streak—
Lecture0% read

8 min readCode examples: 4

  1. 01When "no" is almost always right
  2. 02Weights, the loss and its gradients
  3. 03Scores for a rare event
  4. 04The panel
  5. 05What you will build

A model that never says "big move" is right 90% of the time on the fit years and 96% on the next four. Add weights and it says "big" on 7% of the rows, with the same ranking quality and a log loss twice as bad. This topic shows what weights, the loss and the threshold each change.

01

When "no" is almost always right

Where we are. The first topics predicted the size of next month's move as a number. Often the question that matters is a yes/no one: will the move be big (larger than the 90% quantile of the fit rows, about 13%)? Only one row in ten is a "yes" in the fit years, one in twenty-six in 2011 to 2014, and one in thirteen from 2015 on. The rate of the rare event is not even constant.

DefinitionImbalanced target

A yes/no target where one answer is much rarer than the other. Accuracy is a poor score for it: always answering "no" is right 90% of the time and finds nothing.

A classifier minimises the log loss of the probability p it gives to "yes". With 10% of the rows positive, the log-loss-optimal model for rows it cannot tell apart says p = 0.1 for all of them. That is the correct probability, and it is never above 0.5, so a rule "predict yes when p > 0.5" never fires. Nothing is broken: the model is honest and the rule is too strict for a rare event. There are three separate levers.

  1. 1
    WeightsMake a positive row count more in the loss. It changes what the model learns, and it changes the probabilities it reports.
  2. 2
    ScoresJudge the model with a score that looks at the rare class: average precision for the ranking, F1 for a decision.
  3. 3
    ThresholdPick the cut-off on p from the valid rows, not 0.5.
02

Weights, the loss and its gradients

LightGBM's scale_pos_weight multiplies the weight of every positive row. The usual choice makes the two classes weigh the same in total.

scale_pos_weight = (number of rows with label 0) / (number of rows with label 1)(1)on the fit rows: 5,943 negatives and 661 positives give 8.99; is_unbalance=True asks LightGBM for exactly this value

The weighted log loss and the numbers a boosting round needs from it are short. With p = sigmoid(raw), where raw is the model's score before the sigmoid, a row with label y and weight w has

loss = w × ( −y log p − (1 − y) log(1 − p) ) grad = w (p − y) hess = w p (1 − p)(2)grad and hess are the first and second derivatives of the loss with respect to raw; a boosting round fits a tree to −grad / hess

Worked example 1. *Problem:* ten rows, two positive. What are the weight for the positives, the weighted loss of a model that says p = 0.2 everywhere, and the gradients at raw = 0? *Plan:* count the classes; plug into equation 2. *Steps:* below.

main.pyPython
labels = np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0])w_pos = pos_weight(labels)1w = sample_weights(labels, w_pos)2p = np.full(10, 0.2)print(w_pos, w.tolist())print(round(weighted_logloss(labels, p, np.ones(10)), 4), round(weighted_logloss(labels, p, w), 4))grad, hess = weighted_gradients(labels, np.zeros(10), w)print(grad.round(2).tolist()[:3], hess.round(2).tolist()[:3])
4.0 [4.0, 4.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
0.5004 0.9163
[-2.0, -2.0, 0.5] [1.0, 1.0, 0.25]
  1. 18 negatives for 2 positives: each positive counts 4 times.
  2. 2One weight per row.

*Check:* scale_pos_weight is 4. With all weights 1 the loss of p = 0.2 is 0.5004: the model is exactly right about the base rate. With the weights it is 0.9163: now the positives weigh as much as the negatives (2 × 4 = 8 against 8), so the best answer for rows that cannot be told apart is 0.5, with a loss of 0.6931 = ln 2. At raw = 0 (p = 0.5) a positive row has grad = 4 × (0.5 − 1) = −2 and hess = 4 × 0.25 = 1; a negative has grad = 0.5 and hess = 0.25. *What to notice:* the weights moved the best constant answer from 0.2 to 0.5. That is the whole effect of a weight: it changes the probabilities the model reports.

Weights are not the only way

Passing sample_weight to fit gives nearly the same model, but not exactly: LightGBM counts rows, not weights, when it applies min_child_samples, and it starts from a different base score. scale_pos_weight and is_unbalance are weights inside the objective itself, which is why the study below can reproduce them with a custom objective.

03

Scores for a rare event

How do we judge a model on 4% positives? Average precision rewards putting the positives at the top of the ranking, ignoring the sea of negatives. Go down the rows from the highest score. At each distinct score t look at the rows with a score at least t: precision is the share of them that are positive and recall the share of all positives found so far.

AP = Σ over scores t, highest first: (recall(t) − recall(previous t)) × precision(t)(3)recall starts at 0 before the highest score; AP is the area under the precision-recall curve; a random ranking scores about the share of positives

Worked example 2. *Problem:* six rows with the labels 1, 0, 1, 0, 0, 1 and the scores 0.9, 0.8, 0.7, 0.6, 0.5, 0.4. Compute the average precision and the best F1. *Plan:* the positives are the 1st, 3rd and 6th of the ranking, so recall grows by 1/3 at each of them, and precision there is 1/1, 2/3 and 3/6. F1 is 2PR / (P + R) at every threshold. *Steps:* below.

main.pyPython
labels = np.array([1, 0, 1, 0, 0, 1])scores = np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4])print(round(average_precision(labels, scores), 4), round((1 / 1 + 2 / 3 + 3 / 6) / 3, 4))1print(best_f1(labels, scores))print(round(average_precision(labels, labels + 0.01 * scores), 4))
0.7222 0.7222
(0.7, 0.6666666666666666)
1.0
  1. 1A ranking with all the positives first.

*Check:* AP = (1 + 2/3 + 1/2) / 3 = 0.7222, the same as the function returns, and a ranking with all the positives first scores 1.0. F1 depends on the threshold: at t = 0.9 it is 0.5 (precision 1, recall 1/3); at t = 0.7 it is 2/3 (precision 2/3, recall 2/3); at t = 0.4, with every row predicted positive, it is 2/3 again (precision 1/2, recall 1). The function returns (0.7, 0.667): on a tie it takes the larger threshold. *What to notice:* F1 depends on the threshold, AP does not. AP asks whether the ranking is good; F1 asks whether one cut-off is.

04

The panel

Worked example 3. *Problem:* on the 56 stocks, train two classifiers for "big move next month" on the fit rows (before 2011), one plain and one with scale_pos_weight, and judge them on 2011 to 2014 and on 2015 onwards. *Plan:* compute the labels from the 90% quantile of the fit rows, fit both with 150 trees and 8 leaves, and print the average precision, the log loss, the mean probability and how often p > 0.5. *Steps:* below.

main.pyPython
panel = build_panel(load_close())fit, valid, test = split_panel(panel)threshold = np.quantile(fit[TARGET], 0.9)y_fit, y_valid, y_test = (make_labels(part[TARGET], threshold) for part in (fit, valid, test))1settings = dict(n_estimators=150, learning_rate=0.05, num_leaves=8, min_child_samples=20, n_jobs=1, random_state=0, verbose=-1)2spw = pos_weight(y_fit)print([round(float(y.mean()), 3) for y in (y_fit, y_valid, y_test)], round(spw, 2))for name, extra in (("plain", {}), ("weighted", {"scale_pos_weight": spw})):    model = lgb.LGBMClassifier(**extra, **settings).fit(fit[FEATURES], y_fit)    p_valid, p_test = model.predict_proba(valid[FEATURES])[:, 1], model.predict_proba(test[FEATURES])[:, 1]    print(f"{name:>8}: AP {average_precision(y_valid, p_valid):.4f} / {average_precision(y_test, p_test):.4f} | logloss {weighted_logloss(y_valid, p_valid, np.ones(len(y_valid))):.4f} | mean p {p_valid.mean():.3f} | p > 0.5 on {np.mean(p_valid > 0.5):.1%}")
[0.1, 0.038, 0.079] 8.99
   plain: AP 0.1743 / 0.1945 | logloss 0.1397 | mean p 0.045 | p > 0.5 on 0.0%
weighted: AP 0.1714 / 0.1994 | logloss 0.3056 | mean p 0.228 | p > 0.5 on 7.3%
  1. 1The only difference between the two models.
  2. 2Probabilities of the class 1, on the 2011 to 2014 rows and on the later rows.

*Check:* the rates of big moves are 10.0 %, 3.8 % and 7.9 %, and scale_pos_weight is 8.99. The plain model has an average precision of 0.1743 on 2011 to 2014 and 0.1945 after (a random ranking would give 0.038 and 0.079), a log loss of 0.1397, a mean probability of 0.045, and it never says more than 0.5. The weighted model has 0.1714 and 0.1994, a log loss of 0.3056, a mean probability of 0.228, and says "big" on 7.3 % of the rows. *What to notice:* the weights changed the probabilities a lot (0.045 to 0.228 when the true rate is 3.8 %) and the ranking not at all: the average precision moved by 0.003 and 0.005, in different directions. Weights make the model answer "yes" more often; they do not make it better at finding the positives.

Two checks, in the lab. First, is_unbalance=True gives exactly the same probabilities as scale_pos_weight=8.99. Second, the gradients of equation 2, given to LightGBM as a custom objective, reproduce its built-in binary objective with the same weight to the last digit. Then the decision: choose the threshold on the valid rows to maximise F1, and apply it to the test rows.

main.pyPython
t, valid_f1 = best_f1(y_valid, p_valid)predicted = model.predict_proba(test[FEATURES])[:, 1] >= thits = int(np.sum(predicted & (y_test == 1)))print(round(t, 3), round(valid_f1, 3), int(predicted.sum()), hits, int(y_test.sum()))print(round(hits / predicted.sum(), 3), round(hits / y_test.sum(), 3))
0.567 0.312 1006 214 611
0.213 0.35

*Check:* on the valid rows the best threshold is 0.567 with an F1 of 0.312. On the test rows that threshold flags 1,006 of the 7,783 rows as big; 214 of them are, out of 611 real big moves: a precision of 0.213 and a recall of 0.350. *What to notice:* the threshold came from other years than the ones it is judged on, so the numbers are honest, and they are modest. Finding rare large moves from three simple features is hard, and a table of precision and recall says so more clearly than an accuracy of 92%.

A threshold from one period

The rate of big moves was 10% in the fit years, 3.8% in 2011 to 2014 and 7.9% afterwards. A threshold tuned on one period carries that period's rate with it. Re-check it on every new period, or choose it by a target such as "flag the top 5% of scores".

  • FunctionQuestion it answers
  • pos_weight(labels)How much should a positive row count?negatives / positives
  • sample_weights(labels, w_pos)What weight does each row get?float array
  • weighted_logloss(labels, p, w)How wrong are the probabilities?clipped, divided by the sum of weights
  • weighted_gradients(labels, raw, w)What does a boosting round need?grad and hess
  • average_precision(labels, scores)Is the ranking good?area under precision-recall
  • best_f1(labels, scores)Which cut-off balances precision and recall?larger threshold on a tie
What the real data says56 US stocks; fit rows before 2011, valid 2011 to 2014, test 2015 onwards
Rate of big moves10.0 / 3.8 / 7.9 %fit, valid and test
Plain modelp > 0.5 on 0%average precision 0.1743 on valid; mean probability 0.045
Weighted modelp > 0.5 on 7.3%average precision 0.1714; log loss 0.3056 against 0.1397
is_unbalancegap 0same probabilities as scale_pos_weight = 8.99
F1 threshold0.567chosen on valid; test precision 0.213, recall 0.350

Key takeaways

  • Accuracy hides a rare event. Always answering no is right 90% of the time; judge a rare-event model by average precision and by precision and recall at a threshold.
  • Weights change the probabilities. scale_pos_weight = negatives / positives moves the model's best constant answer towards 0.5 and inflates every probability; it hardly changes the ranking.
  • The threshold is a choice. Pick it from the valid rows, for the F1 or the recall you need, and re-check it when the rate of the event changes.
  • Custom objectives are short. grad = w (p − y) and hess = w p (1 − p) reproduce LightGBM's built-in weighted binary loss exactly.
Quick check
Your turn. A model gives a probability of 0.30 to a row. It was trained with scale_pos_weight = 9, and the true rate of the event is 10%. About what is the real probability of the event for that row?
Pick an answer.
05

What you will build

The lab follows the lecture. Tasks 1 and 2 compute the weights. Task 3 is the weighted loss and task 4 its gradients. Tasks 5 and 6 are the two scores for a rare event: average precision and the best F1. Task 7 trains the plain and the weighted classifier on the real panel, reproduces LightGBM's own objective with your gradients, and picks a threshold on the valid rows.

Next topic: you now have models you can score, and many settings to choose: leaves, trees, learning rate, regularisation. The next topic, Parameter tuning without fooling yourself, shows how to search them without the validation set quietly turning into training data.

Lab · what's graded

7 tasks · 100 pts
  • The weight of the rare class10 pts
  • One weight per row5 pts
  • The weighted log loss10 pts
  • Gradients of the loss15 pts
  • Average precision15 pts
  • The best F1 threshold15 pts
  • A rare-event classifier on the panel30 pts
Explorer · lab-lg-04
▾ lab-lg-04
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-lg-04$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-lg-04 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes