http://blog.csdn.net/pipisorry/article/details/52247679

本blog内容有标准化、数据最大最小缩放处理、正则化、特征二值化和数据缺失值处理。

基础知识参考

[数据标准化/归一化normalization]

[均值、方差与协方差矩阵]

[矩阵论:向量范数和矩阵范数]

Note: 一定要注意归一化是归一化什么,归一化features还是samples。

数据标准化:去除均值和方差进行缩放

Standardization: mean removal and variance scaling

数据标准化:当单个特征的样本取值相差甚大或明显不遵从高斯正态分布时,标准化表现的效果较差。实际操作中,经常忽略特征数据的分布形状,移除每个特征均值,划分离散特征的标准差,从而等级化,进而实现数据中心化。

Note: test set要和training set做相同的预处理操作(standardization、data transformation、etc)。
[数据标准化/归一化normalization]

scale函数标准化

from sklearn import preprocessing

preprocessing.scale(X)

def scale(X, axis=0, with_mean=True, with_std=True, copy=True)

注意,scikit-learn中assume that all features are centered around zero and have variance in the same order.同时这个默认操作是对features进行的(如mean removal),所以操作都是针对axis=0的操作,如果数据不是这样的要注意!公式为:(X-X_mean)/X_std 计算时对每个属性/每列分别进行。

参数解释:
    X:{array-like, sparse matrix} 数组或者矩阵,一维的数据都可以(但是在0.19版本后一维的数据会报错了!)
    axis:int类型,初始值为0,axis用来计算均值 means 和标准方差 standard deviations. 如果是0,则单独的标准化每个特征(列),如果是1,则标准化每个观测样本(行)。
    with_mean: boolean类型,默认为True,表示将数据均值规范到0
    with_std: boolean类型,默认为True,表示将数据方差规范到1

这种标准化相当于z-score 标准化(zero-mean normalization)

[sklearn.preprocessing.scale]

scale标准化示例

>>> from sklearn import preprocessing
>>> import numpy as np
>>> X = np.array([[ 1., -1.,  2.],
...               [ 2.,  0.,  0.],
...               [ 0.,  1., -1.]])
>>> X_scaled = preprocessing.scale(X)

>>> X_scaled
array([[ 0.  ..., -1.22...,  1.33...],
       [ 1.22...,  0.  ..., -0.26...],
       [-1.22...,  1.22..., -1.06...]])

对于一维数据的一种可能的处理:先转换成二维,再在结果中转换为一维

cn )

转换后的数据有0均值(zero mean)和单位方差(unit variance,方差为1)

>>> X_scaled.mean(axis=0)
array([ 0.,  0.,  0.])

>>> X_scaled.std(axis=0)
array([ 1.,  1.,  1.])

使用StandardScaler使标准化应用在测试集上:保存标准化参数

一般我们的标准化先在训练集上进行,在测试集上也应该做同样mean和variance的标准化,这样就应该将训练集上的标准化参数保存下来。

The preprocessing module further provides a utility class StandardScaler that implements the Transformer API to computethe mean and standard deviation on a training set so as to beable to later reapply the same transformation on the testing set.This class is hence suitable for use in the early steps of a sklearn.pipeline.Pipeline:

>>> scaler = preprocessing.StandardScaler().fit(X)
>>> scaler
StandardScaler(copy=True, with_mean=True, with_std=True)

>>> scaler.mean_
array([ 1. ...,  0. ...,  0.33...])

>>> scaler.scale_
array([ 0.81...,  0.81...,  1.24...])

>>> scaler.transform(X)
array([[ 0.  ..., -1.22...,  1.33...],
       [ 1.22...,  0.  ..., -0.26...],
       [-1.22...,  1.22..., -1.06...]])

The scaler instance can then be used on new data to transform it thesame way it did on the training set:

>>> scaler.transform([[-1.,  1., 0.]])
array([[-2.44...,  1.22..., -0.26...]])

It is possible to disable either centering or scaling by eitherpassing with_mean=False or with_std=False to the constructorof StandardScaler.[StandardScaler]

[Standardization, or mean removal and variance scaling]

StandardScaler示例

def preprocess():
:
        xy = np.loadtxt(os.path.join(DIR, train_file), delimiter=',', dtype=float)
        x, y ], xy[]
        scaler = preprocessing.StandardScaler().fit(x)
        xy = np.hstack([scaler.transform(x), y])
        np.savetxt(os.path.join(DIR, train_file1), xy, fmt='%.7f')

        x_test = np.loadtxt(os.path.join(DIR, test_file), delimiter=',', dtype=float)
        x_test = scaler.transform(x_test)
        np.savetxt(os.path.join(DIR, test_file1), x_test, fmt='%.7f')
    else:
        print('data loading...')
        xy = np.loadtxt(os.path.join(DIR, train_file1), dtype=float)
        x_test = np.loadtxt(os.path.join(DIR, test_file1), dtype=float)
    ], xy[], x_test

Note:

