分类和数值特征 - 分类目标 - Scikit Learn - Python



我有一个包含分类列和数值列的数据集,我的目标列也是分类列。我在Python34中使用Scikit库。我知道在进行任何机器学习方法之前,Scikit需要将所有分类值转换为数值。

如何将分类列转换为数值?我尝试了很多东西,但我得到了不同的错误,如"str"对象没有"numpy"。narray ' object '没有属性'items'.

Here is an example of my data:
 UserID  LocationID   AmountPaid    ServiceID   Target
 29876      IS345       23.9876      FRDG        JFD
 29877      IS712       135.98       WERS        KOI

我的数据集保存在一个CSV文件中,这里是我写的一小段代码,让你知道我想做什么:

#reading my csv file
data_dir = 'C:/Users/davtalab/Desktop/data/'
train_file = data_dir + 'train.csv'
train = pd.read_csv( train_file )
#numeric columns:
x_numeric_cols = train['AmountPaid']
#Categrical columns:
categorical_cols = ['UserID' + 'LocationID' + 'ServiceID']
x_cat_cols = train[categorical_cols].as_matrix() 

y_target = train['Target'].as_matrix() 

我需要将x_cat_cols转换为数值,并将它们添加到x_numeric_cols中,从而获得完整的输入(x)值。

然后我需要将我的目标函数转换为数值,并使其作为我的最终目标(y)列。

然后我想用这两个完全集做一个随机森林:

rf = RF(n_estimators=n_trees,max_features=max_features,verbose =verbose, n_jobs =n_jobs)
rf.fit( x_train, y_train )

谢谢你的帮助!

对于目标,您可以使用sklearn的LabelEncoder。这将为您提供从字符串标签到数字标签的转换器(以及反向映射)。链接中的示例

对于特征,学习算法通常期望(或最好使用)有序数据。所以最好的选择是使用OneHotEncoder来转换分类特征。这将为每个类别生成一个新的二进制特征,表示每个类别的开/关。同样,链接中的用法示例

这是因为我枚举数据的方式。如果我打印数据(使用另一个示例),您将看到:

>>> import pandas as pd
>>> train = pd.DataFrame({'a' : ['a', 'b', 'a'], 'd' : ['e', 'e', 'f'],
...                       'b' : [0, 1, 1], 'c' : ['b', 'c', 'b']})
>>> samples = [dict(enumerate(sample)) for sample in train]
>>> samples
[{0: 'a'}, {0: 'b'}, {0: 'c'}, {0: 'd'}]

这是一个字典列表。我们应该这样做:

    >>> train_as_dicts = [dict(r.iteritems()) for _, r in train.iterrows()]
    >>> train_as_dicts
    [{'a': 'a', 'c': 'b', 'b': 0, 'd': 'e'},
     {'a': 'b', 'c': 'c', 'b': 1, 'd': 'e'},
     {'a': 'a', 'c': 'b', 'b': 1, 'd': 'f'}]
Now we need to vectorize the dicts:
>>> from sklearn.feature_extraction import DictVectorizer
>>> vectorizer = DictVectorizer()
>>> vectorized_sparse = vectorizer.fit_transform(train_as_dicts)
>>> vectorized_sparse
<3x7 sparse matrix of type '<type 'numpy.float64'>'
    with 12 stored elements in Compressed Sparse Row format>
>>> vectorized_array = vectorized_sparse.toarray()
>>> vectorized_array
array([[ 1.,  0.,  0.,  1.,  0.,  1.,  0.],
       [ 0.,  1.,  1.,  0.,  1.,  1.,  0.],
       [ 1.,  0.,  1.,  1.,  0.,  0.,  1.]])
To get the meaning of each column, ask the vectorizer:
>>> vectorizer.get_feature_names()
['a=a', 'a=b', 'b', 'c=b', 'c=c', 'd=e', 'd=f']

最新更新