LightGBM:分箱、叶数预算与选择性计算
LightGBM
计算直方图分裂与按叶生长,核查 GOSS 加权和严格互斥特征编码。
lightgbm把下一次分裂用在收益最大的地方
传感器有八档,编号为 0 到 7,对应修正目标为 0、1、0、1、5、5、9、9。一棵树先把前四档与后四档分开。预算只剩一次分裂,应该处理左侧的小幅波动,还是把右侧的 5 与 9 分开?
按叶生长面对的就是这个选择:在现有叶子之间比较可获得的改善。LightGBM 把这种生长策略与直方图分裂搜索结合;2017 年论文另外提出了减少计算量的两项技术:基于梯度的单侧采样 GOSS,以及互斥特征捆绑 EFB。原论文;LightGBM 4.6.0 功能说明。
本章程序从调用方给定的分箱构建一棵精确小回归树,比较两种生长顺序,并分别核算 GOSS 与 EFB 的小例子。它不训练 LightGBM 库或完整提升集成。树外层的修正与二阶目标见梯度提升和 XGBoost。
分箱、叶子与采样改变不同决策
直方图保存允许切分所需的统计量
给定递增阈值 ,将 x 放入第一个上界不小于 x 的箱;没有这样的上界则放入最后一个箱。相等值归左侧箱。每箱 b 累加样本数、目标和与目标平方和。非空的一组箱,其未归一化平方误差为:
最优常数预测为 S/N;围绕该均值展开平方误差即可验证公式。用前缀和便能给每条允许边界评分,无须逐次重扫其中的样本。本章目标是固定的修正量,损失为完整 SSE,不加叶权正则。因此分裂改善为:
两个子节点都须满足 min_leaf,且改善严格为正。允许空箱,不允许空子节点。对分箱限制下的问题,公式完全精确;同一箱内的好阈值却无法选择。即使算术与直方图累加精确,候选集合本身仍是一种近似。
不相交样本集的直方图可以相加。节点分裂后,只构建较小子节点的直方图,从父直方图减去它,便得到另一子节点的统计。这个恒等式逐项适用于计数、和与平方和,前提是父子使用相同分箱定义。LightGBM 用这种相减减少直方图构建工作。固定版本功能说明:直方图相减。
生长顺序决定怎样使用叶数预算
每次分裂使叶数增加一。最佳优先顺序选择当前允许改善最大的叶子。代码中的对照顺序先扩展最浅的可分裂叶,同深度按创建顺序破同分。这是带硬叶数上限的明确广度优先对照,预算可以让它在一层中途停下。
传感器例子的右子节点可改善 16,左子节点最佳改善为 1/3。因此最佳优先把最后一次分裂用在右侧。这并不证明贪心生长总能找到固定叶数下的全局最优树:眼前的收益可能遮住后续有价值的切分。当最佳优先不断扩展同一分支时,深度限制仍然有作用。固定版本生长说明。
GOSS 校正抽样和,不会自动校正所有非线性评分
先固定当前梯度,保留绝对梯度较大的集合 A;其余 R 条样本组成 U,再从 U 均匀无放回抽取恰好 r 条,1≤r≤R。每条低梯度样本被选中的概率为 r/R。对于任何固定区域 J,加权估计为:
逐项对入选指示变量取期望,即得该等式。按论文算法 2 的数量约定,a=|A|/n、b=r/n,乘数就是 (1−a)/b。如果另一种表述把采样比例定义为占剩余池的比例,乘数应取该比例的倒数。必须说清分母。原论文算法 2 与第 3 节。
这个结论针对固定的和。将估计平方会额外带入其方差:
非线性增益式、估计出的分母,以及从估计增益中选择最大者,都需要另行分析。不能因为梯度和无偏,就认定这些量也无偏。本章审计枚举所有低梯度子集来揭示区别,不是快速采样实现。
EFB 需要没有歧义的编码
假设特征 j 的非零整数箱为 1,…,cⱼ,零表示未激活。以之前各特征容量之和作为偏移。如果每行至多一个特征激活,则编码为:
非零区间互不重叠,所以 z 同时决定特征身份与原始箱,其余特征均为零。因此可以恢复箱统计,而不必把打包后的编码当作普通有序特征。对打包码做一次大小切分,不一定对应某个原始特征的切分。论文区分了组建捆绑与重建原始特征直方图,并将允许冲突作为近似讨论。本章打包器只接受严格互斥,拒绝冲突行。论文第 4 节。
看清省了什么,也看清丢了哪些切分
输入使用整数或 Fraction,拒绝布尔值与浮点数。fit 要求非空、长度一致的数据及严格递增切点;空切点列表是合法的单箱问题。max_leaves 至少为一,min_leaf 至少为一,max_depth 不设或为非负整数。根的样本数可以小于 min_leaf,该限制作用于候选子节点。同分的正增益保留较小箱边界;叶增益同分保留较小节点编号。
模型保存真实节点、训练预测和分裂事件。每条事件记录扩展节点、深度、箱边界、SSE 改善及用于构建较小直方图的样本数。histogram_row_updates 统计根构建与这些较小子节点的累加,不计划分样本、扫描候选或全部运行操作。辅助函数假定接收 fit 内部产生的直方图;predict 要求未经修改的拟合模型。
from bisect import bisect_left
from fractions import Fraction as F
from itertools import combinations
from math import comb
def number(x):
if type(x) not in (int, F):
raise ValueError('use integers or Fraction values')
return F(x)
def vector(xs, empty=False):
if type(xs) not in (list, tuple) or (not xs and not empty):
raise ValueError('expected a nonempty list or tuple')
return tuple(number(x) for x in xs)
def integer(x, low):
if type(x) is not int or x < low:
raise ValueError('invalid integer control')
return x
def histogram(ids, bins, ys, size):
counts, sums, squares = [0]*size, [F(0)]*size, [F(0)]*size
for i in ids:
b = bins[i]
counts[b] += 1
sums[b] += ys[i]
squares[b] += ys[i]*ys[i]
return tuple(zip(counts, sums, squares))
def difference(parent, child):
return tuple(tuple(a-b for a, b in zip(p, c))
for p, c in zip(parent, child))
def best_split(hist, min_leaf):
n = sum(row[0] for row in hist)
total = sum((row[1] for row in hist), F(0))
left_n, left_sum, best = 0, F(0), None
for cut in range(len(hist)-1):
left_n += hist[cut][0]
left_sum += hist[cut][1]
right_n = n-left_n
if min(left_n, right_n) < min_leaf:
continue
gain = left_sum**2/left_n + (total-left_sum)**2/right_n - total**2/n
if gain > 0 and (best is None or gain > best[0]):
best = (gain, cut)
return best
def fit(xs, ys, cuts, max_leaves=3, min_leaf=1, max_depth=None,
policy='leaf'):
xs, ys, cuts = vector(xs), vector(ys), vector(cuts, empty=True)
if len(xs) != len(ys) or any(a >= b for a, b in zip(cuts, cuts[1:])):
raise ValueError('matching data and strictly increasing cuts required')
integer(max_leaves, 1)
integer(min_leaf, 1)
if max_depth is not None:
integer(max_depth, 0)
if policy not in ('leaf', 'breadth'):
raise ValueError('policy must be leaf or breadth')
bins = tuple(bisect_left(cuts, x) for x in xs)
size = len(cuts)+1
nodes, leaves, events = {}, {}, []
hist_updates = len(xs)
def add_node(node, ids, hist, depth):
total = sum((r[1] for r in hist), F(0))
mean = total/len(ids)
candidate = None if max_depth is not None and depth >= max_depth else best_split(hist, min_leaf)
nodes[node] = ('leaf', mean)
leaves[node] = (ids, hist, depth, candidate)
add_node(0, tuple(range(len(xs))), histogram(range(len(xs)), bins, ys, size), 0)
while len(leaves) < max_leaves:
eligible = [node for node, data in leaves.items() if data[3] is not None]
if not eligible:
break
if policy == 'leaf':
node = min(eligible, key=lambda j: (-leaves[j][3][0], j))
else:
node = min(eligible, key=lambda j: (leaves[j][2], j))
ids, parent_hist, depth, (gain, cut) = leaves.pop(node)
left = tuple(i for i in ids if bins[i] <= cut)
right = tuple(i for i in ids if bins[i] > cut)
small = left if len(left) <= len(right) else right
small_hist = histogram(small, bins, ys, size)
other_hist = difference(parent_hist, small_hist)
left_hist, right_hist = (small_hist, other_hist) if small is left else (other_hist, small_hist)
hist_updates += len(small)
a, b = len(nodes), len(nodes)+1
nodes[node] = ('split', cut, a, b)
add_node(a, left, left_hist, depth+1)
add_node(b, right, right_hist, depth+1)
events.append((node, depth, cut, gain, len(small)))
predictions = [F(0)]*len(xs)
for node, (ids, _, _, _) in leaves.items():
for i in ids:
predictions[i] = nodes[node][1]
return {'cuts': cuts, 'nodes': nodes, 'events': tuple(events),
'predictions': tuple(predictions),
'sse': sum(((p-y)**2 for p, y in zip(predictions, ys)), F(0)),
'histogram_row_updates': hist_updates}
def predict(model, xs):
values = vector(xs, empty=True)
result = []
for x in values:
b, node = bisect_left(model['cuts'], x), 0
while model['nodes'][node][0] == 'split':
_, cut, left, right = model['nodes'][node]
node = left if b <= cut else right
result.append(model['nodes'][node][1])
return tuple(result)
def goss_moments(gradients, keep, take):
g = vector(gradients)
integer(keep, 0)
integer(take, 1)
if keep >= len(g) or take > len(g)-keep:
raise ValueError('need a nonempty low-gradient pool and valid take')
order = sorted(range(len(g)), key=lambda i: (-abs(g[i]), i))
high, low = order[:keep], order[keep:]
factor = F(len(low), take)
fixed = sum((g[i] for i in high), F(0))
first, second = F(0), F(0)
for chosen in combinations(low, take):
estimate = fixed + factor*sum((g[i] for i in chosen), F(0))
first += estimate
second += estimate**2
count = comb(len(low), take)
return {'high': tuple(high), 'weight': factor, 'outcomes': count,
'mean_sum': first/count, 'mean_squared_sum': second/count}
def pack_exclusive(rows, caps):
if type(caps) not in (list, tuple) or not caps:
raise ValueError('nonempty bin capacities required')
caps = tuple(integer(c, 1) for c in caps)
if type(rows) not in (list, tuple):
raise ValueError('rows must be a list or tuple')
offsets, total = [], 0
for c in caps:
offsets.append(total)
total += c
packed = []
for row in rows:
if type(row) not in (list, tuple) or len(row) != len(caps):
raise ValueError('incorrect row width')
active = []
for j, (value, cap) in enumerate(zip(row, caps)):
integer(value, 0)
if value > cap:
raise ValueError('bin value exceeds its capacity')
if value:
active.append(offsets[j]+value)
if len(active) > 1:
raise ValueError('exclusive bundle has a conflicting row')
packed.append(active[0] if active else 0)
return tuple(packed), tuple(offsets)
if __name__ == '__main__':
xs, ys = list(range(8)), [0, 1, 0, 1, 5, 5, 9, 9]
cuts = [F(2*i+1, 2) for i in range(7)]
for policy in ('leaf', 'breadth'):
model = fit(xs, ys, cuts, policy=policy)
print(policy, 'split nodes', tuple(e[0] for e in model['events']),
'SSE', model['sse'], 'histogram updates', model['histogram_row_updates'])
coarse = fit([0, 1, 2, 3], [0, 0, 4, 4], [F(5, 2)], max_leaves=2)
fine = fit([0, 1, 2, 3], [0, 0, 4, 4], [F(1, 2), F(3, 2), F(5, 2)], max_leaves=2)
print('coarse / fine SSE:', coarse['sse'], fine['sse'])
moments = goss_moments([6, 2, -1, 1], 1, 1)
print('GOSS weight / mean / mean square:', moments['weight'], moments['mean_sum'], moments['mean_squared_sum'])
print('exclusive codes:', pack_exclusive([(0, 0), (2, 0), (0, 1), (0, 2)], [2, 2])[0])
实际输出:
leaf split nodes (0, 2) SSE 1 histogram updates 14
breadth split nodes (0, 1) SSE 50/3 histogram updates 13
coarse / fine SSE: 32/3 0
GOSS weight / mean / mean square: 3 8 78
exclusive codes: (0, 2, 3, 4)
两种顺序都先在 3.5 分裂根。三叶预算下,最佳优先留下 SSE 1,广度优先对照留下 50/3。直方图行更新数分别为 14、13,也说明更低损失并不意味着每一种工作计数都更小。比较固定了分箱、叶数上限与目标。
四点例子的理想分隔阈值为 1.5。只提供 2.5 时,值 0、1、2 被合到一箱,被迫留下 SSE 32/3;更细的候选集合达到零。边界一旦省略,仅在箱内做更精确的加法,无法将它重新创造出来。
GOSS 例子的梯度为 6、2、−1、1,保留 6,从另三条中抽一条。可能的加权和为 12、3、9,均值为真实和 8,但平方的均值是 78,而不是 64。EFB 中容量 (2,2) 给出特征区间 1—2 和 3—4;编码 (0,2,3,4) 可唯一还原四条输入行。行 (1,1) 会被拒绝,而非悄悄覆盖其中一项。
这个实现的成本
令 n 为样本数、B 为箱数、S 为实际分裂数。输入分箱需要 O(n log(B+1)+B)。每次分裂扫描所在样本完成划分,构建一个较小直方图,扫描 O(B) 统计,并在至多 S+1 个已缓存叶候选中选择。有效最坏总界为 O(n log(B+1)+B+S(n+B)+S²),包含 S=0。工作存储与返回模型共占 O(n+(S+1)B+S) 槽位;叶样本列表划分全部数据,而每个当前叶保留自己的直方图。预测 m 个点需 O(1+m(log(B+1)+d+1)) 次操作、O(1+m) 槽位,d 为返回树的深度。
GOSS 审计因枚举子集,需要 O(n log(n+1)+C(R,r)(r+1)) 次操作、O(n+r) 槽位。打包 n 行 p 个特征需要 O(p+np) 次操作、O(p+n) 槽位,也涵盖空行集合。以上按精确算术与比较、期望常数字典访问计数;有理数增长另加位成本。这些都不是编译版库的训练速度结论。
这些优化选择不能互相替代
分箱改变允许在哪里切分,最佳优先生长改变扩展哪个叶子,GOSS 按当前梯度抽取样本,EFB 改变稀疏特征表示。启用其中一项,不表示其他项也在使用,也不表示每次分裂决策都不变。
固定的 4.6.0 版中,data_sample_strategy 默认为 bagging,不是 goss;enable_bundle 默认为 true。Bagging 本身也要同时满足正的采样频率与小于一的比例,才会抽取行。这些是带版本的设置,不是提升的定义。官方参数;捆绑设置。
本章树没有缺失值路由、类别切分、样本权重、多特征、单调约束与多轮提升。切点由外部提供,不由库的分箱器学习。此类预处理应只在训练部分上学习,再固定映射评估留出样本。更小的箱可能恢复有用切分,也可能容许对噪声更细的拟合。
绝对梯度大,不一定表示样本干净且有信息;离群点或标签错误也可能产生大梯度。上面的和恒等式以当前梯度和固定区域为条件,用同一批随机估计来选择区域,还会增加选择效应。同样,观测冲突率低,不是 EFB 精确可逆的证明。即使训练中没有冲突,未来一行若同时激活两个特征,也违反本章打包器约定。
分清表示、顺序与估计
- 四点粗直方图为何不能在 1.5 切分?答案:它只有切点 2.5,0、1、2 共用一箱;允许切分集合没有箱内边界。其最佳双叶 SSE 为 32/3,更细集合可达到零。
- 根的两个可分裂子节点分别能改善 1/3、16,只剩一次分裂。代码两种策略各选哪个?答案:
leaf选 16;breadth在同深度选较小编号,即本例改善 1/3 的左子节点。两种策略都不改变切分评分公式。 - GOSS 保留梯度 6,从 2、−1、1 抽一条。求采样乘数、估计和的均值与方差。答案:乘数为 3,估计值 12、3、9 平均为 8;平方均值为 78,方差为 78−8²=14。和无偏,不表示平方和也无偏。
- 容量 (2,2) 时,能把行 (1,1) 安全地替换为编码 1+3=4 吗?答案:不能,4 已表示合法行 (0,2),相加激活编码会破坏单射。精确打包须拒绝冲突或使用更丰富表示;悄悄接受会改变问题。
减少计算,也要看清改动发生在哪里
Ke 等人的 2017 年论文围绕 GOSS 与 EFB,构建基于直方图的提升实现。固定版本功能指南解释直方图相减与最佳优先叶生长;参数参考则区分可用技术与已启用设置。这是三类不同证据:算法提案、实现设计与带版本的接口。
可继续做一个对照实验:先固定梯度,仅改变箱边界;再固定分箱,仅改变扩展顺序;最后考察采样。这样就能将切分变化追溯到某个具体近似或顺序决策,而非统统归因于库名。关于模型大小控制与验证,可回到 CART和过拟合。
先判断,再看解释
GOSS 加权和的均值为真实和 8,且方差为正,其平方的均值必须为 64 吗?
学习目标
- 区分分箱限制的切分搜索与叶扩展顺序。
- 解释并核查直方图相减及共用分箱要求。
- 推导 GOSS 和的加权,区别于非线性增益无偏,并识别精确 EFB 冲突。
先修与延伸
查看知识关联图 →参考文献
- LightGBM: A Highly Efficient Gradient Boosting Decision Tree
Guolin Ke, Qi Meng, Thomas Finley, Taifeng Wang, Wei Chen, Weidong Ma, Qiwei Ye and Tie-Yan Liu · 2017 - Features — LightGBM 4.6.0
LightGBM contributors - Parameters — LightGBM 4.6.0
LightGBM contributors
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- 7 项测试通过。原始样本划分与两两离差独立核对 36 例事件、训练预测、SSE,并核 histogram_row_updates 和训练 predict;另 4 例深度/最小叶约束只比较事件、训练预测与 SSE;3 例相减逐箱直接核对。主例另与全部 21 个三段划分比较,不推广为贪心全局最优结论。
- 24 份 GOSS 审计与独立有限总体方差式一致,涵盖全采样、同分、正负与零梯度。7 条严格互斥行往返还原,恢复 9 项原始箱统计;拒绝冲突行并展示直接相加编码碰撞。核查输入约定、相等路由、常值、空切点/查询与输入保留。
- 原创双语、相同完整 Python 与五行实际输出、5 显示式、6 锚点、4 已答练习。严格 MDX/KaTeX 和实际 React HTML 通过,六个数学注解一致。按 Humanizer 复读,仅 AI 作者检查,保持 written 待独立审校;未改仓库、全站构建或安装 LightGBM。
- 7 项作者测试通过。另以秩一正交对比分裂证书核对 38 份完整树报告、30 次真实分裂、86 个允许候选对比,以及全部节点链接、叶值、切点、训练预测、SSE、工作计数与合法终止;原阈值区间参照核对 369 个查询值,不走查询分箱。参照未使用直方图矩或两两离差。
- 生成多项式系数动态规划核对 21 份 GOSS 报告全部五字段,不显式枚举子集,也不使用作者有限总体方差公式。字面特征块码本核验 17 条 EFB 行与偏移,另 6 个非法尾项、类型及冲突检查通过。复读数学条件与成本项,包括 B 至少为一、n 非空、保存叶直方图、空查询、严格互斥与位成本限制。
- 完整复读双语、代码与练习答案;代码与独立示例文件一致,核对五行实际输出、五个对应显示公式及一个行内数学注解、六顺序锚点和四答案。独立严格 MDX/KaTeX/React HTML、实际 MathML 注解与强调检查通过。元数据范围修正后最终五份 SHA 一致。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- LightGBM: A Highly Efficient Gradient Boosting Decision Tree · Actually read the official nine-page 2017 paper: section 2.1 and Algorithm 1 (PDF pages 2–3), histogram building versus boundary scans; Algorithm 2 and sections 3.1–3.2 (pages 3–4), large absolute gradients, low-pool sampling, multiplier and nonlinear variance score; section 4/Algorithms 3–4 (pages 5–6), exact exclusivity, disjoint bin offsets, original histogram recovery and approximate conflicts. The text uses inconsistent denominators for b: Algorithm 2 specifies randN=b*n, whereas one section 3.2 sentence says b times the remaining pool. Our explicit fixed-count model follows Algorithm 2 and independently proves weight R/r. No theorem-bound transcription, universal speedup claim, original assets or library execution.
- Features — LightGBM 4.6.0 · Actually opened /en/v4.6.0/Features.html, rendered 4.6.0. Lines 11–26: histogram construction, O(bins) scans, smaller-child construction and parent subtraction. Lines 34–42: greatest-loss-change leaf, possible overfitting and depth limit while retaining leaf-wise order. Did not repeat the guide’s time-sensitive comparison with another library’s default algorithm, or infer universal global optimality.
- Parameters — LightGBM 4.6.0 · Actually opened /en/v4.6.0/Parameters.html, rendered 4.6.0. Lines 152–168: boosting versus data_sample_strategy, default bagging and its activation requirements; 475–484: top_rate and other_rate; 720–760: discrete-bin controls, enable_bundle=True and missing/zero distinctions. Defaults are explicitly tied to 4.6.0. No claim that our exact count sampler or packer reproduces all production options.
- LightGBM: A Highly Efficient Gradient Boosting Decision Tree · Independently opened the official nine-page proceedings PDF, reading §2.1/Algorithm 1 (pages 2–3), Algorithm 2 and §3.1–3.2 (pages 3–4), and §4/Algorithms 3–4 (pages 5–6). Confirmed the paper’s inconsistent b denominators: Algorithm 2 uses b*n while §3.2 says b*remaining-pool. The article correctly fixes a count model and derives R/r, rather than silently inheriting the inconsistent convention. Also checked disjoint bin offsets, exact recovery and approximate conflict distinction. Text extraction only; no supplementary theorem or benchmark replication.
- Features — LightGBM 4.6.0 · Independently opened fixed 4.6.0 HTML, lines 11–26 and 34–42: bin-restricted candidates, smaller-child histogram subtraction, greatest-loss-change leaf growth and depth limiting. The article avoids a general greedy global-optimum or universal speed claim.
- Parameters — LightGBM 4.6.0 · Independently opened fixed 4.6.0 HTML, lines 152–168 (boosting, data_sample_strategy default and activation), 715–760 (binning, enable_bundle and zero/missing distinctions). Documentation version is explicit; no compiled library was installed or executed.
相关主题