python - 决策树学习中当前节点到下一个节点的特征组合: useful to determine potential interactions?

标签 python machine-learning scikit-learn decision-tree

使用 this 中的一些指导在关于理解决策树结构的 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

接下来,我将在一些数据集上训练一棵稍深的树。波士顿住房数据集给了我一些有趣的结果,因此我在我的示例中使用了它:

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]))

其产量:

$ 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)]

添加排除“下一个”叶子节点的标准后,结果似乎有所改善。

现在,经常出现的功能组合是 frozenset({'AGE', 'LSTAT'}) - 也就是说,建筑物的年龄以及“人口地位较低的百分比”的组合(无论这意味着什么,大概是低收入率的衡量标准)。来自 model.feature_importances_ ,两者 LSTATAGE是销售价格相对重要的预测因素,这使我相信这种功能组合 AGE * LSTAT可能有用。

这是否是在吠叫正确的树(可能是双关语)?计算给定树中连续特征的组合是否代表模型中的潜在交互?

最佳答案

TL;DR:决策树并不是分析特征组合重要性的最佳工具。

与任何其他算法一样,决策树 (DT) 也有其弱点。 DT 算法的基本形式假设是它所使用的特征是不相关的。然后,增长 DT 是一个过程,当您从所有可能的问题(决策)集中进行选择时,该过程以产生最大增益的方式分割示例集(根据所选的损失函数,通常是基尼指数或信息增益) 。如果你的特征是相关的,你需要尝试去相关它们(例如通过应用 PCA)或以聪明的方式丢弃一些特征(称为特征选择的过程),否则可能会导致不好的泛化或太多的小叶子。您可以阅读here更多关于它的信息。

DT 的另一个问题是它被设计用于处理分类数据,我们通过应用 binning 使其能够处理数值数据。到数据。因此,在某些功能上,问题的剪切量可能比在其他功能上高得多。

也就是说,当你的DT准备好后,你就可以了解每个决策的重要性(数据在一定的值范围内):决策越接近树的根,它就越重要。因此位置也很重要,某些特征组合在树中出现的次数并不直接表明该组合的重要性。虽然一些有意义的组合可能会出现,但它们的数量不一定会高到足以脱颖而出。

关于python - 决策树学习中当前节点到下一个节点的特征组合: useful to determine potential interactions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58703496/

相关文章:

python - 从 web2py 的私有(private)文件夹中打开一个文本文件

python - 是否可以从 Google 云存储对象创建 TFRecordDataset?

python - 为什么 conv2d 在不同的批量大小下会产生不同的结果

python - Keras 中的 Tensorflow adam 优化器

python - Spotify 授权代码(不是访问 token )即将过期 - 我该如何规避此问题?

Python:从非常大的 JSON 请求中提取特定数据

python - 在 Keras 中训练多元回归模型时损失值非常大

python - 使 sklearn 中的网格搜索功能忽略空模型

python - 我可以对 sklearn 进行对数回归吗?

python - 来自 statsmodels 的自定义估算器 WLS 的 sklearn check_estimator 错误