对于决策树,输出特征名称而不是列号

如何在决策树输出中打印列名,例如特征1、特征2、特征3、特征4、特征5或特征6,而不是-2。答案应该具有可扩展性,例如,如果有人有500列或更多列的情况。

import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationfrom sklearn.ensemble import RandomForestClassifierX, y = make_classification(n_samples=1000,                           n_features=6,                           n_informative=3,                           n_classes=2,                           random_state=0,                           shuffle=False)# 创建数据框df = pd.DataFrame({'Feature 1':X[:,0],                                  'Feature 2':X[:,1],                                  'Feature 3':X[:,2],                                  'Feature 4':X[:,3],                                  'Feature 5':X[:,4],                                  'Feature 6':X[:,5],                                  'Class':y})y_train = df['Class']X_train = df.drop('Class',axis = 1)from sklearn.tree import _tree# 使用这些数组,我们可以解析树结构:n_nodes = dt.tree_.node_countchildren_left = dt.tree_.children_leftchildren_right = dt.tree_.children_rightfeature = dt.tree_.featurethreshold = dt.tree_.thresholdnew_X = np.array(X_train)node_indicator = dt.decision_path(new_X)# 同样,我们也可以得到每个样本到达的叶子节点ID。leave_id = dt.apply(new_X)# 现在,我们可以获取用于预测一个样本或一组样本的测试。首先,让我们为样本做这个。sample_id = 703node_index = node_indicator.indices[node_indicator.indptr[sample_id]:                                    node_indicator.indptr[sample_id + 1]]print('用于预测样本%s的规则: ' % sample_id)for node_id in node_index:    if leave_id[sample_id] != node_id:        continue    if (new_X[sample_id, feature[node_id]] <= threshold[node_id]):        threshold_sign = "<="    else:        threshold_sign = ">"    print("决策节点ID %s : (对于样本编号[%s, %s] (= %s) %s %s)"          % (node_id,             sample_id,             feature[node_id],             new_X[sample_id, feature[node_id]],             threshold_sign,             threshold[node_id]))

用于预测样本703的规则: 决策节点ID 11 : (对于样本编号[703, -2] (= -0.210092480919) > -2.0)


回答:

只需将feature[node_id]替换为df.columns[feature[node_id]],如下所示:

print("决策节点ID %s : (对于样本编号[%s, %s] (= %s) %s %s)"      % (node_id,         sample_id,         X_train.columns[feature[node_id]],         new_X[sample_id, feature[node_id]],         threshold_sign,         threshold[node_id]))

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注