In [1]:
import numpy as np
import pandas as pd

from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

构建 DataFrame

首先我们创造一个 DataFrame

In [2]:
animal = ['cat', 'dog', 'fish', 'cat']
colors = ['white', 'yellow', 'red', 'yellow']
data = pd.DataFrame({'animal': animal, 'color': colors})
data
Out[2]:
animal color
0 cat white
1 dog yellow
2 fish red
3 cat yellow

LabelEncoder

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html

数字化以后的数据才有用,直接用字符串是不能使用 sklearn 里面的各种分类器的。

数字化后的数据会失去之前的标签,只留下一个数字。相同的类的数字相等。

In [3]:
for feature in data:
    le = LabelEncoder()
    data[feature] = le.fit_transform(data[feature])
    print feature, le.classes_
data
animal ['cat' 'dog' 'fish']
color ['red' 'white' 'yellow']
Out[3]:
animal color
0 0 1
1 1 2
2 2 0
3 0 2

OneHot 编码

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

OneHot 编码常用于分类问题,因为字符串无法直接输出,这涉及到自然语言处理的问题。

而进行 OneHot 编码之后的数据就非常适合神经网络来分类了。

进行 OneHot 编码以后的数据,同一个类的向量方向相同,不同的类的向量相互正交。此外每个向量都是单位向量。

In [4]:
ohe = OneHotEncoder()
ohed = ohe.fit_transform(pd.DataFrame(data['animal'])).todense()
ohed
Out[4]:
matrix([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.],
        [ 1.,  0.,  0.]])
In [ ]: