AI Wiki中文/EN

CatBoost:决定每条记录能看到哪些答案

CatBoost

用精确小例追踪有序目标统计与前缀残差,区分它们和普通交叉拟合编码。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

一个已经看过答案的特征

质检员记录 red、blue 这样的批次标签,以及物品是否未通过检查。把批次标签替换为历史失败率,听起来很合理。但如果某件物品自己的质检结果也参与生成它的训练特征,改变答案就会改变展示给模型的问题。

CatBoost 是梯度提升树系统,其排序原则处理两种相关依赖:怎样构造类别目标统计量,以及用哪些已经拟合的预测计算下一轮残差。2018 年论文同时讨论这两点;它的名称并不意味着每个拟合预测都是真实响应的无偏估计。原论文

这里的六条质检记录依次属于 red, blue, red, green, blue, red,标签为 1, 0, 0, 1, 1, 1。为每个新类别设置固定先验二分之一、强度一。处理第三条记录之前,red 只有一次历史失败,因此这条记录的特征是四分之三。必须先记下特征,才能把它的零标签加入 red 汇总。这是在安排信息流,不是给类别排出有意义的数值顺序。

可执行例子包含前缀编码器,以及单独的常数模型残差实验。可以先读决策树;梯度提升解释更完整的加性模型框架。

每条记录允许知道什么

设给定排列列表为 π,π(t) 表示位置 t 对应的原始行。对行 i,Hᵢ 只包含同类别且排在它之前的行,mᵢ 为其数量。二元目标、[0,1] 内的固定先验 p,以及大于零的强度 a,给出

zi=ap+∑j∈Hiyja+mi,Hi={π(s):s<t, cπ(s)=ci},i=π(t).z_i=\frac{a p+\sum_{j\in H_i}y_j}{a+m_i},\qquad H_i=\{\pi(s):s<t,\ c_{\pi(s)}=c_i\},\quad i=\pi(t).

历史为空时,结果就是先验。历史非空时,它是 p 与历史类别均值的加权平均;a 越大,稀疏估计越靠近 p。它也是 a(z−p)² 加上历史中各项 (z−yⱼ)² 之和的唯一最小点,因为二次项系数 a+mᵢ 为正。

实现顺序必须是读取、输出、更新。每一步开始时,字典恰好包含此前访问过的行;归纳即可证明这个不变量。处理完所有行,同一字典便可在不读取新记录标签的情况下为其编码。固定版本的 CatBoost 类别指南说明了基于先前记录、带先验平滑的统计量;这里的强度参数把小型二元情形写得更明确。

再比较直接把完整训练类别均值当成训练行特征。该类别有 N_c 条记录,当前标签改变 Δ,而类别、先验、强度与顺序均固定时,

Δzifull=ΔNc+a,Δziordered=0.\Delta z_i^{\mathrm{full}}=\frac{\Delta}{N_c+a},\qquad \Delta z_i^{\mathrm{ordered}}=0.

零敏感度是精确的依赖陈述,并不证明训练与测试特征分布相同、估计方差小或预测准确。靠前位置的历史更短。若改用全部 n 个标签的均值作为 p,被类别求和排除的当前标签仍会通过先验进入:

Δziordered, global prior=a Δn(a+mi).\Delta z_i^{\mathrm{ordered,\ global\ prior}} =\frac{a\,\Delta}{n(a+m_i)}.

因此程序把 p 当作外部固定输入。依赖标签选择排列也会破坏排除论证。进行 IID 统计分析时,排列应独立于标签;对具有时间依赖的记录,则要遵守实际预测时的信息可用范围。

有序编码与有序提升是两个操作。平方损失下,普通提升用一个可能已经拟合过当前记录的模型计算残差。论文把训练记录与新记录之间由此产生的条件预测分布差异称为预测偏移(prediction shift)。概念性的有序过程为每个前缀维护一个模型,用上一前缀预测当前行。实际树实现共享结构并管理多个排列,工作远不止预先生成一列编码。论文第 4—5 节

为了让依赖关系容易检查,把每个模型限制为一个常数。按排列位置编号,各常数从零开始,冻结上一轮结果,再更新

