M2-049M2: Classical Machine LearningK-Nearest Neighbors & Metric LearningMedium
⚡Flashcard Drill➔Mastery:
Explain Why KNN Strictly Requires Feature Scaling and Contrast Common Distance Metrics
📐 Mathematical Definition
⚡ One-Sentence Core Answer
KNN relies on geometric distance metrics; unscaled features with large numerical magnitudes dominate distance calculations completely, reducing smaller-scale features to zero influence.
📌 Key Takeaways
- •Necessity of Scaling: In Euclidean distance , a feature ranging (e.g. Annual Income) dwarfs a feature ranging (e.g. Age ratio) by factor .
- •Euclidean Distance (L2): Straight-line geometric distance; sensitive to outliers and high dimensions.
- •Manhattan Distance (L1): Grid-based distance ; more robust to outliers than L2.
- •Cosine Distance: ; measures directional angle while ignoring vector magnitude (standard in text and embeddings).
📐 Mathematical Derivations
Minkowski distance family: . When , it gives Manhattan distance; , Euclidean distance; , Chebyshev distance . Mahalanobis distance: , which incorporates the covariance matrix . If features are correlated, Mahalanobis distance automatically scales variances to 1 and rotates coordinates along principal axes, eliminating the need for manual feature scaling while accounting for feature multicollinearity.
🏭 Production Trade-offs
Standardization vs Normalization in KNN: (1) StandardScaler ($z$-score): Transforms to ; preferred when features follow approximately normal distributions. (2) MinMaxScaler: Bounds features into ; preferred for bounded variables with zero outliers. (3) Cosine Similarity: Dominates recommendation systems and vector search because document length or embedding norm does not distort semantic similarity.
⚠️ Common Interview Pitfalls
- ✕Applying Euclidean distance to raw text TF-IDF vectors without length normalization (longer documents appear falsely distant).
- ✕Evaluating Euclidean distance on categorical or high-dimensional sparse one-hot vectors.
🎯 Interviewer Follow-up Inquiries
- ?Why does Mahalanobis distance eliminate the need for feature scaling in KNN?
- ?How does Cosine distance mathematically relate to normalized Euclidean distance: ?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
为什么 KNN 需要特征缩放?不同距离度量有何差异。
距离对量纲敏感,需标准化;欧氏/L1/余弦/马氏距离适应不同数据结构。
核心要点
- 缩放的必要性:欧氏距离 d=√(Σ(xᵢ−yᵢ)²) 对每个维度等权,若某特征量纲大 1000 倍,它的差异会主导距离,其他特征的影响被淹没。例如'年龄(0–100)'与'收入(0–10⁶)',不标准化时收入完全决定距离。 标准化后 各维度方差为 1,贡献均衡。 四种距离的差异 :① 欧氏(L2) ——默认选择,对异常值敏感(平方放大),假设各维独立同尺度;② 曼哈顿(L1) ——各维差异的绝对值和,对异常值更鲁棒(线性而非平方),在高维下有时优于 L2(因为 L2 的距离集中现象更严重);③ 余弦 ——只关心方向不关心长度,适合 高维稀疏 (文本 TF-IDF、嵌入向量),因为此时'长度'常是文档长度等无关因素;④ 马氏距离 ——用协方差矩阵 Σ⁻¹ 加权,自动考虑特征相关性与尺度差异,等价于'先白化再算欧氏距离'。
- 实践要点:① 缩放方法的选择 ——StandardScaler(零均值单位方差,适合近似正态)vs MinMaxScaler(压到 [0,1],适合有界特征)vs RobustScaler(用中位数与 IQR,抗异常值);KNN 对异常值敏感,RobustScaler 常更稳。② 余弦 vs 欧氏的关系 ——若先对向量做 L2 归一化,则欧氏距离与余弦相似度 单调对应 (‖a−b‖²=2−2cos),故归一化后的欧氏 KNN ≡ 余弦 KNN。③ 马氏距离的陷阱 ——需估计 p×p 协方差矩阵的逆,当 p>n(宽数据)或特征共线时 Σ 奇异,需用伪逆或收缩估计(shrinkage);这也意味着马氏距离在高维下不实用。④ 度量学习 ——若默认距离不适合任务,可 学习 一个度量(LMNN、NCA、或对比学习),把'同类更近、异类更远'作为目标——这是深度度量学习(人脸识别、检索)的基础。
- 余弦适合文本/嵌入
- 马氏距离考虑特征相关性
- L1 对异常值更鲁棒
常见陷阱
- 不标准化直接算欧氏距离
- 在 p>n 时用马氏距离(协方差矩阵奇异)