σμ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 3 · Tuning and ranking›Topic 3.2·~55 minAdvanced

lambdarank and group queries

Skill positionModule 3 of 4 · Topic 2 of 2
3.2 lambdarank and group queries
—Lab score— / 100Total XP—Streak—
Lecture0% read

8 min readCode examples: 4

  1. 01Lists, not rows
  2. 02Scoring a list: DCG and NDCG
  3. 03From pairs to gradients
  4. 04The panel
  5. 05What you will build

Rank the 56 stocks of each month by volatility alone and the lists score 50.4% of a perfect one, where a random order scores 35.2%. A LightGBM ranker scores 51.1%. This topic builds the pieces of a ranking model: the lists, the score NDCG, and the gradients that lambdarank adds.

01

Lists, not rows

Where we are. Every earlier topic predicted a number or a yes/no for each row on its own. A ranking question is different: *among the 56 stocks of this month, which ones will move the most?* Only the order inside the month matters, and mostly the top of it. The natural unit is a list (LightGBM calls it a *query*): all the rows of one month.

DefinitionQuery (list)

A group of rows that are ranked against each other, here the stocks of one month. A ranking model never compares a row of January with a row of February.

LightGBM learns from lists if you tell it where each list starts and ends. The rows must be sorted so that a list is contiguous, and you pass group=sizes, the length of every list in order. Worked example 1. *Problem:* five rows sorted by month: two stocks of January and three of February. What is the group array? *Plan:* count the runs of equal months. *Steps:* below.

main.pyPython
months = ["2020-01", "2020-01", "2020-02", "2020-02", "2020-02"]print(group_sizes(months))print(group_sizes(["a", "b", "a"]))
[2, 3]
[1, 1, 1]

*Check:* the answer is [2, 3]: LightGBM reads the first 2 rows as one list and the next 3 as the second. The second line shows the trap: if the rows are not sorted, the same month appears as separate lists ([1, 1, 1]), and the model silently learns from lists that are not what you meant.

02

Scoring a list: DCG and NDCG

Each row gets an integer relevance: here a grade 0 to 4 from the size of its next move inside its month (4 = the largest fifth). A good list puts the high grades at the top. DCG (discounted cumulative gain) adds up a gain for every place, with a discount that makes the top places count most.

DCG@k = Σ for places i = 0 … k−1 of (2^rel[i] − 1) / log2(i + 2)(1)rel[i]: the relevance of the row shown in place i, counting from 0; the gain 2^rel − 1 makes a grade 4 worth 15 and a grade 1 worth 1; the discount is 1 for the first place, 0.63 for the second, 0.5 for the third
NDCG@k = DCG@k of the list in the order of the scores / DCG@k of the best possible order(2)between 0 and 1; 1 means the model put the rows in the best possible order; the best order sorts the relevances from high to low

Worked example 2. *Problem:* a list of six rows has the relevances 3, 2, 3, 0, 1, 2 in the order the model ranked them. What are its DCG and NDCG? And what if only the first place counts (k = 1)? *Plan:* apply equation 1 to the list as given, equation 1 again to the best order 3, 3, 2, 2, 1, 0, and divide. *Steps:* below.

main.pyPython
rel = [3, 2, 3, 0, 1, 2]print(round(dcg(rel, 6), 4), round(dcg(sorted(rel, reverse=True), 6), 4))print(round(ndcg(rel, [6, 5, 4, 3, 2, 1], 6), 4))1rel = np.array([2, 0, 1, 0])scores = np.array([0.1, 0.9, 0.5, 0.3])print(round(ndcg(rel, scores, 4), 4), round(ndcg(rel, scores, 1), 4))2
13.8483 14.5954
0.9488
0.5296 0.0
  1. 1The scores 6, 5, 4 ... keep the list in the order given.
  2. 2k = 1: the model put an irrelevant row first, so the top place is worth nothing.

*Check:* the list as given has a DCG of 13.8483; the best order has 14.5954; the NDCG is 0.9488, close to perfect because the two grade-3 rows are near the top. For the second list, whose scores put the relevance-0 row first, NDCG over four places is 0.5296 and over the first place only it is 0.0. *What to notice:* NDCG at a small k is very strict about the top, and it is the number lambdarank is built to improve.

Why the gain is 2^rel − 1

LightGBM's default label_gain is 2^i − 1, so a grade 4 is worth 15 times a grade 1. If you want a linear reward for grades, pass your own label_gain; the NDCG of your function and LightGBM's must then use the same gains.

