数据预处理包括::

  1. 缺失值的处理,当样本量很大,缺失值很少时,直接删除缺失值对应的样本,并不会导致样本规模的大幅下降,此时直接删除缺失值是一种可取的办法,但是对于小样本量,且缺失值较多的场景,就需要考虑对缺失值进行插补(见002)
  2. 标准化和归一化,很多的机器学习算法对特征的分布是有预定的假设的,比如需要服从正态分布,对于不符合分布的数据,需要进行标准化,转化为正态分布,另外,考虑到不同特征的量纲不同,也需要进行缩放,比如到缩放到0到1的区间,保证了不同特征在模型中的可比性
  3. 稀疏化,也叫做离散化,指的是根据业务场景对特征进行分段处理,比如按照某个阈值,将考试分数划分为及格和不及格两类,从而将连续性的数值变换为0,1两个离散型的变量
  4. 特征编码,对于分类变量,近期映射为数值型
  5. 特征提取,适用于自然语言处理,图形识别领域的机器学习,因为原始的数据数据是文本,图像等数据,不能直接用于建模,所以需要通过特征提取转换为适合建模的矩阵数据

    sklearm.preprocessing子模块

  1. from sklearn import preprocessing
  2. import numpy as np

1.1,标准化

标准化的目标是使得变量服从标准正态分布

  1. x = np.array([1, 2, 3, -4, 5, 6]).reshape(-1, 1)
  2. scaler=preprocessing.StandardScaler().fit(x)
  3. x_scaled=scaler.transform(x)
  4. x_scaled

1.2 归一化(线性缩放)

适合对于标准差比较小的数据进行处理

  1. scaler=preprocessing.MinMaxScaler().fit_transform(x)
  2. scaler= preprocessing.MinMaxScaler(feature_range=(-5, 5)).fit_transform(x) #feature_range参数设定具体的缩放区间
  3. scaler=preprocessing.MaxAbsScaler().fit_transform(x)#根据最大绝对值进行缩放,适合稀疏数据或者是早已经中心化的数据,可以缩放到-11的区间

2. 非线性变换

分位数变换和幂变换两种,默认对样本量大于1000的数据进行变化,采用分位数对原始数据划分,默认将数据映射为0到1的均匀分布

  1. x = np.random.random(10000).reshape(-1, 1)
  2. #x_scaled = quantile_transformer.fit_transform(x)
  3. #输出正太分布的数据
  4. quantile_transformer = preprocessing.QuantileTransformer(output_distribution='normal')
  5. x_scaled = quantile_transformer.fit_transform(x)

幂变换,用于稳定方差,将数据处理为近似正态分布

  1. pt = preprocessing.PowerTransformer(method='box-cox', standardize=False)
  2. x_scaled = pt.fit_transform(x)

3.正则化

  1. x_normalized=preprocessing.normalize(x,norm='l2')
  2. x_normalized=preprocessing.Normalizer(norm='l2').fit_transform(x)

image.png

4,特征编码

将离散型的分类变量转换为数值型变量

  1. x = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox'],['male', 'from Europe', 'uses Chrome']]
  2. scale=preprocessing.OrdinalEncoder().fit_transform(x)

image.png

5.离散化,

将连续变量进行分组,比如将原始数据划分为不同的区间,称之为bin

  1. X = np.array([[ -3., 5., 15 ],[ 0., 6., 14 ],[ 6., 3., 11 ]])
  2. est = preprocessing.KBinsDiscretizer(n_bins=[3, 2, 2], encode='ordinal').fit(X)
  3. est.transform(X)

二值化变换,也是一种离散化的操作,通过某个阈值将数值划分为0和1两类

  1. X = np.array([[ 1., -1., 2.],[ 2., 0., 0.],[ 0., 1., -1.]])
  2. binarizer = preprocessing.Binarizer(threshold=1.1).fit(X)
  3. binarizer.transform(X)

7.多项式构建

多项式的构建相当于升维操作,在原来独立的特征x1, x2的基础上,构建起平方以及乘积的新变量,

  1. from sklearn.preprocessing import PolynomialFeatures
  2. X = np.arange(6).reshape(3, 2)
  3. poly = PolynomialFeatures().fit_transform(X)

image.png

8.自定义

  1. from sklearn.preprocessing import FunctionTransformer
  2. transformer = FunctionTransformer(np.log1p, validate=True)
  3. X = np.array([[0, 1], [2, 3]])
  4. trans = transformer.fit_transform(X)

image.png