sci-kit中使用的功能可以学习DT的实现

时间:2013-10-06 14:28:00

标签: python scikit-learn decision-tree feature-selection

我在sci-kit学习中实现了带有CV的DT分类器。 但是,我还想输出有助于分类的功能数量。这是我到目前为止的代码:

from collections import defaultdict

import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.tree import DecisionTreeClassifier

from scipy.sparse import csr_matrix

lemma2feat = defaultdict(lambda: defaultdict(float))  # { lemma: {feat : weight}}
lemma2cat = dict()
features = set()


with open("input.csv","rb") as infile:
    for line in infile:
        lemma, feature, weight, tClass = line.split()
        lemma2feat[lemma][feature] = float(weight)
        lemma2cat[lemma] = int(tClass)
        features.add(feature)

sorted_rows = sorted(lemma2feat.keys())
col2index = dict()
for colIdx, col in enumerate(sorted(list(features))):
    col2index[col] = colIdx

dMat = np.zeros((len(sorted_rows), len(col2index.keys())), dtype = float)


# popola la matrice
for vIdx, vector in enumerate(sorted_rows):
    for feature in lemma2feat[vector].keys():
        dMat[vIdx][col2index[feature]] = lemma2feat[vector][feature]

res = []
for lem in sorted_rows:
    res.append(lemma2cat[lem])


clf = DecisionTreeClassifier(random_state=0)


print "Acc:"
print cross_val_score(clf, dMat, np.asarray(res), cv=10, scoring = "accuracy")

我可以包括输出功能的数量,例如,我查看了RFE,正如我在另一个问题中查询的那样,但它不能轻易地包含在DT中。因此,我想知道是否有一种方法可以修改我的上述代码,以输出有助于实现最高精度的功能数量。这里的总体目标是在肘图中绘制这与其他分类器的输出相比较。 谢谢。

1 个答案:

答案 0 :(得分:1)

一旦您的树适合,您可以使用feature_importances_属性检查相关功能。如果第i个特征对于构建树很重要/有帮助,它将为您提供一个n_features浮点值数组,以使feature_importances_[i]为高(与其他值相对)(低于(关闭)到0)如果不是。