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.
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.
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.
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.
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.
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.
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
- 1The scores 6, 5, 4 ... keep the list in the order given.
- 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.
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.
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.
- 1How wrong the pair is
rho = 1 / (1 + exp(sigma × (score_i − score_j))): close to 1 when the less relevant rowjhas the higher score, close to 0 when the order is right. - 2How much it matters
delta = |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. - 3The push
grad[i] −= sigma × rho × deltaandgrad[j] += sigma × rho × delta. A negative gradient means "raise this score".
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.
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
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.
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- 1group= tells LightGBM where each month starts and ends.
- 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.
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 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