Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样用少量样本手算有序目标统计?

查看完整题解

参考回答

直接回答

可以用形式 (历史正例和 + p)/(历史次数 + 1) 示意每个类别的一个有序统计。p 是先验。每次先计算,再更新历史计数与标签和。

讲清原理

假设同一类别在次序中出现三次,标签为 1、0、1,p=0.5。前三次编码依次为 0.5、0.75、0.5。第三个标签改为 0,前三个编码仍一样。

同一类别的前三条怎样编码?
同一类别的前三条怎样编码?

例子与易错点

下方代码模拟这一种统计,检查编码不随当前标签改变。CatBoost 实际还有其他 CTR、目标量化和多个先验,不能拿这一种公式套所有配置。

from collections import defaultdict

def encode(categories, targets, prior=0.5):
    totals = defaultdict(int)
    counts = defaultdict(int)
    values = []
    for category, label in zip(categories, targets):
        values.append((totals[category] + prior) / (counts[category] + 1))
        totals[category] += label
        counts[category] += 1
    return values

rows = ["A", "A", "A"]
actual = encode(rows, [1, 0, 1])
assert actual == [0.5, 0.75, 0.5]
assert actual == encode(rows, [1, 0, 0])
print(actual)

相关题:第 11 题、第 15 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。