分类和数字特征 - 分类目标 - Scikit学习 - Python

USC*_*jan 6 python numerical target scikit-learn categorical-data

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

我应该如何将分类列转换为数值?我尝试了很多东西,但是我得到了不同的错误,例如"str"对象没有'numpy.ndarray'对象没有属性'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
Run Code Online (Sandbox Code Playgroud)

我的数据集保存在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() 
Run Code Online (Sandbox Code Playgroud)

我需要将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 )
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

USC*_*jan 0

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

>>> 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'}]
Run Code Online (Sandbox Code Playgroud)

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

    >>> 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']
Run Code Online (Sandbox Code Playgroud)