rj(t)=yπ(j)−Mj−1(t−1),Mi(t)=Mi(t−1)+η1i∑j=1irj(t),M0(t)=0.r_j^{(t)}=y_{\pi(j)}-M_{j-1}^{(t-1)},\qquad M_i^{(t)}=M_i^{(t-1)}+\eta\frac{1}{i}\sum_{j=1}^{i}r_j^{(t)},\qquad M_0^{(t)}=0.

i、j 从一开始,η 在 (0,1] 内。前缀残差的均值就是该前缀上的最小二乘常数拟合。归纳可知 Mᵢ 只依赖前 i 个目标,所以 rⱼ 所使用的预测不含位置 j 的目标;残差本身当然必须包含该目标。同一轮的更新都使用冻结的旧模型族,不是让较早更新影响较晚残差的原地扫描。

两个能看到依赖的小实验

下面是完整 Python 3.10+ 程序,使用精确有理数。类别必须为非空字符串,标签是整数零或一,顺序是从零编号的行索引完整排列。拒绝布尔值、浮点数、缺失类别、空训练数据与非法排列;允许空预测查询。encode 只接受本程序返回的模型,不会更新它。

ordered_constants 没有类别特征、树搜索或分类阈值,只隔离前缀残差递推。其常数可能超出 [0,1],它们是回归值,不是概率。零轮返回初始零模型;随轮数增加,第一个前缀的常数可以无界增长,因此这个实验不提供优化或泛化保证。

from fractions import Fraction as F


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def rational(value):
    if type(value) not in (int, F):
        raise ValueError('expected integer or Fraction, not bool or float')
    return F(value)


def names(values):
    values = tuple(sequence(values))
    if any(type(v) is not str or not v for v in values):
        raise ValueError('categories must be nonempty strings')
    return values


def data(categories, labels, order):
    categories = names(categories)
    labels, order = tuple(sequence(labels)), tuple(sequence(order))
    n = len(categories)
    if not n or len(labels) != n or any(type(y) is not int or y not in (0, 1) for y in labels):
        raise ValueError('nonempty matching binary labels required')
    if len(order) != n or any(type(i) is not int for i in order) or set(order) != set(range(n)):
        raise ValueError('order must be a permutation of row indices')
    return categories, labels, order


def ordered_stats(categories, labels, order, prior=F(1, 2), strength=1):
    categories, labels, order = data(categories, labels, order)
    prior, strength = rational(prior), rational(strength)
    if not 0 <= prior <= 1 or strength <= 0:
        raise ValueError('prior in [0,1] and positive strength required')
    stats, scores, audit = {}, [None] * len(labels), []
    for i in order:
        count, total = stats.get(categories[i], (0, 0))
        score = (total + strength * prior) / (count + strength)
        scores[i] = score
        audit.append((i, count, total, score))
        stats[categories[i]] = (count + 1, total + labels[i])
    return {'scores': tuple(scores), 'audit': tuple(audit),
            'model': {'prior': prior, 'strength': strength, 'stats': stats}}


def encode(model, categories):
    # model is returned by ordered_stats; no labels or updates are accepted here.
    output = []
    for category in names(categories):
        count, total = model['stats'].get(category, (0, 0))
        output.append((total + model['strength'] * model['prior']) /
                      (count + model['strength']))
    return tuple(output)


def ordered_constants(labels, order, rounds=2, rate=1):
    labels = tuple(sequence(labels))
    _, labels, order = data(('group',) * len(labels), labels, order)
    if type(rounds) is not int or rounds < 0:
        raise ValueError('rounds must be a nonnegative integer')
    rate = rational(rate)
    if not 0 < rate <= 1:
        raise ValueError('rate must be in (0,1]')
    y = tuple(F(labels[i]) for i in order)
    models, trace = (F(0),) * (len(y) + 1), []
    for _ in range(rounds):
        # Freeze the old family before calculating this round's residuals.
        residuals = tuple(y[j] - models[j] for j in range(len(y)))
        total, updated = F(0), [F(0)]
        for i, residual in enumerate(residuals, 1):
            total += residual
            updated.append(models[i] + rate * total / i)
        models = tuple(updated)
        trace.append((residuals, models))
    return {'order': order, 'models': models, 'trace': tuple(trace),
            'prediction': models[-1]}


