簡體   English   中英

在決策樹分類器中使用OneHotEncoder進行分類功能

[英]Using OneHotEncoder for categorical features in decision tree classifier

我是Python的ML新手,對於如何使用分類變量實現決策樹感到非常困惑,因為它們由R中的partyctree自動編碼。

我想創建一個具有兩個分類獨立特征和一個相關類的決策樹。

我正在使用的數據框如下所示:

data
      title_overlap_quartile sales_rank_quartile rank_grp
    0                     Q4                  Q2    GRP 1
    1                     Q4                  Q3    GRP 1
    2                     Q2                  Q1    GRP 1
    3                     Q4                  Q1    GRP 1
    5                     Q2                  Q1    GRP 2

我了解到,需要使用labelencoder和/或一個熱編碼器在scikit學習中對分類特征進行編碼。

首先,我嘗試僅使用標簽編碼器,但這不能解決問題,因為DecisionTreeClassifier開始將編碼后的變量視為連續變量。 然后,我從這篇文章中閱讀: 有關分類功能的OneHotEncoder問題,應首先使用標簽編碼器對變量進行編碼,然后再使用一個熱編碼器對變量進行再次編碼。

我嘗試通過以下方式在此數據集上實現該功能,但出現錯誤。

def encode_features(df, columns):
    le = preprocessing.LabelEncoder()
    ohe = preprocessing.OneHotEncoder(sparse=False)
    for i in columns:
        le.fit(df[i].unique())
        df[i+'_le'] = le.transform(df[i])
        df[i+'_le'] = df[i+'_le'].values.reshape(-1, 1)
        df[i+'_le'+'_ohe'] = ohe.fit_transform(df[i+'_le'])
    return(df)

data = encode_features(data, ['title_overlap_quartile', 'sales_rank_quartile'])


  File "/Users/vaga/anaconda2/envs/py36/lib/python3.5/site-packages/pandas/core/series.py", line 2800, in _sanitize_index
    raise ValueError('Length of values does not match length of ' 'index')

ValueError: Length of values does not match length of index

當我刪除ohe部分從功能外運行它,它運行但結果看起來很怪異:

def encode_features(df, columns):
    le = preprocessing.LabelEncoder()
    ohe = preprocessing.OneHotEncoder(sparse=False)
    for i in columns:
        le.fit(df[i].unique())
        df[i+'_le'] = le.transform(df[i])
        # df[i+'_le'] = df[i+'_le'].values.reshape(-1, 1)
        # df[i+'_le'+'_ohe'] = ohe.fit_transform(df[i+'_le'])
    return(df)

data = encode_features(data, ['title_overlap_quartile', 'sales_rank_quartile']) 

data['title_overlap_quartile_le'] = data['title_overlap_quartile_le'].values.reshape(-1, 1)

print(ohe.fit_transform(data['title_overlap_quartile_le']))

[[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
   1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
   1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
   1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]

我還嘗試使用pandas.get_dummies ,它使用二進制編碼將變量轉換為多列並使用了它,但是再次被決策樹分類器視為連續變量。

有人可以幫助我如何使用分類變量作為分類來擬合決策樹並輸出樹形圖嗎?

擬合和繪制我正在使用的樹的代碼是:

clf = tree.DecisionTreeClassifier()
clf = clf.fit(data[['title_overlap_score', 'sales_rank_quartile']], data[['rank_grp']])

dot_data = tree.export_graphviz(clf, out_file=None, feature_names=data[['title_overlap_score', 'sales_rank_quartile']].columns,  
                         filled=True, rounded=True,  
                         special_characters=True)  

graph = graphviz.Source(dot_data)  
graph.render("new_tree")

盡管應該使用決策樹來處理類別變量,但是由於存在這個未解決的錯誤,sklearn的實現目前無法實現。 當前的解決方法有些復雜,它是在將分類變量傳遞給分類器之前對其進行一次熱編碼。

您是否嘗試過category_encoders 這更易於處理,也可以在管道中使用。

scikit-learn的最新尚未發布版本似乎允許字符串列類型,而無需轉換為int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM