Split 56 tickers into two groups and there are 36,028,797,018,963,967 ways to do it. LightGBM looks at 55 of them and still finds the best one. This topic builds that search, and then shows on real stocks that a column LightGBM can cut this cleanly is not always one it should.
Why a number is the wrong code for a label
Where we are. So far every column was a number, and a cut meant "is x at most this threshold?". A ticker, a sector or a calendar month is a label. The quick fix is to replace each label by a number (A = 0, B = 1, ...), but then every cut is a cut in an arbitrary order: it can separate {A, B} from {C, D, E, F} and never {A, C, E} from {B, D, F}.
A question of the form "is the label in this set?". The rows whose label is in the set go left, all the others (also labels the tree has never seen) go right.
Worked example 1. *Problem:* six labels A to F, three rows each, with the target 1, 9, 2, 8, 1, 9 for A..F: the labels A, C, E are low and B, D, F are high, mixed in the alphabet. How good is the best cut if the labels are numbers, and how good if they are labels? *Plan:* the gain of a cut is S_L²/n_L + S_R²/n_R − S²/n (equation 1 of the first topic), where S is a sum of the target and n a count. For numbers, cut after each label in alphabetical order. For labels, best_category_split will do the search. *Steps:* below.
cats = np.array(list("ABCDEF") * 3)target = np.array([1.0, 9.0, 2.0, 8.0, 1.0, 9.0] * 3)labels, sums, counts = category_stats(cats, target)1code_sum = np.cumsum(sums)[:-1]code_n = np.cumsum(counts)[:-1]2code_gain = code_sum**2 / code_n + (sums.sum() - code_sum) ** 2 / (18 - code_n) - sums.sum() ** 2 / 18print("labels as numbers:", code_gain.round(1).tolist())print("labels as labels: ", best_category_split(cats, target))
labels as numbers: [57.6, 0.0, 18.0, 0.0, 57.6] labels as labels: (['A', 'C', 'E'], 242.0)
- 1Sums on the left of every cut, in alphabetical order.
- 2The gain of each of the 5 numeric cuts.
*Check:* the five numeric cuts gain at most 57.6 (after A, or after E). The categorical cut {A, C, E} against {B, D, F} gains 242: 12²/9 + 78²/9 − 90²/18 = 16 + 676 − 450. *What to notice:* the numeric code hid the pattern, the label cut finds it in one question. The code 0..5 told the tree an order that does not exist.
Sort by the mean, then cut
Finding the best group of labels looks hard: for k labels there are 2^(k−1) − 1 ways to split them into two non-empty groups (fix the first label on the left; each of the other k − 1 labels is on the left or not; remove the case where the right group is empty). For 6 labels that is 31, for the 12 months 2,047, for 56 tickers 36,028,797,018,963,967.
For a squared error there is a shortcut, proved by W. D. Fisher in 1958. Sort the labels by the mean of the target. The best split is a prefix of that order: the first k labels go left, the others right. So only k − 1 splits need a look, and best_category_split computes them with cumulative sums, as for a numeric column.
Worked example 2. *Problem:* find the best split of the labels of example 1 by sorting, and check that no other split of the 31 is better. *Plan:* order the labels by their score (the mean minus the overall mean), take cumulative sums over the ordered labels, compute the gain of the 5 prefixes; then run the slow search over all the splits. *Steps:* below.
cats = np.array(list("ABCDEF") * 3)target = np.array([1.0, 9.0, 2.0, 8.0, 1.0, 9.0] * 3)labels, sums, counts = category_stats(cats, target)scores = category_scores(sums, counts)1order = np.argsort(scores, kind="stable")2left_sum = np.cumsum(sums[order])[:-1]left_n = np.cumsum(counts[order])[:-1]gain = left_sum**2 / left_n + (sums.sum() - left_sum) ** 2 / (18 - left_n) - sums.sum() ** 2 / 18print(labels[order].tolist(), scores[order].tolist())print(gain.round(1).tolist())3print(best_subset_split(cats, target))
['A', 'E', 'C', 'D', 'B', 'F'] [-4.0, -4.0, -3.0, 3.0, 4.0, 4.0] [57.6, 144.0, 242.0, 144.0, 57.6] (242.0, 31)
- 1The labels in the order of their mean.
- 2Sums over the first k labels of that order.
- 3The slow search: the best gain and how many splits it tried.
*Check:* the order is A, E, C, D, B, F (scores −4, −4, −3, 3, 4, 4: A and E tie and keep their alphabetical order). The five prefixes gain 57.6, 144, 242, 144, 57.6; the best is the third, {A, E, C}, with 242. The slow search over all 31 splits also finds 242. *What to notice:* the best split has the low labels together and the high labels together, whatever the alphabet says. Five steps replaced thirty-one.
Suppose a split puts a low label on the right and a high label on the left, with the labels between them in either group. Swapping the two labels into the group where their mean fits always lowers the squared error or leaves it equal. So the best split never "crosses", and every crossing-free split is a prefix of the order by mean. That argument needs the squared error; for other losses LightGBM sorts by the ratio of the sum of the gradients to the sum of the second derivatives, and the same scan applies.
Smoothing and rare labels
The mean of a label with one row is that row's value. A label seen once with an extreme value would go to an end of the order, and a tree could then isolate it, which learns that one row and nothing more. LightGBM guards against this with cat_smooth: the order is not by the mean but by a score that shrinks the deviation of a label towards 0 by the number of rows it has.
Only the order uses the smoothed score. The gain of each prefix still uses the true sums and counts. Worked example 3. *Problem:* four labels with 1, 2, 10, 12 rows and the constant targets 1, 0, 3, 2. Does smoothing change the best split? *Plan:* compute the scores and the best split for smooth = 0 and smooth = 10. *Steps:* below.
cats = np.repeat([1, 2, 3, 4], [1, 2, 10, 12])target = np.repeat([1.0, 0.0, 3.0, 2.0], [1, 2, 10, 12])labels, sums, counts = category_stats(cats, target)for smooth in (0, 10): print(smooth, category_scores(sums, counts, smooth).round(3).tolist(), best_category_split(cats, target, smooth))
0 [-1.2, -2.2, 0.8, -0.2] ([1, 2], 11.878787878787875) 10 [-0.109, -0.367, 0.4, -0.109] ([1, 2, 4], 10.666666666666657)
*Check:* without smoothing the order is 2, 1, 4, 3 and the best split is {1, 2} with gain 11.88. With smooth = 10 the label with a single row (label 1) loses most of its deviation: its score goes from −1.2 to −0.109, level with label 4, and the best prefix is {1, 2, 4} with gain 10.67. *What to notice:* smoothing does not change the gain formula, only which prefixes are candidates. In LightGBM the rest of the guard is min_data_per_group (a group needs that many rows, 100 by default) and max_cat_threshold (how many labels can move to one side, 32 by default).
A stump on labels
A tree with one categorical cut has the set of left labels and one value for each side. A label that was not in the training data (a new ticker, say) is in no set, so it goes right. LightGBM does the same.
- FunctionQuestion it answers
- category_stats(categories, y)How many rows and what sum per label?np.unique, np.bincount
- category_scores(sums, counts, smooth)In what order do the labels go?shrunk towards 0
- best_category_split(categories, y, smooth, min_leaf)Which labels go left?sorted scan
- best_subset_split(categories, y, min_leaf)Is that really the best of all splits?2^(k−1) − 1 splits
- stump_fit(categories, y, smooth, min_leaf)What is the one-cut tree?mean on each side
- stump_predict(stump, categories)What does it say for each row?unseen goes right
The panel
Worked example 4. *Problem:* the calendar month of the month-end is a natural label with 12 values. Does the best group of months have a clear pattern, and does it hold on the later rows (2011 to 2014)? *Plan:* find the best split of the 12 months on the fit rows with the sorted scan and with the slow search, then use the stump on the valid rows. *Steps:* below.
panel = build_panel(load_close())fit, valid, test = split_panel(panel)y, y_valid = fit[TARGET].to_numpy(), valid[TARGET].to_numpy()months = month_of(fit)1cut = best_category_split(months, y)brute, tried = best_subset_split(months, y)stump = stump_fit(months, y)2print(cut, brute, tried)print(round(rmse(y_valid, stump_predict(stump, month_of(valid))), 5), round(rmse(y_valid, y.mean()), 5))
([1, 2, 4, 5, 7, 11, 12], 0.23496601355371283) 0.23496601355371283 2047 0.04304 0.04271
- 1The sorted scan: 11 prefixes.
- 2The valid error of the stump, against the error of the plain fit mean.
*Check:* the sorted scan and the slow search agree on a gain of 0.2350, after 11 steps against 2,047. The months 1, 2, 4, 5, 7, 11, 12 go left (a calmer group) and the others right. On the valid rows the stump has an error of 0.04304, worse than the 0.04271 of the plain mean. *What to notice:* the pattern is real in the fit years (2001 to 2010 include 2008 and 2009) and gone afterwards. A cut can be the best on the data it was fitted on and still carry no information about later months.
Worked example 5. *Problem:* now the ticker, a label with 56 values and about 120 rows each. How many splits are there, how much does smoothing reorder the labels, and does a stump on the ticker help on the valid rows? *Plan:* the same functions on the ticker column; for the order, compare the arrangement of the labels with smooth = 0 and smooth = 200. *Steps:* below.
tickers = fit["ticker"].to_numpy()labels, sums, counts = category_stats(tickers, y)cut = best_category_split(tickers, y)plain = np.argsort(category_scores(sums, counts, 0.0), kind="stable")smooth = np.argsort(category_scores(sums, counts, 200.0), kind="stable")stump = stump_fit(tickers, y)print(len(labels), 2 ** (len(labels) - 1) - 1, round(cut[1], 4), len(cut[0]), int(np.sum(plain != smooth)))print(round(rmse(y_valid, stump_predict(stump, valid["ticker"].to_numpy())), 5))print(sorted(counts.tolist())[:3], labels[np.argmin(counts)])
56 36028797018963967 1.7494 39 8 0.04244 [59, 65, 120] MS
*Check:* 56 labels, 36,028,797,018,963,967 possible splits, a best gain of 1.7494 with 39 labels on the left. Raising smooth to 200 changes the position of 8 labels; most labels have 120 rows, but MS has only 59 and another label 65, so their scores shrink more than the others'. The ticker stump gets 0.04244 on the valid rows, a little better than the mean (0.04271). *What to notice:* one cut on the ticker is a mild, reasonable thing to learn. Whether a model with many cuts is, is the next experiment.
Finally the models. In LightGBM a column is categorical when its dtype is category (a pd.Categorical). Compare five models with 8 leaves and 150 trees on the same fit rows: the three features alone; plus the ticker as a number (alphabetical order); plus the ticker as a category; plus the month as a number; plus the month as a category. Score on the valid rows.
all_tickers = sorted(panel["ticker"].unique())number = {t: i for i, t in enumerate(all_tickers)}def columns(frame, kind): out = frame[FEATURES].copy() if kind == "ticker_number": out["ticker"] = frame["ticker"].map(number).to_numpy() elif kind == "ticker_category": out["ticker"] = pd.Categorical(frame["ticker"], categories=all_tickers)1 elif kind == "month_number": out["month"] = month_of(frame) elif kind == "month_category": out["month"] = pd.Categorical(month_of(frame), categories=list(range(1, 13)))2 return outfor kind in ("none", "ticker_number", "ticker_category", "month_number", "month_category"): model = lgb.LGBMRegressor(n_estimators=150, learning_rate=0.05, num_leaves=8, min_child_samples=20, n_jobs=1, random_state=0, verbose=-1) model.fit(columns(fit, kind), y) print(f"{kind:>16}: {rmse(y_valid, model.predict(columns(valid, kind))):.5f}")
none: 0.03672
ticker_number: 0.03685
ticker_category: 0.03782
month_number: 0.03637
month_category: 0.03657- 1A category column: LightGBM sees the dtype and uses categorical cuts.
- 2The month, as a category with its 12 possible values.
*Check:* the model without any label scores 0.03672. The ticker as a number gives 0.03685, the ticker as a category 0.03782: the categorical ticker is the worst of the five, because with 56 labels of 120 rows each the trees learn the history of each stock, which did not repeat in 2011 to 2014. The month as a number gives 0.03637 and as a category 0.03657, both within 0.0004 of no month: the month carries almost nothing here, and treating it as a label changes little. *What to notice:* a categorical column helps when the groups mean the same thing in the future (a sector, an exchange, a type of order). A label that is nearly an identifier, like a ticker, lets the model memorise instead.
One last check against LightGBM itself: a single categorical cut on the fit rows, with the smoothing and size guards switched off, compared with our best split.
codes = {t: i for i, t in enumerate(all_tickers)}one = pd.DataFrame({"ticker": pd.Categorical(fit["ticker"].map(codes), categories=range(56))})stump_model = lgb.LGBMRegressor(n_estimators=1, learning_rate=1.0, num_leaves=2, min_child_samples=1, min_child_weight=0, reg_lambda=0, cat_smooth=0, cat_l2=0, min_data_per_group=1, max_cat_threshold=100, max_cat_to_onehot=1, n_jobs=1, random_state=0, verbose=-1)stump_model.fit(one, y)split = stump_model.booster_.trees_to_dataframe().loc[0]print(round(float(split["split_gain"]), 4), len(str(split["threshold"]).split("||")))
1.6977 16
*Check:* LightGBM reports a gain of 1.6977 with 16 labels on one side; ours is 1.7494 with 39 on the other (the same as 17 on the first side). So LightGBM lands on a nearly identical partition, one label short: it holds MS, with 59 rows, back on the other side. It has extra rules of its own, which is why the sorted scan of this lab is the idea of its search, not a line-by-line copy.
What you will build
The lab follows the lecture. Task 1 summarises each label, task 2 scores the labels. Task 3 is the sorted scan, task 4 the slow search that proves it right. Tasks 5 and 6 fit and apply a one-cut tree. Task 7 runs everything on the real panel and compares five LightGBM models.
Next topic: a model that predicts "a large move" yes or no has a different problem: large moves are rare. The next topic, Imbalanced targets, shows what the loss, the weights and the threshold do when 9 rows in 10 are "no".
Lab · what's graded
7 tasks · 100 pts- Label statistics10 pts
- Label scores10 pts
- The sorted scan20 pts
- Every split15 pts
- Fit a one-cut tree12 pts
- Apply a one-cut tree8 pts
- Categories on the panel25 pts