如何在决策树输出中打印列名,例如特征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]))