You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 3.3 数据预处理常用技巧---归一化
## 归一化与标准化
归一化是缩放**单个样本**以具有**单位范数**的过程。也就是说,上一节中提到的标准化是对数据中的每一列进行计算,而本节中提到的归一化则是对数据中的每一行进行计算。
一般来说,当我们想要计算两个样本之间的相似度之前,可以尝试一下使用归一化来作为计算相似度之前的预处理,因为有可能会使得相似度计算地更加准确。
在实践中,用的最多的是**L1范式归一化**和**L2范式归一化**,下面来详细看看这两种归一化是怎样计算的。
## L1范式归一化
`L1`范式定义如下:
$$
||x||_1=\sum_{i=1}^n|x_i|
$$
表示数据`x`中每个特征值`xi`的绝对值之和。
因此,`L1`范式归一化就是将样本中每个特征的特征值**除以**`L1`范式。虽然这个功能实现起来简单,但我们也不必重新造轮子。在`sklearn`中已经提供了该功能,即`normalize`函数,用法如下:
```python
# 导入normalize函数
from sklearn.preprocessing import normalize
# 定义数据数据中有3条样本每条样本中有3个特征
data = np.array([[-1,0,1],
[1,0,1],
[1,2,3]])
# 使用normalize函数进行L1范式归一化
# data即想要归一化的数据 l1即表示想要使用L1范式归一化来进行归一化处理
data = normalize(data,'l1')
# 可以分析一下第一行的L1范数是不是2在归一化完了之后第一行第一列的值是不是-0.5
>>>data
array([[-0.5 , 0. , 0.5 ],
[ 0.5 , 0. , 0.5 ],
[ 0.167, 0.333, 0.5 ]])
```
## L2范式归一化
`L2`范式定义如下:
$$
||x||_2=\sqrt{\sum_{i=1}^nx_i^2}
$$
表示数据`x`中每个特征值`xi`计算平方和再开跟。
因此,`L2`范式归一化就是将样本中每个特征**除以**特征的`L2`范式。在`sklearn`中已经提供了该功能,即`normalize`函数,用法如下:
```python
# 导入normalize函数
from sklearn.preprocessing import normalize
# 定义数据数据中有3条样本每条样本中有3个特征
data = np.array([[-1,0,1],
[1,0,1],
[1,2,3]])
# 使用normalize函数进行L2范式归一化
# data即想要归一化的数据 l2即表示想要使用L2范式归一化来进行归一化处理
data = normalize(data,'l2')
# 可以分析一下第一行的L1范数是不是根号2在归一化完了之后第一行第一列的值是不是-0.707
>>>data
array([[-0.707, 0. , 0.707],
[ 0.707, 0. , 0.707],
[ 0.267, 0.535, 0.802]])
```