特征预处理

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
from sklearn.preprocessing import StandardScaler

#模块1 标准化
#无量纲化使不同规格的数据转换到同一规格。常见的无量纲化方法有标准化和区间缩放法。
#标准化的前提是特征值服从正态分布,标准化后,其转换成标准正态分布。

x = np.array([[1,0,1],[0,1,0],[1,0,0]],dtype=float)

y = StandardScaler().fit_transform(x)

print y

‘‘‘
[[ 0.70710678 -0.70710678  1.41421356]
 [-1.41421356  1.41421356 -0.70710678]
 [ 0.70710678 -0.70710678 -0.70710678]]
‘‘‘

#模块2 区间缩放
#区间缩放法利用了边界值信息,将特征的取值区间缩放到某个特点的范围,例如[0, 1]等。
print ‘\n222222222222222222222222222222222\n‘
from sklearn.preprocessing import MinMaxScaler
x = np.array([[1,2,3],[4,5,6],[7,8,9]],dtype=float)
y = MinMaxScaler().fit_transform(x)
print y  #注意fit+transform

y1 = MinMaxScaler().fit(x)
print y1 #注意至少存储相关参数,并没有转变

y2 = y1.transform(x)
print y2 #进行实际变换
‘‘‘
[[ 0.          1.          0.        ]
 [ 1.          0.          1.        ]
 [ 0.66666667  0.66666667  0.125     ]]
MinMaxScaler(copy=True, feature_range=(0, 1))
[[ 0.          1.          0.        ]
 [ 1.          0.          1.        ]
 [ 0.66666667  0.66666667  0.125     ]]
‘‘‘

#模块3 使用preproccessing库的Normalizer类对数据进行归一化的代码如下:
from sklearn.datasets import load_iris
iris = load_iris()
print iris.data
print iris.target

from sklearn.preprocessing import Normalizer
print Normalizer().fit_transform(iris.data)

#模块4 二值化
print ‘\n4\n‘
from sklearn.preprocessing import Binarizer
X = [[ 1., -1.,  2.],[ 2.,  0.,  0.], [ 0.,  1., -1.]]
binarizer = Binarizer().fit(X)
# fit does nothing
# binarizer Binarizer(copy=True, threshold=0.0)
print binarizer.transform(X)
‘‘‘
[[ 1.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]
‘‘‘
#It is possible to adjust the threshold of the binarizer:
binarizer = Binarizer(threshold=1.1)
print binarizer.transform(X)
‘‘‘
[[ 0.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  0.  0.]]
‘‘‘
#模块5 OneHotEncoder
‘‘‘
4.3.4. Encoding categorical features
Often features are not given as continuous values but categorical.
For example a person could have features
["male", "female"],
["from Europe", "from US", "from Asia"],
["uses Firefox", "uses Chrome", "uses Safari", "uses Internet Explorer"].
Such features can be efficiently coded as integers,
for instance ["male", "from US", "uses Internet Explorer"] could be expressed as [0, 1, 3]
while ["female", "from Asia", "uses Chrome"] would be [1, 2, 1].
Such integer representation can not be used directly with scikit-learn estimators,
as these expect(期望、期待) continuous input, and would interpret the categories as being ordered,
which is often not desired (i.e. the set of browsers was ordered arbitrarily).
One possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K or one-hot encoding, which is implemented in OneHotEncoder.
This estimator transforms each categorical feature with m possible values into m binary features, with only one active.
Continuing the example above:
‘‘‘
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder()
print enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])
print enc.transform([[0, 1, 3]]).toarray()
print enc.transform([[1, 1, 0]]).toarray()
print enc.transform([[0, 2, 1]]).toarray()
print enc.transform([[1, 0, 2]]).toarray()

‘‘‘
By default, how many values each feature can take is inferred automatically from the dataset.
It is possible to specify this explicitly using the parameter n_values.
There are two genders, three possible continents and four web browsers in our dataset.
Then we fit the estimator, and transform a data point.
In the result, the first two numbers encode the gender, the next set of three numbers the continent and the last four the web browser.
‘‘‘

