Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python sklearn DecisionTreeClassifier使用应被视为分类的字符串_Python_Numpy_Scikit Learn - Fatal编程技术网

Python sklearn DecisionTreeClassifier使用应被视为分类的字符串

Python sklearn DecisionTreeClassifier使用应被视为分类的字符串,python,numpy,scikit-learn,Python,Numpy,Scikit Learn,我正在训练一个sklearn.tree.DecisionTreeClassifier。我从pandas.core.frame.DataFrame开始。此数据帧的某些列是真正应该分类的字符串。例如,“Color”就是这样一列,其值包括“black”、“white”、“red”等。因此,我将此列转换为如下类型: data['Color'] = data['Color'].astype('category') X = data.drop(['OutcomeType'], axis=1) y = da

我正在训练一个
sklearn.tree.DecisionTreeClassifier
。我从pandas.core.frame.DataFrame开始。此数据帧的某些列是真正应该分类的字符串。例如,“Color”就是这样一列,其值包括“black”、“white”、“red”等。因此,我将此列转换为如下类型:

data['Color'] = data['Color'].astype('category')
X = data.drop(['OutcomeType'], axis=1)
y = data['OutcomeType']
X_train, X_test, y_train, y_test = train_test_split(X, y)
这个很好用。现在,我使用
sklearn.cross\u validation.train\u test\u split
拆分数据帧,如下所示:

data['Color'] = data['Color'].astype('category')
X = data.drop(['OutcomeType'], axis=1)
y = data['OutcomeType']
X_train, X_test, y_train, y_test = train_test_split(X, y)
现在,
X\u列车
的类型为
numpy.ndarray
。但是,“颜色”值不再是分类的,而是字符串

因此,当我打以下电话时:

    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X_train, y_train)
我得到以下错误:

ValueError:无法将字符串转换为浮点:黑色


要使其正常工作,我需要做什么?

如果要将分类列转换为整数,可以使用
data.Color.cat.code
;这使用
data.Color.cat.categories
来执行映射(第i个数组元素映射到整数
i

正如ayhan所说,一种解决方法是从“Color”变量创建虚拟特征(这在决策树/RF中非常常见)

您可以使用以下内容:

def feature_to_dummy(df, column, drop=False):
    ''' take a serie from a dataframe,
        convert it to dummy and name it like feature_value
        - df is a dataframe
        - column is the name of the column to be transformed
        - if drop is true, the serie is removed from dataframe'''
    tmp = pd.get_dummies(df[column], prefix=column, prefix_sep='_')
    df = pd.concat([df, tmp], axis=1, join_axes=[df.index])
    if drop:
        del df[column]
    return df
有关熊猫的信息,请参见。获取假人

示例

df
Out[1]: 
   color
0    red
1  black
2  green

df_dummy = feature_to_dummy(df, 'color', drop=True)

df_dummy
Out[2]: 
   color_black  color_green  color_red
0            0            0          1
1            1            0          0
2            0            1          0

我不确定算法的细节,但我认为你需要的是假人而不是类别类型。有了熊猫,你可以试着做些小假人,因为sklearn也有类似的预处理工具