03

From pairs to gradients

NDCG cannot be trained directly: it depends on the sorting of the scores, so it is flat almost everywhere and jumps when two rows swap places. LambdaRank's idea is to skip the loss and write the gradients by hand. For every pair of rows i, j in a list where i is more relevant, push i up and j down. The push is the product of two things.

  1. 1
    How wrong the pair isrho = 1 / (1 + exp(sigma × (score_i − score_j))): close to 1 when the less relevant row j has the higher score, close to 0 when the order is right.
  2. 2
    How much it mattersdelta = |gain_i − gain_j| × |discount_i − discount_j| / idcg: the change of NDCG if the two rows swapped places. A swap near the top between very different grades matters most.
  3. 3
    The pushgrad[i] −= sigma × rho × delta and grad[j] += sigma × rho × delta. A negative gradient means "raise this score".
grad[i] −= σ · ρ · Δ, grad[j] += σ · ρ · Δ, hess[i], hess[j] += σ² · ρ (1 − ρ) · Δ(3)for every pair with rel[i] > rel[j]; ρ: how wrong the pair is, Δ: the NDCG change of swapping the two rows; the positions that enter Δ come from the current scores

Worked example 3. *Problem:* a list with the relevances 2, 0, 1, 0. What are the gradients when all four scores are 0, when the scores are 0.1, 0.9, 0.5, 0.3 (the relevant rows are ranked low) and when they are 5, −5, 2, −2 (a good order)? *Plan:* call the function and read the signs. *Steps:* below.

main.pyPython
rel = np.array([2, 0, 1, 0])for scores in (np.zeros(4), np.array([0.1, 0.9, 0.5, 0.3]), np.array([5.0, -5.0, 2.0, -2.0])):    grad, hess = lambda_gradients(rel, scores)    print(grad.round(4).tolist(), round(float(grad.sum()), 12))
[-0.5254, 0.1705, 0.1101, 0.2447] 0.0
[-0.4221, 0.3854, -0.011, 0.0477] 0.0
[-0.01, 0.0001, 0.0089, 0.001] 0.0

*Check:* at equal scores the gradients are -0.5254, 0.1705, 0.1101, 0.2447: the relevance-2 row is pushed up hardest (it is the most negative), the two relevance-0 rows are pushed down. With the relevant rows ranked low the pushes are large (-0.4221 for the top-grade row, +0.3854 for the row that is ranked above it wrongly). With a good order they almost vanish (-0.01 at most). Every list's gradients sum to 0. *What to notice:* the gradients are large exactly where the order is wrong and the error costs NDCG. This is what LightGBM's lambdarank objective feeds to the trees, with an extra normalisation (lambdarank_norm) and a truncation level (lambdarank_truncation_level).

  • FunctionQuestion it answers
  • group_sizes(keys)Where does every list start and end?runs of equal neighbours
  • dcg(rel, k)How good is a list in the order shown?gain 2^rel − 1, log discount
  • ndcg(rel, scores, k)How close to the best order?ties keep the order
  • mean_ndcg(rel, scores, sizes, k)How good are all the lists?each list on its own
  • lambda_gradients(rel, scores, sigma)Which rows should move up or down?pairs weighted by ΔNDCG
04

The panel

Worked example 4. *Problem:* rank the 56 stocks of each month by the size of their next move. Train a lambdarank model on the fit months (before 2011) and compare, on the valid (2011 to 2014) and test months (2015 onwards), with a plain regression on move, with ranking by vol alone, with a random order and with the perfect order. *Plan:* labels and group sizes per period; the metric is the mean NDCG@10 of your function, and LightGBM reports its own NDCG@10 so that the two can be compared. *Steps:* below.