if __name__ == '__main__':
    categories = ('red', 'blue', 'red', 'green', 'blue', 'red')
    labels = (1, 0, 0, 1, 1, 1)
    order = tuple(range(6))
    result = ordered_stats(categories, labels, order)
    print('prefix scores:', tuple(map(str, result['scores'])))
    print('full-data scores:', tuple(map(str, encode(result['model'], categories))))
    print('new red / unseen:', tuple(map(str, encode(result['model'], ('red', 'violet')))))
    changed = ordered_stats(categories, (1, 0, 1, 1, 1, 1), order)
    print('row 2 before / after:', result['scores'][2], changed['scores'][2])
    print('row 5 before / after:', result['scores'][5], changed['scores'][5])
    toy = ordered_constants((1, 0, 1, 0), (0, 1, 2, 3), rounds=2)
    for i, (residuals, models) in enumerate(toy['trace'], 1):
        print('round', i, 'residuals', tuple(map(str, residuals)), 'models', tuple(map(str, models)))
    print('ordered constant / ordinary two-step constant:', toy['prediction'], F(1, 2))

输出为

prefix scores: ('1/2', '1/2', '3/4', '1/2', '1/4', '1/2')
full-data scores: ('5/8', '1/2', '5/8', '3/4', '1/2', '5/8')
new red / unseen: ('5/8', '1/2')
row 2 before / after: 3/4 3/4
row 5 before / after: 1/2 5/6
round 1 residuals ('1', '0', '1', '0') models ('0', '1', '1/2', '2/3', '1/2')
round 2 residuals ('1', '-1', '1/2', '-2/3') models ('0', '2', '1/2', '5/6', '11/24')
ordered constant / ordinary two-step constant: 11/24 1/2

把记录 2 的标签从零改为一,它自己的有序特征仍是 3/4,却把记录 5 的特征从 1/2 改为 5/6。新 red 物品使用原完整训练表的 5/8,未见过的 violet 使用 1/2。用部署编码器重新编码训练表,会得到输出中的 full-data scores,并非原来的训练特征。

常数实验第二轮使用的残差是 1、−1、1/2、−2/3,总和为 −1/6,因此完整前缀常数从 1/2 变为 1/2−1/24=11/24。同样从零开始、步长为一的普通常数提升,第一轮到达样本均值 1/2,之后保持不变。这个差异验证了机制,不能据此判断哪个预测器在新质检记录上更好。

n 条记录、C 个类别时,校验加一次编码扫描需要期望 O(n+1) 次字典操作,保存 O(n+C+1) 项,包括返回分数与审计。编码 q 个新名称需要期望 O(q+1) 次操作及 O(q+1) 额外存储。常数实验对 T 轮需要 O(n(T+1)) 次算术操作及同阶存储,因为保留了每轮残差和模型族;若不保存轨迹,工作存储可以降为 n 的线性量级。这些是单位成本算术与哈希界;有理数位数、类别字符串长度也影响实际时间和内存。

排除一个标签,还没有完成评估设计

普通折外目标编码在其他折上拟合统计量,再应用到留出折。它可以成为有用的管线组件,却没有构造有序提升所用的前缀预测模型族。在 scikit-learn 1.7.2 中,fit_transform 使用交叉拟合,fit(...).transform(...) 使用完整数据上拟合的编码;两种调用的训练语义本来就不同。其全局均值与自动平滑行为也不同于这里的固定先验。

留一统计量同样需要检查:从某次计算中移除一行标签,不能据此断言共同构造的特征与下游拟合模型具有所需的独立性。随机按行划分也可能让同一客户或未来信息同时进入两边。先选定评估单位,再编码;仅在允许的训练数据内拟合统计量,将验证标签用于选择或评估预先定义的流程。人为排列不能修复错误的时间或分组划分。

固定的 CatBoost 参数参考区分 Ordered、Plain 提升,输入顺序处理,以及多种树生长策略。因此,“CatBoost 总是使用有序提升”“所有支持的树都必须对称”都过于宽泛。论文中的对称树在同一层使用同一个分裂条件,库接口已经不只支持这一种构造。

本程序省略类别组合、目标量化、多排列、树结构、正则化、类别统计量选择和生产环境内存优化。给未知类别使用先验分数,是一种回退估计,不是它必然与总体平均行为相同的证据。新类别很重要时,应单独检查其覆盖率与错误。

检查信息边界

  1. 原始 red 类别中,记录 2 的全数据编码是多少?若把它的标签从零改成一,并固定 p=1/2、a=1,变化多少?
查看答案

