【问题标题】:How to get the MSE of the node in the DecisionTreeRegressor of scikit-learn?如何获取scikit-learn的DecisionTreeRegressor中节点的MSE?
【发布时间】:2020-04-10 00:20:30
【问题描述】:

在生成的决策树回归模型中,使用graphviz查看树结构时有一个MSE属性。我需要获取每个叶子节点的MSE,并根据MSE进行后续操作。但是,在阅读文档后,我找不到提供输出 MSE 的方法。其他属性如特征名、样本数、预测值等。都有对应的方法:

使用help(sklearn.tree._tree.Tree),我可以看到大部分属性都有一些输出值的方法,但是我没有看到任何关于MSE的信息。

关于模块 sklearn.tree._tree 中的类 Tree 的帮助

【问题讨论】:

  • 我们如何重现这样的情节?无论我对DecisionTreeRegressor 做什么,情节总是包含entropy;从不mse
  • 刚刚找到方法。看我的回答。

标签: python scikit-learn


【解决方案1】:

好问题。你需要tree_reg.tree_.impurity

简答:

tree_reg = tree.DecisionTreeRegressor(max_depth=2)
tree_reg.fit(X_train, y_train)

extracted_MSEs = tree_reg.tree_.impurity # The Hidden magic is HERE

for idx, MSE in enumerate(tree_reg.tree_.impurity):
    print("Node {} has MSE {}".format(idx,MSE))

Node 0 has MSE 86.873403833
Node 1 has MSE 40.3211827171
Node 2 has MSE 25.6934820064
Node 3 has MSE 19.0053469592
Node 4 has MSE 74.6839429717
Node 5 has MSE 38.3057346817
Node 6 has MSE 39.6709615385

使用带有视觉输出的 boston 数据集的长答案:

import pandas as pd
import numpy as np
from sklearn import ensemble, model_selection, metrics, datasets, tree
import graphviz

house_prices = datasets.load_boston()

X_train, X_test, y_train, y_test = model_selection.train_test_split(
    pd.DataFrame(house_prices.data, columns=house_prices.feature_names),
    pd.Series(house_prices.target, name="med_price"),
    test_size=0.20, random_state=42)

tree_reg = tree.DecisionTreeRegressor(max_depth=2)
tree_reg.fit(X_train, y_train)

extracted_MSEs = tree_reg.tree_.impurity # YOU NEED THIS 
print(extracted_MSEs)
#[86.87340383 40.32118272 25.69348201 19.00534696 74.68394297 38.30573468 39.67096154]

# Compare visually
dot_data = tree.export_graphviz(tree_reg, out_file=None, feature_names=X_train.columns)
graph = graphviz.Source(dot_data)

#this will create an boston.pdf file with the rule path
graph.render("boston")

将 MSE 值与视觉输出进行比较:

【讨论】:

  • 这如何提供每个节点的 MSE 值?
  • 我正在提取 MSE 值。为什么要投反对票?
  • 在你编辑你的答案之前你不是。我现在已经删除了。请注意,当您的回答没有回答问题时,您被否决了。
  • 我错过了 OP 需要实际值。我的回答现在正好解决了这个问题。干杯
  • 非常感谢,这正是我想要的
【解决方案2】:

你可以使用

from sklearn.metrics import mean_squared_error
mean_squared_error(y_true, y_pred)

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2015-02-23
    • 2019-02-21
    • 2020-12-26
    • 2014-03-06
    • 2019-12-11
    • 2015-11-06
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多