bla*_*ite 7 python machine-learning decision-tree scikit-learn
使用这个scikit-learn 教程中关于理解决策树结构的一些指导,我有一个想法,也许查看两个连接节点之间发生的特征组合可能会对潜在的“交互”术语有所了解。也就是说,通过查看给定特征y跟随给定特征 的频率x,我们可能能够确定x和之间是否存在某种高阶交互作用y,与模型中的其他变量相比。
这是我的设置。基本上这个对象只是解析树的结构,让我们很容易遍历节点并确定每个节点发生了什么。
import numpy as np
class TreeInteractionFinder(object):
def __init__(
self,
model,
feature_names = None):
self.model = model
self.feature_names = feature_names
self._parse_tree_structure()
self._node_and_leaf_compute()
def _parse_tree_structure(self):
self.n_nodes = self.model.tree_.node_count
self.children_left = self.model.tree_.children_left
self.children_right = self.model.tree_.children_right
self.feature = self.model.tree_.feature
self.threshold = self.model.tree_.threshold
self.n_node_samples = self.model.tree_.n_node_samples
self.predicted_values = self.model.tree_.value
def _node_and_leaf_compute(self):
''' Compute node depth and whether each node is a leaf '''
node_depth = np.zeros(shape=self.n_nodes, dtype=np.int64)
is_leaves = np.zeros(shape=self.n_nodes, dtype=bool)
# Seed is the root node id and its parent depth
stack = [(0, -1)]
while stack:
node_idx, parent_depth = stack.pop()
node_depth[node_idx] = parent_depth + 1
# If we have a test (where "test" means decision-test) node
if self.children_left[node_idx] != self.children_right[node_idx]:
stack.append((self.children_left[node_idx], parent_depth + 1))
stack.append((self.children_right[node_idx], parent_depth + 1))
else:
is_leaves[node_idx] = True
self.is_leaves = is_leaves
self.node_depth = node_depth
Run Code Online (Sandbox Code Playgroud)
接下来,我将在某个数据集上训练一个有点深的树。波士顿住房数据集给了我一些有趣的结果,因此我在我的例子中使用了它:
from sklearn.datasets import load_boston as load_dataset
from sklearn.tree import DecisionTreeRegressor as model
bunch = load_dataset()
X, y = bunch.data, bunch.target
feature_names = bunch.feature_names
model = model(
max_depth=20,
min_samples_leaf=2
)
model.fit(X, y)
finder = TreeInteractionFinder(model, feature_names)
from collections import defaultdict
feature_combos = defaultdict(int)
# Traverse the tree fully, counting the occurrences of features at the current and next indices
for idx in range(finder.n_nodes):
curr_node_is_leaf = finder.is_leaves[idx]
curr_feature = finder.feature_names[finder.feature[idx]]
if not curr_node_is_leaf:
# Test to see if we're at the end of the tree
try:
next_idx = finder.feature[idx + 1]
except IndexError:
break
else:
next_node_is_leaf = finder.is_leaves[next_idx]
if not next_node_is_leaf:
next_feature = finder.feature_names[next_idx]
feature_combos[frozenset({curr_feature, next_feature})] += 1
from pprint import pprint
pprint(sorted(feature_combos.items(), key=lambda x: -x[1]))
pprint(sorted(zip(feature_names, model.feature_importances_), key=lambda x: -x[1]))
Run Code Online (Sandbox Code Playgroud)
其中产生:
$ python3 *py
[(frozenset({'AGE', 'LSTAT'}), 4),
(frozenset({'RM', 'LSTAT'}), 3),
(frozenset({'AGE', 'NOX'}), 3),
(frozenset({'NOX', 'CRIM'}), 3),
(frozenset({'NOX', 'DIS'}), 3),
(frozenset({'LSTAT', 'DIS'}), 2),
(frozenset({'AGE', 'RM'}), 2),
(frozenset({'AGE', 'DIS'}), 2),
(frozenset({'TAX', 'DIS'}), 1),
(frozenset({'RM', 'INDUS'}), 1),
(frozenset({'PTRATIO'}), 1),
(frozenset({'NOX', 'PTRATIO'}), 1),
(frozenset({'LSTAT', 'CRIM'}), 1),
(frozenset({'RM'}), 1),
(frozenset({'TAX', 'PTRATIO'}), 1),
(frozenset({'NOX'}), 1),
(frozenset({'DIS', 'CRIM'}), 1),
(frozenset({'AGE', 'PTRATIO'}), 1),
(frozenset({'AGE', 'CRIM'}), 1),
(frozenset({'ZN', 'DIS'}), 1),
(frozenset({'ZN', 'CRIM'}), 1),
(frozenset({'CRIM', 'PTRATIO'}), 1),
(frozenset({'RM', 'CRIM'}), 1)]
[('RM', 0.60067090411997),
('LSTAT', 0.22148824141475706),
('DIS', 0.068263421165279),
('CRIM', 0.03893906506019243),
('NOX', 0.028695328014265362),
('PTRATIO', 0.014211478583574726),
('AGE', 0.012467751974477529),
('TAX', 0.011821058983765207),
('B', 0.002420619208623876),
('INDUS', 0.0008323703650693053),
('ZN', 0.00018976111002551332),
('CHAS', 0.0),
('RAD', 0.0)]
Run Code Online (Sandbox Code Playgroud)
添加排除“下一个”叶子节点的标准后,结果似乎有所改善。
现在,一种非常频繁出现的特征组合是frozenset({'AGE', 'LSTAT'})——也就是说,建筑物的年龄以及“人口较低地位的百分比”(不管这意味着什么,大概是低收入率的衡量标准)的组合。从model.feature_importances_,LSTAT和AGE都是销售价格的相对重要的预测因素,这让我相信这种功能的组合AGE * LSTAT可能有用。
这甚至是在正确的树上吠叫(可能是双关语)吗?计算给定树中顺序特征的组合是否与模型中的潜在交互有关?
TL;DR:决策树并不是分析特征组合重要性的最佳工具。
与任何其他算法一样,决策树 (DT) 也有其弱点。DT 算法的基本形式假设是它所使用的特征是不相关的。然后,增长 DT 是一个过程,当您从所有可能的问题(决策)集中进行选择时,该过程以产生最大增益的方式分割示例集(根据所选的损失函数,通常是基尼指数或信息增益) 。如果你的特征是相关的,你需要尝试去相关它们(例如通过应用 PCA)或以聪明的方式丢弃一些特征(称为特征选择的过程),否则可能会导致不好的泛化或太多的小叶子。您可以在这里阅读更多相关信息。
DT 的另一个问题是它被设计用于处理分类数据,我们通过对数据应用分箱来使其处理数值数据。因此,在某些功能上,问题的剪切量可能比在其他功能上高得多。
也就是说,在你的DT准备好之后,你就可以了解每个决策的重要性(数据在一定的值范围内):决策越接近树的根,它就越重要。因此位置也很重要,某些特征组合在树中出现的次数并不直接表明该组合的重要性。虽然一些有意义的组合可能会出现,但它们的数量不一定会高到足以脱颖而出。