#模块6 补充缺失数值
print ‘\n666666666666666666666666666666666666666\n‘
import numpy as np
from sklearn.preprocessing import Imputer
imp = Imputer(missing_values=‘NaN‘, strategy=‘mean‘, axis=0)
print 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 x
#[[nan, 2], [6, nan], [7, 6]]
# x is list
print(imp.transform(x))
‘‘‘
[[ 4.          2.        ]
 [ 6.          3.66666667]
 [ 7.          6.        ]]
‘‘‘

#注意到 水平缺失值 4 = (1+7)/2, 列的平均值
#注意到 水平缺失值 3.6666 = (2+3+6)/3,列的平均值

#模块7 多项式特征
#Generating polynomial features
print ‘\n777777777777777777777777777777\n‘
from sklearn.preprocessing import PolynomialFeatures
X = np.arange(6).reshape(3, 2)
print X
poly = PolynomialFeatures(2)
poly.fit_transform(X)
print poly.fit_transform(X)
#(x1,x2)->(1,x1,x2,x1的平方,x1x2,x2的平方)
‘‘‘
[[0 1]
 [2 3]
 [4 5]]
[[  1.   0.   1.   0.   0.   1.]
 [  1.   2.   3.   4.   6.   9.]
 [  1.   4.   5.  16.  20.  25.]]
‘‘‘
X = np.arange(9).reshape(3, 3)
poly = PolynomialFeatures(degree=3, interaction_only=True)
print poly.fit_transform(X)
‘‘‘
[[   1.    0.    1.    2.    0.    0.    2.    0.]
 [   1.    3.    4.    5.   12.   15.   20.   60.]
 [   1.    6.    7.    8.   42.   48.   56.  336.]]
‘‘‘

#模块8  函数变换
#FunctionTransformer
print ‘\n888888888888888888888888888888\n‘
‘‘‘
Often, you will want to convert an existing Python function into a transformer to assist in data cleaning
or processing. You can implement a transformer from an arbitrary function with FunctionTransformer.
For example, to build a transformer that applies a log transformation in a pipeline, do:
‘‘‘
import numpy as np
from sklearn.preprocessing import FunctionTransformer
transformer = FunctionTransformer(np.log1p)
X = np.array([[0, 1], [2, 3]])
print transformer.transform(X)
‘‘‘
[[ 0.          0.69314718]
 [ 1.09861229  1.38629436]]
‘‘‘
时间: 2024-08-26 19:07:09

特征预处理的相关文章

机器学习系列(6)_从白富美相亲看特征预处理与选择(下)

作者:viewmode=contents">龙心尘 &&寒小阳 时间:2016年1月. 出处: http://blog.csdn.net/longxinchen_ml/article/details/50493845. http://blog.csdn.net/han_xiaoyang/article/details/50503115 声明:版权全部,转载请联系作者并注明出处 1. 剧情一:挑螃蟹的秘密 李雷与韩梅梅的关系发展得不错.趁国庆休假一起来天津玩. 今天,李雷十分

特征工程之特征预处理

