Passing categorical data to Sklearn Decision Tree

后端 未结 5 2055
攒了一身酷
攒了一身酷 2020-11-28 23:05

There are several posts about how to encode categorical data to Sklearn Decision trees, but from Sklearn documentation, we got these

Some advantages of d

5条回答
  •  佛祖请我去吃肉
    2020-11-28 23:54

    Contrary to the accepted answer, I would prefer to use tools provided by Scikit-Learn for this purpose. The main reason for doing so is that they can be easily integrated in a Pipeline.

    Scikit-Learn itself provides very good classes to handle categorical data. Instead of writing your custom function, you should use LabelEncoder which is specially designed for this purpose.

    Refer to the following code from the documentation:

    from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    le.fit(["paris", "paris", "tokyo", "amsterdam"])
    le.transform(["tokyo", "tokyo", "paris"]) 
    

    This automatically encodes them into numbers for your machine learning algorithms. Now this also supports going back to strings from integers. You can do this by simply calling inverse_transform as follows:

    list(le.inverse_transform([2, 2, 1]))
    

    This would return ['tokyo', 'tokyo', 'paris'].

    Also note that for many other classifiers, apart from decision trees, such as logistic regression or SVM, you would like to encode your categorical variables using One-Hot encoding. Scikit-learn supports this as well through the OneHotEncoder class.

    Hope this helps!

提交回复
热议问题