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

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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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