BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Data processing and features17 of 54 in topic

88. 对类别进行频率编码,并为稀有和未见值设置共享桶

MediumData processing and features

重要性 对于模型名称、设备或国家等高基数(high-cardinality)类别,频率编码和计数编码是强大且廉价的特征。

Frequency encoding 通过类别在训练集中的出现频率来替换该类别。稀有类别本身具有噪声,因此它们共享一个桶,而测试时从未在训练中见过的类别也会落入同一个桶中。

编写 frequency_encode(train, test, min_count)。train 和 test 是字符串列表。仅使用 TRAIN:统计每个类别的数量;数量 < min_count 的类别为稀有类别。常见类别的编码为 count / len(train)。每个稀有类别以及在 train 中未见过的测试类别,都编码为稀有桶的值:(所有稀有类别的总计数) / len(train),如果没有稀有类别,则该值为 0.0。

返回 (train_enc, test_enc) 作为 float 数组。

函数def frequency_encode(train, test, min_count)

示例 1

输入: frequency_encode(['a', 'a', 'a', 'b', 'c'], ['a', 'z'], 2)

输出: train [0.6, 0.6, 0.6, 0.4, 0.4] and test [0.6, 0.4]. (b and c are rare, together 2 of 5 rows.)

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

在 train 上构建一个 Counter,将类别分为常见和稀有,计算一个稀有值,然后使用 dict 和默认值进行映射。

提示 2

仅统计 train 中的类别。

提示 3

为所有稀有类别计算一个共享值。

提示 4

使用 dict.get(category, rare_value) 进行查找。

常见错误
  • 在 train 和 test 上同时拟合计数。
  • 给未见类别分配 0.0,而让训练中的稀有类别获得正值,导致模型对同一个概念看到了两个不同的编码。
理解思路

Frequency encoding 将类别转换为一个数字:即包含该类别的训练行所占的比例。常见类别获得较大的值,稀有类别获得较小的值。极稀有的类别携带的信号很少,因此我们将它们池化到一个“稀有”桶中。从未在训练中出现的类别也被视为稀有类别。

Worked example

train ['a', 'a', 'a', 'b', 'c'],min_count 为 2。计数:a = 3, b = 1, c = 1。a 是常见的:3 / 5 = 0.6。b 和 c 是稀有的;它们共同占据了 5 行中的 2 行,因此稀有值为 0.4。在测试中,'a' 映射到 0.6,未见的 'z' 映射到稀有值 0.4。

如果 count(x) >= min_count,则 enc(x) = count(x) / N,否则为 (sum of rare counts) / N,所有计数均来自 train。

点击率(Click-through)、欺诈检测和表格模型都会对高基数列使用 frequency encoding。

主题
Data processing and features
相似题目
  • 按比例拆分数据集以保持各类别占比Medium
  • 将特征分桶至从训练数据中学习的分位数桶中Medium
  • 生成 K-fold 训练集和验证集索引切分Medium
  • 归一化后去除重复训练文本Medium
所有 Data processing and features 道题目
反馈
88 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
7
import numpy as np
from collections import Counter
​
def frequency_encode(train, test, min_count):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS