add K-Nearest Neighbors details

This commit is contained in:
2025-01-13 17:34:39 +08:00
parent 74ae58bd12
commit f68c9071aa
38 changed files with 1054 additions and 238 deletions

View File

@@ -0,0 +1,51 @@
---
title: 机器学习
tags: machinelearning
abbrlink: 29139
mathjax: true
date: 2025-01-13 17:20:59
---
## **k近邻算法K-Nearest NeighborsKNN**
将当前样本的类别归类于距离最近的**k**个样本的类别
#### **距离公式(2维)**
- 欧式距离
$$
d = \sqrt{(x_1-y_1)^2 + (x_2 - y_2)^2}
$$
- 曼哈顿距离
$$
d = |x_1 - x_2| + |y_1 - y_2|
$$
- 切比雪夫距离
$$
d = \max\left(|x_1 - x_2|, |y_1 - y_2|\right)
$$
#### k值选择问题
| k值 | 影响 |
| --- | ------------------ |
| 越大 | 模型过拟合,准确率波动较大 |
| 越小 | 模型欠拟合,准确率趋于稳定但可能较低 |
### 特征预处理
> 通过一些转换函数将特征数据转换成更加适合算法模型的特征数据过程
- 归一化
将数据变换到指定区间(默认是\[0,1\]
$$ x' = \frac{x- x_{\text {min}}}{x_{\text{max}} - x_{\text{min}}} $$
若需要缩放到任意区间 \(\[a, b\]\),公式为: $$ x' = a + \frac{(x - x_{\text{min}}) \cdot (b - a)}{x_{\text{max}} - x_{\text{min}}} $$
其中:\( \[a, b\] \):目标区间的范围
归一化受到数据集的异常值的影响,需要进行标准化处理(更加合理)
``` python
from sklearn.preprocessing import MinMaxScaler # 归一化
```
- 标准化
将数据调整为均值为 0标准差为 1 的标准正态分布
$$ z = \frac{x - \mu}{\sigma} $$
\( z \):标准化后的值 \( x \):原始数据值 \( $\mu$ \):数据的均值 \( $\sigma$\):数据的标准差
``` python
from sklearn.preprocessing import StandardScaler # 标准化
```