pipeline能简化该过程( See  Pipeline and FeatureUnion: combining estimators ,翻译后的文章:http://www.voidcn.com/blog/mmc2015/article/p-3379231.html):

>>> from sklearn.pipeline import make_pipeline
>>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))
>>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv)
...
array([ 0.97...,  0.93...,  0.95...])

MinMaxScaler函数:将特征的取值缩小到一个范围(如0到1)

将属性缩放到一个指定的最大值和最小值(通常是1-0)之间,这可以通过preprocessing.MinMaxScaler类来实现。
使用这种方法的目的包括:
    1、对于方差非常小的属性可以增强其稳定性;
    2、维持稀疏矩阵中为0的条目。
min_max_scaler = preprocessing.MinMaxScaler()
X_minMax = min_max_scaler.fit_transform(X)

有大量异常值的归一化

sklearn.preprocessing.robust_scale(X, axis=0, with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True)

Center to the median and component wise scaleaccording to the interquartile range.

[Scaling data with outliers]

其它

[Scaling sparse data

Centering kernel matrices]

皮皮blog

正则化Normalization

正则化的过程是将每个样本缩放到单位范数(每个样本的范数为1),如果要使用如二次型(点积)或者其它核方法计算两个样本之间的相似性这个方法会很有用。
该方法是文本分类和聚类分析中经常使用的向量空间模型(Vector Space Model)的基础.
Normalization主要思想是对每个样本计算其p-范数,然后对该样本中每个元素除以该范数,这样处理的结果是使得每个处理后样本的p-范数(l1-norm,l2-norm)等于1。

Normalization is the process of scaling individual samples to haveunit norm.This process can be useful if you plan to use a quadratic formsuch as the dot-product or any other kernel to quantify the similarityof any pair of samples.This assumption is the base of the Vector Space Model often used in textclassification and clustering contexts.

def normalize(X, norm='l2', axis=1, copy=True)

注意,这个操作是对所有样本(而不是features)进行的,也就是将每个样本的值除以这个样本的Li范数。所以这个操作是针对axis=1进行的。

>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> X_normalized = preprocessing.normalize(X, norm='l2')
>>> X_normalized                                      
array([[ 0.40..., -0.40...,  0.81...],
       [ 1.  ...,  0.  ...,  0.  ...],
       [ 0.  ...,  0.70..., -0.70...]])

[Normalization]

皮皮blog

二值化Binarization

特征的二值化主要是为了将数据特征转变成boolean变量。

在sklearn中,sklearn.preprocessing.Binarizer函数可以实现这一功能。可以设定一个阈值,结果数据值大于阈值的为1,小于阈值的为0。

>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> binarizer = preprocessing.Binarizer().fit(X)  # fit does nothing
>>> binarizer
Binarizer(copy=True, threshold=0.0)
>>> binarizer.transform(X)
array([[ 1.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])

[Binarization]

Encoding categorical features

[Encoding categorical features]

皮皮blog

缺失值处理Imputation of missing values

由于不同的原因,许多现实中的数据集都包含有缺失值,要么是空白的,要么使用NaNs或者其它的符号替代。这些数据无法直接使用scikit-learn分类器直接训练,所以需要进行处理。幸运地是,sklearn中的Imputer类提供了一些基本的方法来处理缺失值,如使用均值、中位值或者缺失值所在列中频繁出现的值来替换。
Imputer类同样支持稀疏矩阵。
>>> import numpy as np
>>> from sklearn.preprocessing import Imputer
>>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>>> imp.fit([[1, 2], [np.nan, 3], [7, 6]])
Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)
>>> X = [[np.nan, 2], [6, np.nan], [7, 6]]
>>> print(imp.transform(X))                           
[[ 4.          2.        ]
 [ 6.          3.666...]
 [ 7.          6.        ]]

不过lz更倾向于使用pandas进行数据的这种处理[pandas小记:pandas高级功能]。

[Imputation of missing values]

皮皮blog

其它

[Generating polynomial features]

[Custom transformers]

皮皮blog

from: http://blog.csdn.net/pipisorry/article/details/52247679

ref: [Preprocessing data]