答案: 三条 red 记录的目标总和为二,编码为 (2+1/2)/4=5/8。翻转后为 7/8,增加 1/4。有序编码仍为 3/4,因为只有更早的那条 red 记录可用。

  1. 如果第一条记录的编码使用全部六个标签均值作为先验,这个编码独立于它自己的目标吗?
查看答案

答案: 不独立。历史为空时编码就是先验,把它的目标增加一会让编码增加 1/6。从类别求和排除它,并没有排除全局先验中的依赖。

  1. 对排列后的标签 1、0、1、0,步长一、零初始化,重算两轮后的最终常数。为什么必须先计算全部残差,再更新模型?
查看答案

答案: 第一轮前缀常数为 0、1、1/2、2/3、1/2。第二轮残差为 1、−1、1/2、−2/3,总和 −1/6,最终常数为 11/24。若提前更新某前缀,再把新值用于较晚残差,就实现了另一套递推。

  1. 某模型使用折外目标编码,随后拟合普通提升树。它实现了 CatBoost 的有序提升吗?这个管线仍可以正确做到什么?
查看答案

答案: 没有构造提升预测的前缀模型族,提升过程仍是普通版本。隔离正确的交叉拟合仍可避免把一行标签直接用于其他折上拟合的统计量。验证、分组或时间隔离、平滑与部署编码仍需明确设计。

沿依赖关系读到具体实现

2018 年 CatBoost 论文把排序原则用于类别统计与残差构造。概念性前缀算法解释统计动机,实际算法则改变表示与计算,让树提升可行。标题中的“无偏”应结合这些模型与假设理解,不能变成针对一切拟合函数的保证。

版本化类别指南把这一思路连接到可配置统计量与类别组合。固定 TargetEncoder 接口提供另一种设计:基于折的编码是可复用变换,CatBoost 则协调编码与提升过程。继续阅读数据泄漏与训练、验证、测试划分,把两种方法放回评估协议中。

先判断,再看解释

固定先验与顺序时,改变记录 2 的目标不改变其有序统计。这是否足以证明部署预测器无偏?

选择一个答案

学习目标

  • 追踪哪些标签能影响有序类别统计与部署编码。
  • 区分前缀残差模型与普通交叉拟合目标编码。
  • 审查固定先验、排列、有限递推及评估边界,不假定普遍无偏保证。

先修与延伸

查看知识关联图 →

参考文献

  1. CatBoost: unbiased boosting with categorical features
    Liudmila Prokhorenkova; Gleb Gusev; Aleksandr Vorobev; Anna Veronika Dorogush; Andrey Gulin · 2018
  2. CatBoost v1.2.8 — Transforming categorical features to numerical features
    CatBoost developers
  3. CatBoost v1.2.8 — Common training parameters
    CatBoost developers
  4. TargetEncoder — scikit-learn 1.7.2
    scikit-learn developers

版本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.

  • 8 项测试通过。12 组编码配置以独立类别/位置掩码及二次函数驻点核对分数与审计;32 组常数前缀配置以有限幂零矩阵二项展开核对最终模型族及全部保留轮次,不使用逐轮递推作为参照。
  • 核验固定先验/顺序下当前与未来标签排除、完整部署计数、未知类别回退、输入与模型不变、平滑范围、顺序敏感性、全局均值先验泄漏及零轮。六行主例有序分数为 1/2、1/2、3/4、1/2、1/4、1/2;改变记录 2 后记录 5 为 5/6。常数实验为 11/24,对照普通 1/2;单行四轮达到 4,说明输出不是概率,也不普遍收敛。
  • 拒绝 11 类非法训练/顺序、7 类先验/强度组合、6 类轮数/步长组合、4 类非法查询及空常数训练。双语完整原创 Python 相同,实际输出 8 行;各语 4 显示式、6 锚点、4 已答练习通过严格 MDX/KaTeX 与 React 实际 HTML,4 项数学注解对应。冻结前修复 details 块格式与中文强调符字面残留。
  • 按固定 Humanizer 规范复读完整双语。研究段讨论贡献与差异,访问和核验过程留在元数据。所有关联 ID 存在于目录,仅当前已有正文使用 wiki 直链;复杂度计入保留轨迹及空查询/零轮边界。仅 AI 作者检查,保持 written 等待独立技术审校;没有库训练、基准实验、浏览器或全站构建。
  • 8 项作者测试全部通过。另以 Bernoulli 似然多项式对整数形状或反正弦 Beta 先验精确积分,核对 32 份完整编码报告、240 个训练/部署值。用有理 Gauss–Jordan 同时求解残差与最小二乘线性方程,核对 48 份完整常数模型报告、256 个未知量,不重放轮次或使用作者幂零矩阵公式;另核 4 次标签扰动的排除与部署敏感度。
  • 完整复读双语、代码、4 题答案与元数据,核验固定先验依赖、读/输出/更新顺序、冻结前缀递推、首前缀无界例、完整部署计数、未见类别回退、返回轨迹存储及有限哈希/算术成本,不推导自动概率或泛化保证。独立严格 MDX/KaTeX/React HTML 通过:每语 4 个相同显示公式、6 个顺序锚点、4 答案,并核对实际 MathML 注解与强调符。
  • 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
  • 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。