在前面我们分别讨论了特征工程中的特征选择与特征表达,本文我们来讨论特征预处理的相关问题.主要包括特征的归一化和标准化,异常特征样本清洗与样本数据不平衡问题的处理. 1. 特征的标准化和归一化  由于标准化和归一化这两个词经常混用,所以本文不再区别标准化和归一化,而通过具体的标准化和归一化方法来区别具体的预处理操作. z-score标准化:这是最常见的特征预处理方式,基本所有的线性模型在拟合的时候都会做 z-score标准化.具体的方法是求出样本特征x的均值mean和标准差std,然后用(x-me

特征工程——特征预处理

特征的标准化和归一化 异常特征样本清洗 处理不平衡数据 特征的标准化和归一化   由于标准化和归一化这两个词经常混用,所以本文不再区别标准化和归一化,而通过具体的标准化和归一化方法来区别具体的预处理操作. z-score标准化:这是最常见的特征预处理方式,基本所有的线性模型在拟合的时候都会做 z-score标准化.具体的方法是求出样本特征x的均值mean和标准差std,然后用(x-mean)/std来代替原特征.这样特征就变成了均值为0,方差为1了.在sklearn中,我们可以用Standard

1. 特征工程之特征预处理

1. 前言 "数据决定了机器学习的上限,而算法只是尽可能逼近这个上限",这里的数据指的就是经过特征工程得到的数据.特征工程指的是把原始数据转变为模型的训练数据的过程,它的目的就是获取更好的训练数据特征,使得机器学习模型逼近这个上限.特征工程能使得模型的性能得到提升,有时甚至在简单的模型上也能取得不错的效果.特征工程在机器学习中占有非常重要的作用,主要包括数据与特征预处理.特征选择和数据的降维三部分.接下去会通过3篇文章对这三方面进行介绍.今天首先讲讲数据与特征的预处理. 2. 数据与特

1.3_数据的特征预处理

数据的特征预处理 单个特征 (1)归一化 归一化首先在特征(维度)非常多的时候,可以防止某一维或某几维对数据影响过大,也是为了把不同来源的数据统一到一个参考区间下,这样比较起来才有意义,其次可以程序可以运行更快. 例如:一个人的身高和体重两个特征,假如体重50kg,身高175cm,由于两个单位不一样,数值大小不一样.如果比较两个人的体型差距时,那么身高的影响结果会比较大,k-临近算法会有这个距离公式. min-max方法 常用的方法是通过对原始数据进行线性变换把数据映射到[0,1]之间,变换的函

03_数据的特征预处理

03 数据特征预处理 特征的预处理 特征的预处理 定义:通过特定的统计方法(数学方法),将数据转换成算法要求的数据. 数值型数据:标准缩放 归一化 标准化 类别性数据: one-hot编码 时间类型: 时间的切分 归一化 定义: 通过对原始数据的变化把数据映射到 [0,1] 之间 优点:多个特征时,某一个特征对最终结果不会造成更大的影响 (同一个维度) 缺点:容易受到极大值和极小值的影响 标准化 定义: 将原始数据变换为均值为0, 标准差为1的范围内 如果出现异常点,由于具有一定的数据量,少量的

机器学习系列(5)_从白富美相亲名单看特征选择与预处理(上)

作者:龙心尘 &&寒小阳 时间:2016年1月. 出处: http://blog.csdn.net/longxinchen_ml/article/details/50471682, http://blog.csdn.net/han_xiaoyang/article/details/50481967 声明:版权所有,转载请联系作者并注明出处 1. 引言 再过一个月就是春节,相信有很多码农就要准备欢天喜地地回家过(xiang)年(qin)了.我们今天也打算讲一个相亲的故事. 讲机器学习为什么要

快速入门特征工程

有一句话在业界广为流传:特征工程决定了模型的上界,调参决定模型能够有多逼近这个上界. 这里以sklearn为例讲讲特征工程. 一图概览特征工程 虽然说分了这么多部分,但特征工程最重要的部分还是特征处理,特征处理主要包含三个方面,特征预处理,特征选择和降维度. 数据预处理 数据预处理一方面把特征转为合适的编码喂给我们学习算法,另一方面就是把数据都转化到一个同一个规格.我们平时会用公制单位,那么对于特征也要转化到这样的公制单位.都是身高体重的数据,转化到公制下比较方便. 无量纲化 即把特征转化到"公

特征工程之特征选择

特征工程是数据分析中最耗时间和精力的一部分工作,它不像算法和模型那样是确定的步骤,更多是工程上的经验和权衡.因此没有统一的方法.这里只是对一些常用的方法做一个总结.本文关注于特征选择部分.后面还有两篇会关注于特征表达和特征预处理. 1. 特征的来源 在做数据分析的时候,特征的来源一般有两块,一块是业务已经整理好各种特征数据,我们需要去找出适合我们问题需要的特征:另一块是我们从业务特征中自己去寻找高级数据特征.我们就针对这两部分来分别讨论. 2.  选择合适的特征 我们首先看当业务已经整理好各种特