main.pyPython
panel = build_panel(load_close())fit, valid, test = split_panel(panel)labels = {"fit": relevance_labels(fit), "valid": relevance_labels(valid), "test": relevance_labels(test)}sizes = {"fit": group_sizes(fit["date"]), "valid": group_sizes(valid["date"]), "test": group_sizes(test["date"])}ranker = lgb.LGBMRanker(objective="lambdarank", n_estimators=100, learning_rate=0.05, num_leaves=8, min_child_samples=20, n_jobs=1, random_state=0, verbose=-1)1ranker.fit(fit[FEATURES], labels["fit"], group=sizes["fit"], eval_set=[(valid[FEATURES], labels["valid"])], eval_group=[sizes["valid"]], eval_at=[10])regressor = lgb.LGBMRegressor(n_estimators=100, learning_rate=0.05, num_leaves=8, min_child_samples=20, n_jobs=1, random_state=0, verbose=-1).fit(fit[FEATURES], fit[TARGET])rng = np.random.default_rng(0)2rows = {"ranker": ranker.predict, "regressor": regressor.predict, "vol": lambda X: X["vol"].to_numpy(), "random": lambda X: rng.normal(size=len(X))}for name, score in rows.items():    print(f"{name:>9}", *(round(mean_ndcg(labels[part], score(frame[FEATURES]), sizes[part], 10), 4) for part, frame in (("valid", valid), ("test", test))))print(round(mean_ndcg(labels["valid"], ranker.predict(valid[FEATURES]), sizes["valid"], 10), 6), round(ranker.evals_result_["valid_0"]["ndcg@10"][-1], 6))print(len(sizes["fit"]), len(sizes["valid"]), len(sizes["test"]), sizes["fit"][0])
   ranker 0.5111 0.4742
regressor 0.5268 0.4771
      vol 0.5039 0.4769
   random 0.3524 0.3335
0.511095 0.511095
120 48 139 54
  1. 1group= tells LightGBM where each month starts and ends.
  2. 2Four ways to score the rows, evaluated in the same way.

*Check:* there are 120 fit lists, 48 valid and 139 test, with 54 stocks in the first one. On the valid months the ranker has an NDCG@10 of 0.5111, the regression 0.5268, the volatility column alone 0.5039, a random order 0.3524, and the perfect order is 1.0. On the test months they are 0.4742, 0.4771, 0.4769 and 0.3335. Your NDCG@10 and LightGBM's own agree to the last digit (0.511095 for the ranker). *What to notice:* every model is far above a random order and far below perfect, and they are all close to each other. The rule "a volatile stock moves a lot" is most of what these three features know, and a regression finds it as well as a ranker does. A ranking objective is not a better model by itself: it is the right tool when the top of the list matters and the scores of different lists are not comparable.

When lambdarank helps

A ranker pays off when the label is already an order (clicks, analyst ratings, which stocks beat the market), when only the top places matter, and when the level of the scores changes from list to list. Here the target move is a size that the regression models directly, so the two end up close. On a harder target the ranker may do better or worse; test it against the simple baselines before assuming.

What the real data says56 US stocks; lists = months; 120 fit, 48 valid, 139 test
Ranker0.5111NDCG@10 on valid; 0.4742 on test
Regression on move0.5268NDCG@10 on valid; 0.4771 on test
Volatility alone0.5039NDCG@10 on valid; 0.4769 on test
Random order0.3524the floor; the perfect order is 1.0
Gap to LightGBM0your NDCG@10 equals the one LightGBM reports

Key takeaways

  • Rank inside a list. Sort the rows by list, pass group=sizes, and never compare scores across lists.
  • NDCG rewards the top. A gain of 2^rel − 1 and a discount of 1 / log2(place + 1) make a good list one that puts the high grades first.
  • Lambdarank writes the gradient by hand. Each pair of rows is pushed apart by σ ρ Δ, where ρ says how wrong the pair is and Δ how much NDCG a swap would change.
  • A ranker is not automatically better. On this panel the regression and a single column rank about as well; compare with simple baselines before trusting a model.
Quick check
Your turn. A list has three rows with the relevances 2, 0 and 1. The model puts them in the order 1, 2, 0 (best first). Is NDCG@3 of this order equal to 1?
Pick an answer.
05

What you will build

The lab follows the lecture. Task 1 builds the group array. Tasks 2 to 4 are the score: DCG, NDCG of one list and the mean over many lists. Task 5 writes the lambdarank gradients for one list. Task 6 trains a ranker on the real panel, compares it with a regression and three simple baselines, and checks your NDCG against LightGBM's.

Next topic: you have models and scores; you also want to know why a model says what it says. The next topic, Model interpretation, reads a LightGBM model with split counts, gain and SHAP values, and shows why the three disagree.

Lab · what's graded

6 tasks · 100 pts
  • Group sizes10 pts
  • DCG10 pts
  • NDCG of a list15 pts
  • NDCG of many lists10 pts
  • Lambdarank gradients25 pts
  • Ranking stocks month by month30 pts
Explorer · lab-lg-06
▾ lab-lg-06
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-lg-06$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-lg-06 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