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

87. 将特征分桶至从训练数据中学习的分位数桶中

MediumData processing and features

将像 account age 这样偏态分布的数值转换为几个等频桶有助于提升简单模型的性能。分桶边界必须仅从训练数据中获取,然后原封不动地应用于新数据。

编写 quantile_bins(train, test, n_bins)。train 和 test 是 1D float 数组。步骤:
1. edges = np.quantile(train, np.linspace(0, 1, n_bins + 1)).
2. inner = np.unique(edges[1:-1]) (合并由重复值产生的重复边界,因此你可能会得到较少的桶)。
3. 返回 np.searchsorted(inner, test, side="right") 作为 int 数组。
低于训练集最小值的数值落在 bin 0 中,高于最大值的数值落在最后一个 bin 中。完全等于 inner edge 的值会进入其上方的 bin。

函数def quantile_bins(train, test, n_bins)

示例 1

输入: train = [1, 2, 3, 4, 5, 6, 7, 8], n_bins = 4

输出: inner edges [2.75, 4.5, 6.25]

解析: So test [0, 3, 4.5, 9] maps to [0, 1, 2, 3].

示例 2

输入: train = [1, 2, 3, 4, 5, 6, 7, 8], test = [0, 3, 4.5, 9], n_bins = 4

输出: [0, 1, 2, 3]

示例 3

输入: train = [0, 0, 0, 0, 0, 0, 1, 2], test = [0, 0.5, 1, 3], n_bins = 4

输出: [1, 2, 2, 2]

约束条件

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

仅从 train 中学习一次边界。

提示 2

永远不要在 test 数组上重新计算分位数。

理解思路

Quantile binning 将偏态分布的数值转换为几个包含大致相等训练行数的桶。边界仅从训练数据中学习,然后原封不动地应用于新数据,因此每个桶在任何地方都代表相同的含义。重复的值可能会产生重复的边界,这些边界会被合并,从而产生较少的桶。这就像根据去年的成绩设定分数线,并将其用于今年的试卷。

Worked example

train = [10, 20, 30, 40, 50], n_bins = 2. 在 0, 0.5 和 1 处的分位数为 [10, 30, 50];inner edge 为 [30]。测试 [5, 30, 35, 99]:5 低于 30,属于 bin 0;30 等于边界,因此使用 side='right' 时它进入上方的 bin,即 bin 1;35 属于 bin 1;99 高于训练集最大值,落在最后一个 bin,即 1。结果 [0, 1, 1, 1]。

edges = quantile(train, linspace(0, 1, n_bins + 1)); inner = unique(edges[1:-1]); bins = searchsorted(inner, test, side='right')。在测试数据上重新计算边界会导致信息泄露。
主题
Data processing and features
相似题目
  • 按比例拆分数据集以保持各类别占比Medium
  • 对类别进行频率编码,并为稀有和未见值设置共享桶Medium
  • 生成 K-fold 训练集和验证集索引切分Medium
  • 归一化后去除重复训练文本Medium
所有 Data processing and features 道题目
反馈
87 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def quantile_bins(train, test, n_bins):
# your code here
pass
​

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

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