核对的来源位置:

  • CatBoost: unbiased boosting with categorical features · Actually opened the proceedings PDF, 11 pages. Read cover authors/NeurIPS 2018, section 3.2 (PDF pages 3–4, lines 165–304) on greedy/leave-one-out/ordered target statistics, section 4 (pages 4–5, lines 305–535) on conditional prediction shift and prefix models, Algorithm 1 and section 5 (pages 6–7, lines 539–695) on shared structures, permutations, deployment statistics and categorical combinations. Did not reproduce the two-step theorem, benchmarks, supplementary proofs or example datasets. The original constant-model recurrence is an explicit restricted instantiation; no full CatBoost claim.
  • CatBoost v1.2.8 — Transforming categorical features to numerical features · Direct web/raw and GitHub reads initially failed; this author shell also could not resolve raw.githubusercontent.com. Root fetched https://raw.githubusercontent.com/catboost/catboost/v1.2.8/catboost/docs/en/concepts/algorithm-main-stages_cat-to-numberic.md. Actually read the complete 5383-byte local source-v1.2.8-algorithm-main-stages_cat-to-numberic.md: beginning stages, combination section, binary formula and explicit previous-object note, and one_hot_max_size footer. Included external files were not expanded. A later mutable rendered page also succeeded, but article citation binds the tag.
  • CatBoost v1.2.8 — Common training parameters · Root fetched https://raw.githubusercontent.com/catboost/catboost/v1.2.8/catboost/docs/en/references/training-parameters/common.md after confirming boosting.md is not the filename. Actually read local source-v1.2.8-training-common.md lines 570–602 (symmetric/depthwise/lossguide descriptions), 733–753 (has_time order), 1256–1285 (boosting schemes and conditional defaults). Raw macros remain; the article makes no exact default or hardware-speed claim. This is documentation reading, not library execution.
  • TargetEncoder — scikit-learn 1.7.2 · Actually opened fixed 1.7 API rendered 1.7.2, lines 623–632 (shrinkage, unseen-category global mean, differing fit_transform semantics), 666–680 (smooth and cross-fitting), 685–699 (stored full encodings/mean), 777–783 (method note). No source examples or library execution used.
  • CatBoost: unbiased boosting with categorical features · Independently opened the official 11-page proceedings PDF. Read §3.2 pages 3–4, §4.1–4.2 pages 4–5 and Algorithm 1/§5 pages 6–7: target-statistic leakage, prefix residual construction, conceptual versus shared tree implementation, Ordered/Plain modes and same-level split condition. Text extraction only; no supplementary theorem reproduction or benchmark verification claimed.
  • CatBoost v1.2.8 — Transforming categorical features to numerical features · Independently read the complete retained source-v1.2.8-algorithm-main-stages_cat-to-numberic.md: previous-object formula, category combinations and one-hot footer. Root supplied this fixed-tag download; this reviewer did not fetch its bytes anew or expand included macros.
  • CatBoost v1.2.8 — Common training parameters · Independently read the retained fixed-tag training-common.md lines 570–602, 733–753 and 1256–1285: growth policies, input order and Ordered/Plain schemes. Unexpanded macros prevent literal-default claims; the article correctly avoids those.
  • TargetEncoder — scikit-learn 1.7.2 · Independently opened the official 1.7 API displayed as 1.7.2; read lines 623–632, 666–699, including cross-fitting versus full encodings, global prior and unknown-category handling. This supports a comparison of transformations, not a CatBoost implementation claim.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。