零、为什么要做特征工程

  1. 直接决定了算法模型所能做到准确率的上限。

一、快速数据预处理

无量纲化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from sklearn.datasets import load_iris
import numpy as np
iris = load_iris() # 导入数据集
x = iris.data # 特征矩阵
y = iris.target # 目标向量

'''
无量纲化1——标准化(防止几千几万这种)
'''
from sklearn.preprocessing import StandardScaler
#标准化
xs = StandardScaler().fit_transform(x)
xs

'''
无量纲化2——归一化
'''
from sklearn.preprocessing import MinMaxScaler
#归一化
xs = MinMaxScaler().fit_transform(x)
xs
import numpy as np
np.min(xs,axis = 0)
np.max(xs,axis = 0)

# 另一种归一化,归一为单位向量,有时候这个方法更好
from sklearn.preprocessing import Normalizer
xs = Normalizer().fit_transform(x)
xs

定量特征二值化

1
2
3
from sklearn.preprocessing import Binarizer
xs = Binarizer(threshold = 1.5).fit_transform(x) # 大于1.5为1,小于为0
xs

独热编码

1
2
3
import pandas as pd
l = ['A','B','C','A','C']
pd.get_dummies(l)

数据变换

  • 我们希望数据是连续的正态分布的情况,适合用于机器学习。
  • 将数据处理为类似于正态分布的状态,更规则。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看一下数据情况
x[:,0]
import matplotlib.pyplot as plt
plt.hist(x[:,0],bins = 20)
plt.show()

from numpy import log1p
from sklearn.preprocessing import FunctionTransformer
#log1p = log(x+1)。使用log处理可以将原先的数据变得接近正态分布。
xs = FunctionTransformer(log1p).fit_transform(x)
xs

plt.hist(xs[:,0],bins = 20)
plt.show() # 再次查看图像,会发现情况比不处理好一些。