Scikit-learn:数据预处理Preprocessing data的更多相关文章

  1. 机器学习实战基础(十):sklearn中的数据预处理和特征工程(三) 数据预处理 Preprocessing & Impute 之 缺失值

    缺失值 机器学习和数据挖掘中所使用的数据,永远不可能是完美的.很多特征,对于分析和建模来说意义非凡,但对于实际收集数据的人却不是如此,因此数据挖掘之中,常常会有重要的字段缺失值很多,但又不能舍弃字段的 ...

  2. 机器学习实战基础(九):sklearn中的数据预处理和特征工程(二) 数据预处理 Preprocessing & Impute 之 数据无量纲化

    1 数据无量纲化 在机器学习算法实践中,我们往往有着将不同规格的数据转换到同一规格,或不同分布的数据转换到某个特定分布的需求,这种需求统称为将数据“无量纲化”.譬如梯度和矩阵为核心的算法中,譬如逻辑回 ...

  3. 神经网络中的数据预处理方法 Data Preprocessing

    0.Principal component analysis (PCA) Principal component analysis (PCA) is a statistical procedure t ...

  4. 机器学习实战基础(十二):sklearn中的数据预处理和特征工程(五) 数据预处理 Preprocessing & Impute 之 处理分类特征:处理连续性特征 二值化与分段

    处理连续性特征 二值化与分段 sklearn.preprocessing.Binarizer根据阈值将数据二值化(将特征值设置为0或1),用于处理连续型变量.大于阈值的值映射为1,而小于或等于阈值的值 ...

  5. 机器学习实战基础(十一):sklearn中的数据预处理和特征工程(四) 数据预处理 Preprocessing & Impute 之 处理分类特征:编码与哑变量

    处理分类特征:编码与哑变量 在机器学习中,大多数算法,譬如逻辑回归,支持向量机SVM,k近邻算法等都只能够处理数值型数据,不能处理文字,在sklearn当中,除了专用来处理文字的算法,其他算法在fit的 ...

  6. scikit-learn模块学习笔记(数据预处理模块preprocessing)

    本篇文章主要简单介绍sklearn中的数据预处理preprocessing模块,它可以对数据进行标准化.preprocessing 模块提供了数据预处理函数和预处理类,预处理类主要是为了方便添加到pi ...

  7. weka数据预处理

    Weka数据预处理(一) 对于数据挖掘而言,我们往往仅关注实质性的挖掘算法,如分类.聚类.关联规则等,而忽视待挖掘数据的质量,但是高质量的数据才能产生高质量的挖掘结果,否则只有"Garbag ...

  8. Python的工具包[1] -> pandas数据预处理 -> pandas 库及使用总结

    pandas数据预处理 / pandas data pre-processing 目录 关于 pandas pandas 库 pandas 基本操作 pandas 计算 pandas 的 Series ...

  9. sklearn中的数据预处理和特征工程

    小伙伴们大家好~o( ̄▽ ̄)ブ,沉寂了这么久我又出来啦,这次先不翻译优质的文章了,这次我们回到Python中的机器学习,看一下Sklearn中的数据预处理和特征工程,老规矩还是先强调一下我的开发环境是 ...

随机推荐

  1. Leetcode-颠倒整数

    给定一个范围为 32 位 int 的整数,将其颠倒. 例 1: 输入: 123 输出: 321 例 2: 输入: -123 输出: -321 例 3: 输入: 120 输出: 21 注意: 假设我们的 ...

  2. 【Swfit】Swift与OC两种语法写单例的区别

    Swift与OC两种语法写单例的区别 例如写一个NetworkTools的单例 (1)OC写单例 + (instancetype)sharedNetworkTools { static id inst ...

  3. 二哥的xss游戏

    断断续续做完了,收获挺多的. 地址:http://xsst.sinaapp.com/xss/ 二哥的xss游戏 第一题http://xsst.sinaapp.com/xss/ext/1.php?umo ...

  4. 计蒜客NOIP模拟赛(2) D1T1邻家男孩

    凡是一个具有领导力的孩子.现实生活中他特别喜欢玩一个叫做 UNO 的纸牌游戏,他也总是带着其他小朋友一起玩,然后战胜他们.慢慢地,他厌倦了胜利,于是准备发明一种新的双人纸牌游戏. 初始时,每个人手中都 ...

  5. NOIWC颓废记

    NOIWC大概就干了3件事情:吃.睡.浪. 吃: 目测绍兴一中的饭比二中的好吃多了,每天都有挺多的肉菜,还有一些甜品,而且是自助,不错的,但是一个不好的是排队时间太长了,于是我这么珍惜时间急着回宿舍的 ...

  6. Spring源码分析(一)--BeanProcessor

    一.何谓BeanProcessor BeanProcessor是SpringFramework里非常重要的核心接口之一,我先贴出一段源代码: /* * Copyright 2002-2015 the ...

  7. python2.7入门---条件语句

        前段时间呢,把MongoDB的基础内容了解的差不多了.接下来,就开始学习python2.7的基础内容喽.接着前面的知识点来学习.首先,来看一下条件语句.Python条件语句是通过一条或多条语句 ...

  8. 关于mysql初始化以及安全策略无法修改的问题

    通过mysql官方的yum源来安装的mysql-community-server ,这里版本是MySQL 8.0. wget  rpm -ivh  mysql80-community-release- ...

  9. CentOS7 下安装 Java 8 [wget]

    1. 创建一个文件夹 sudo mkdir /usr/local/services/java8 2. 使用 wget 来下载 wget --no-cookies --no-check-certific ...

  10. 光电转研发:和计算机没有一点关系的专业怎么去bat类的公司

    光电 女 其实编码能力一般般,拿到百度腾讯研发offer. 一来幸运,二来真的想说行动决定了结果.研一没事就出去家教充实自己赚点钱,研二就开始找实习,去了网易,海康威视,百度实习.感觉还是吃了不少苦的 ...