2015-02-08 24 views
2

我想准备一个包含用于分类的连续,名义和有序特征的数据集。我在下面有一些解决方法,但我想知道是否有更好的方式使用scikit-learn的编码器?在scikit-learn中使用OneHotEncoder准备序号和名义特征

让我们看看下面的例子中数据集:

​​

enter image description here

现在,类标签可以简单地通过一个标签编码器转换(分类的类别标签忽略顺序)。

from sklearn.preprocessing import LabelEncoder 
class_le = LabelEncoder() 
df['class label'] = class_le.fit_transform(df['class label'].values) 

而且我会序功能列size转换,像这样:

size_mapping = { 
      'XL': 3, 
      'L': 2, 
      'M': 1} 

df['size'] = df['size'].apply(lambda x: size_mapping[x]) 
df 

enter image description here

最后序color功能:

color_mapping = { 
      'green': [0,0,1], 
      'red': [0,1,0], 
      'blue': [1,0,0]} 

df['color'] = df['color'].apply(lambda x: color_mapping[x]) 
df 

enter image description here

y = df['class label'].values 
X = df.iloc[:, :-1].values 
X = np.apply_along_axis(func1d= lambda x: np.array(x[0] + list(x[1:])), axis=1, arr=X) 
X 

array([[ 0. , 0. , 1. , 1. , 10.1], 
     [ 0. , 1. , 0. , 2. , 13.5], 
     [ 1. , 0. , 0. , 3. , 15.3]]) 

回答

3

您可以使用DictVectorizer进行名义编码,使流程更加清晰。你也可以使用.map()直接应用'size_maping'。

import pandas as pd 
df = pd.DataFrame([['green', 'M', 10.1, 'class1'], ['red', 'L', 13.5, 'class2'], ['blue', 'XL', 15.3, 'class1']]) 
df.columns = ['color', 'size', 'prize', 'class label'] 

from sklearn.preprocessing import LabelEncoder 
class_le = LabelEncoder() 
df['class label'] = class_le.fit_transform(df['class label'].values) 

size_mapping = { 
     'XL': 3, 
     'L': 2, 
     'M': 1} 

df['size'] = df['size'].map(size_mapping) 

feats =df.transpose().to_dict().values() 

from sklearn.feature_extraction import DictVectorizer 
Dvec = DictVectorizer() 

Dvec.fit_transform(feats).toarray() 

回报:

array([[ 0. , 0. , 1. , 0. , 10.1, 1. ], 
     [ 1. , 0. , 0. , 1. , 13.5, 2. ], 
     [ 0. , 1. , 0. , 0. , 15.3, 3. ]]) 

获取的功能名称:

Dvec.get_feature_names() 

['class label', 'color=blue', 'color=green', 'color=red', 'prize', 'size'] 
+0

谢谢,看起来会更加清晰! – Sebastian 2015-02-08 20:33:38

相关问题