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

82. 将特征分箱到基于训练集学习的等宽桶中

EasyData processing and features

重要性 对年龄、收入或价格进行分箱是评分卡和线性模型中常见的特征处理步骤,而边界处理往往是生产环境中 pipeline 崩溃的原因。

等宽分箱将一个数字转换为桶 ID,这有助于线性模型学习阶梯状效应。

编写 uniform_bins(train, test, n_bins)。学习 edges = np.linspace(min(train), max(train), n_bins + 1)。返回 (edges, idx),其中 idx 是一个 int 数组,给出 test 中每个值在 0..n_bins - 1 范围内的桶 ID。恰好在内部边界上的值进入上层桶。低于 train min 的值进入桶 0,等于或高于 train max 的值进入桶 n_bins - 1。

函数def uniform_bins(train, test, n_bins)

示例 1

输入: train [0, 10, 4, 6], test [0, 2.5, 5, 10, 12, -3], n_bins 4

输出: edges [0, 2.5, 5, 7.5, 10] and idx [0, 1, 2, 3, 3, 0]

示例 2

输入: train = [1, 3], test = [1, 2, 2.9, 3], n_bins = 2

输出: ([1.0, 2.0, 3.0], [0, 1, 1, 1])

示例 3

输入: train = [18, 60, 25, 33, 47], test = [18, 29.9, 30, 59, 75], n_bins = 3

输出: ([18.0, 32.0, 46.0, 60.0], [0, 0, 0, 2, 2])

约束条件

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

对内部边界使用 side='right' 的 np.searchsorted 即可完成所有操作。

提示 2

np.linspace(lo, hi, n_bins + 1) 提供 edges。

提示 3

将 edges[1:-1] 传递给 np.searchsorted。

提示 4

side='right' 控制边界上的行为。

常见错误
  • 将最大值放入额外的桶 n_bins 中。
  • 为低于 train min 的值生成负的桶 ID。
  • 在 test 集上重新计算 edges。
理解思路

等宽分箱将训练范围切割成 n_bins 个宽度相同的部分,就像每隔 2.5 cm 在尺子上做一个标记,然后报告每个值落在哪个部分。

Worked example

train min 为 0 且 max 为 10,n_bins 为 4,则 edges 为 0, 2.5, 5, 7.5, 10。值 2.5 恰好在边界上,进入上层桶 1。值 10 是最大值,属于最后一个桶 3,而不是不存在的桶 4。值 12 超出了训练范围,因此也进入桶 3,而 -3 进入桶 0。

edges = linspace(min, max, n_bins + 1); bucket = 满足 <= x 的内部边界数量。

棘手的部分在于两端:简单的 floor 公式会对最大值给出桶 n_bins,并对较小的值给出负的 ID。对内部边界使用 searchsorted,两端都会被自动处理。在 train 上学习一次 edges 并保持固定。

主题
Data processing and features
相似题目
  • 在不泄露测试数据的情况下标准化特征Easy
  • 使用中位数和 IQR 进行特征缩放,防止离群值主导Easy
  • 将一天中的小时和一周中的天数编码为正弦和余弦特征Easy
  • 仅使用在训练集上学习的分位数来裁剪离群值Easy
所有 Data processing and features 道题目
反馈
82 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def uniform_bins(train, test, n_bins):
# your code here
pass
​

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

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