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

72. 在不泄露测试数据的情况下标准化特征

EasyData processing and features

将特征缩放为均值 0 和标准差 1 对大多数模型都有帮助。一个经典的错误是在所有数据上计算均值和标准差,这会将测试集泄露到训练中。

为 2D 数组编写 standardize(train, test)。仅在 train 上计算每列的均值和总体标准差,并返回 (train_scaled, test_scaled)。

如果某一列在 train 中的标准差为 0,则将该列的缩放值保持为 0。

函数def standardize(train, test)

示例 1

输入: standardize([[1.0, 5.0], [3.0, 5.0]], [[2.0, 7.0]])

输出: ([[-1.0, 0.0], [1.0, 0.0]], [[0.0, 0.0]])

示例 2

输入: standardize(np.array([[1.0, 10.0, 5.0], [3.0, 30.0, 5.0], [5.0, 20.0, 5.0]]), np.array([[7.0, 0.0, 9.0]]))[0]

输出: [[-1.224745, -1.224745, 0.0], [0.0, 1.224745, 0.0], [1.224745, 0.0, 0.0]]

示例 3

输入: standardize(np.array([[1.0, 10.0, 5.0], [3.0, 30.0, 5.0], [5.0, 20.0, 5.0]]), np.array([[7.0, 0.0, 9.0]]))[1]

输出: [[2.44949, -2.44949, 0.0]]

约束条件

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

mu = train.mean(0), sd = train.std(0)。

提示 2

在除法之前将零 sd 替换为 1,这样常数列在 train 上就会变成 (x - mu) / 1 = 0。

常见错误
  • 有 Bug 的版本在 train 和 test 上同时进行 fit,这属于数据泄露:测试集在悄无声息地塑造模型的输入。
理解思路

标准化将每个特征置于相同的尺度:减去均值并除以标准差。关键规则是仅从训练数据中学习这些数值,然后在测试数据上复用它们。如果测试数据参与了这些数值的选择,就会发生信息泄露,导致你的评分看起来比实际情况更好。这就像是根据教学大纲出题,而不是偷看学生的答案。

Worked example

train 列 [1, 3] 的均值为 2,总体标准差为 1。Train 变为 [-1, 1]。测试值 5 变为 (5 - 2) / 1 = 3,即使它远在 train 的范围之外。常数 train 列的标准差为 0;将其缩放值设为 0 而不是除以零。

每列从 train 获取 mu 和 sigma (除以 n);两组数据的 scaled = (x - mu) / sigma。scikit-learn 的在 train 上 fit,在 test 上 transform 的模式正是为了解决这个问题。
主题
Data processing and features
相似题目
  • 使用中位数和 IQR 进行特征缩放,防止离群值主导Easy
  • 将一天中的小时和一周中的天数编码为正弦和余弦特征Easy
  • 仅使用在训练集上学习的分位数来裁剪离群值Easy
  • 使用 hashing trick 将类别 token 转换为固定大小的向量Easy
所有 Data processing and features 道题目
反馈
72 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def standardize(train, test):
# your code here
pass
​
standardize(np.array([[1.0, 10.0, 5.0], [3.0, 30.0, 5.0], [5.0, 20.0, 5.0]]), np.array([[7.0, 0.0, 9.0]]))[0]

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

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

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