75. 仅使用在训练集上学习的分位数来裁剪离群值
重要性 对延迟、支出或 token 计数等重尾特征进行 Winsorizing 可以稳定线性模型和神经网络。
裁剪极端值 (winsorizing) 可以防止少数离群值主导模型。裁剪限制是学习到的参数,因此它们必须来自训练数据,并在测试数据上保持不变地重复使用。
编写 clip_outliers(train, test, p_low, p_high)。train 和 test 是 1D float 数组;p_low < p_high 是 0..100 之间的分位数。计算 lo = np.percentile(train, p_low) 和 hi = np.percentile(train, p_high) (默认使用 linear 方法)。返回 (train_clipped, test_clipped, lo, hi),其中两个数组都被裁剪到 [lo, hi] 范围内。
def clip_outliers(train, test, p_low, p_high)示例 1
输入: clip_outliers([1, 2, 3, 4, 100], [0, 50], 0, 75)
输出: train [1, 2, 3, 4, 4], test [1, 4], lo 1.0, hi 4.0
示例 2
输入: train = [-0.802, -1.324, -0.248, 0.42, 1.136, 0.11, -0.553, -0.785, 9.0], test = [-5.0, 0.0, 0.3, 12.0], p_low = 10, p_high = 90
输出: ([-0.802, -0.9064, -0.248, 0.42, 1.136, 0.11, -0.553, -0.785, 2.7088], [-0.9064, 0.0, 0.3, 2.7088], -0.9064, 2.7088)
示例 3
输入: train = [0, 10, 20, 30], test = [5, 25], p_low = 0, p_high = 100
输出: ([0.0, 10.0, 20.0, 30.0], [5.0, 25.0], 0.0, 30.0)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
仅从 train 中计算一次两个分位数,然后使用相同的 lo 和 hi 对 train 和 test 进行 np.clip。
提示 2
限制值是拟合参数。
提示 3
仅在 train 上进行拟合。
提示 4
对两个数组应用具有相同限制的 np.clip。
常见错误
- 在 test 或在 train 加 test 上拟合限制值。
- 删除离群值而不是裁剪,这会改变行数。
理解思路
Winsorizing 在选定的分位数处封顶极端值,而不是删除行。它保留了该行,但防止单个巨大的值拉偏模型。分位数就像均值或 scaler:从训练数据中学习,然后冻结。
train [1, 2, 3, 4, 100]。第 0 个分位数是 1。使用 linear 插值的第 75 个分位数位于排序列表中的位置 0.75 * 4 = 3,即 4。因此 lo = 1, hi = 4,train 变为 [1, 2, 3, 4, 4]。Test [0, 50] 变为 [1, 4]。
lo = percentile(train, p_low), hi = percentile(train, p_high), x_clipped = min(max(x, lo), hi),在所有地方应用相同的 lo 和 hi。
表格模型的特征流水线和 RL 中的 reward-score 归一化都会使用分位数裁剪。
Shape 与数据流
train (N,), test (M,) -> same shapes, plus two scalars