【问题标题】:Plot Interactive Decision Tree in Jupyter Notebook在 Jupyter Notebook 中绘制交互式决策树
【发布时间】:2018-11-18 05:21:48
【问题描述】:

有没有办法在 Jupyter Notebook 中绘制决策树,以便我可以交互式地探索它的节点?我正在考虑这样的事情。这是来自 KNIME 的示例。

我找到了 https://planspace.org/20151129-see_sklearn_trees_with_d3/https://bl.ocks.org/ajschumacher/65eda1df2b0dd2cf616f,我知道你可以在 Jupyter 中运行 d3,但我没有找到任何可以这样做的包。

【问题讨论】:

  • 尝试使用 Jupyter Javascript Magic 插入 javascript sn-p:jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/…
  • 如果你可以传递你点击的节点的子集数据,也许这个包可以帮助你:Treeviz Disclaim : I made this package.
  • 有问题的示例与@NicolòGasparini 评论相结合应该可以解决问题。这个问题是否更多地是关于是否有一种方法或者一个可接受的答案仅限于命名一个包进行可视化?

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


【解决方案1】:

有一个名为 pydot 的模块。您可以创建图表并添加边以制作决策树。

import pydot # 

graph = pydot.Dot(graph_type='graph')
edge1 = pydot.Edge('1', '2', label = 'edge1')
edge2 = pydot.Edge('1', '3', label = 'edge2')
graph.add_edge(edge1)
graph.add_edge(edge2)

graph.write_png('my_graph.png')

这是一个输出决策树的 png 文件的示例。希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在 Jupyter Notebook 中使用 d3js 更新了带有可折叠图形的答案

    笔记本中第一个单元格的开始

    %%html
    <div id="d3-example"></div>
    <style>
    
    .node circle {
      cursor: pointer;
      stroke: #3182bd;
      stroke-width: 1.5px;
    }
    
    .node text {
      font: 10px sans-serif;
      pointer-events: none;
      text-anchor: middle;
    }
    
    line.link {
      fill: none;
      stroke: #9ecae1;
      stroke-width: 1.5px;
    }
    </style>
    

    笔记本中第一个单元格的结尾

    笔记本中第二个单元格的开始

    %%javascript
    // We load the d3.js library from the Web.
    require.config({paths:
        {d3: "http://d3js.org/d3.v3.min"}});
    require(["d3"], function(d3) {
      // The code in this block is executed when the
      // d3.js library has been loaded.
    
      // First, we specify the size of the canvas
      // containing the visualization (size of the
      // <div> element).
      var width = 960,
        height = 500,
        root;
    
      // We create a color scale.
      var color = d3.scale.category10();
    
      // We create a force-directed dynamic graph layout.
    //   var force = d3.layout.force()
    //     .charge(-120)
    //     .linkDistance(30)
    //     .size([width, height]);
        var force = d3.layout.force()
        .linkDistance(80)
        .charge(-120)
        .gravity(.05)
        .size([width, height])
        .on("tick", tick);
    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);
    
    var link = svg.selectAll(".link"),
        node = svg.selectAll(".node");
    
      // In the <div> element, we create a <svg> graphic
      // that will contain our interactive visualization.
     var svg = d3.select("#d3-example").select("svg")
      if (svg.empty()) {
        svg = d3.select("#d3-example").append("svg")
              .attr("width", width)
              .attr("height", height);
      }
    var link = svg.selectAll(".link"),
        node = svg.selectAll(".node");
      // We load the JSON file.
      d3.json("graph2.json", function(error, json) {
        // In this block, the file has been loaded
        // and the 'graph' object contains our graph.
     if (error) throw error;
    else
        test(1);
    root = json;
          test(2);
          console.log(root);
      update();
    
    
    
      });
        function test(rr){console.log('yolo'+String(rr));}
    
    function update() {
        test(3);
      var nodes = flatten(root),
          links = d3.layout.tree().links(nodes);
    
      // Restart the force layout.
      force
          .nodes(nodes)
          .links(links)
          .start();
    
      // Update links.
      link = link.data(links, function(d) { return d.target.id; });
    
      link.exit().remove();
    
      link.enter().insert("line", ".node")
          .attr("class", "link");
    
      // Update nodes.
      node = node.data(nodes, function(d) { return d.id; });
    
      node.exit().remove();
    
      var nodeEnter = node.enter().append("g")
          .attr("class", "node")
          .on("click", click)
          .call(force.drag);
    
      nodeEnter.append("circle")
          .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });
    
      nodeEnter.append("text")
          .attr("dy", ".35em")
          .text(function(d) { return d.name; });
    
      node.select("circle")
          .style("fill", color);
    }
        function tick() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });
    
      node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
    }
              function color(d) {
      return d._children ? "#3182bd" // collapsed package
          : d.children ? "#c6dbef" // expanded package
          : "#fd8d3c"; // leaf node
    }
          // Toggle children on click.
    function click(d) {
      if (d3.event.defaultPrevented) return; // ignore drag
      if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      update();
    }
        function flatten(root) {
      var nodes = [], i = 0;
    
      function recurse(node) {
        if (node.children) node.children.forEach(recurse);
        if (!node.id) node.id = ++i;
        nodes.push(node);
      }
    
      recurse(root);
      return nodes;
    }
    
    });
    

    笔记本中第二个单元格的结尾

    graph2.json 的内容

       {
     "name": "flare",
     "children": [
      {
       "name": "analytics"
        },
        {
       "name": "graph"
        }
       ]
    }
    

    图表

    点击flare,也就是根节点,其他节点会崩溃

    此处使用的笔记本的 Github 存储库Collapsible tree in ipython notebook

    参考文献

    旧答案

    我发现 this tutorial here 用于 Jupyter Notebook 中决策树的交互式可视化。

    安装graphviz

    有两个步骤: 第 1 步:使用 pip 为 python 安装 graphviz

    pip install graphviz
    

    第 2 步:然后您必须单独安装 graphviz。检查此link。 然后根据您的系统操作系统,您需要相应地设置路径:

    适用于 Windows 和 Mac OS check this link。 对于 Linux/Ubuntu check this link

    安装 ipywidgets

    使用点子

    pip install ipywidgets
    jupyter nbextension enable --py widgetsnbextension
    

    使用 conda

    conda install -c conda-forge ipywidgets
    

    现在是代码

    from IPython.display import SVG
    from graphviz import Source
    from sklearn.datasets load_iris
    from sklearn.tree import DecisionTreeClassifier, export_graphviz
    from sklearn import tree
    from ipywidgets import interactive
    from IPython.display import display                               
    

    加载数据集,例如本例中的 iris 数据集

    data = load_iris()
    
    #Get the feature matrix
    features = data.data
    
    #Get the labels for the sampels
    target_label = data.target
    
    #Get feature names
    feature_names = data.feature_names
    

    **绘制决策树的函数**

    def plot_tree(crit, split, depth, min_split, min_leaf=0.17):
        classifier = DecisionTreeClassifier(random_state = 123, criterion = crit, splitter = split, max_depth = depth, min_samples_split=min_split, min_samples_leaf=min_leaf)
        classifier.fit(features, target_label)
    
        graph = Source(tree.export_graphviz(classifier, out_file=None, feature_names=feature_names, class_names=['0', '1', '2'], filled = True))
    
        display(SVG(graph.pipe(format='svg')))
    return classifier
    

    调用函数

    decision_plot = interactive(plot_tree, crit = ["gini", "entropy"], split = ["best", "random"]  , depth=[1, 2, 3, 4, 5, 6, 7], min_split=(0.1,1), min_leaf=(0.1,0.2,0.3,0.5))
    
    display(decision_plot)
    

    您将得到以下图表

    您可以通过更改以下值以交互方式更改输出单元格中的参数

    关于相同数据但参数不同的另一棵决策树

    参考资料:

    【讨论】:

    • 不幸的是,这不是我想要的答案。您描述了如何使用不同的输入参数构建不同的决策树。我有兴趣探索单个决策树。也就是说,交互地折叠和扩展决策树节点以了解其做出的预测。我的决策树也可能非常大(10-100s)的节点。
    • @r0f1 我已根据您的 cmets 更新了我的答案。现在它使用 d3.js 来展开/折叠树。这是一个仅使用 3 个节点的小示例。如果此答案对您有所帮助,请将其标记为正确答案(和/或投票):)
    • 嘿@r0f1,你只需要创建json文件,节点就会相应地创建。这是力导向间隙的示例,您也可以在此处使用任何其他图表(包括您在问题中建议的 heiraricahl 图)
    【解决方案3】:

    我发现了一个基于交互式决策树构建的 GitHub 项目。 也许这可能会有所帮助:

    这是基于 r2d3 库,它接受 Json 脚本并创建决策树的交互式映射。

    https://github.com/yamad/r2d3-decision-tree

    【讨论】:

      【解决方案4】:

      1.如果您只是想在 Jupyter 中使用 D3,这里有一个教程:https://medium.com/@stallonejacob/d3-in-juypter-notebook-685d6dca75c8

      2.为了构建交互式决策树,这里有另一个有趣的 GUI 工具包,称为 TMVAGui。

      这里的代码只是单行代码: factory.DrawDecisionTree(dataset, "BDT")

      https://indico.cern.ch/event/572131/contributions/2315243/attachments/1343269/2023816/gsoc16_4thpresentation.pdf

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 2020-12-12
        • 2016-11-16
        • 2019-06-19
        • 1970-01-01
        • 2021-05-27
        • 2011-03-15
        • 2021-09-16
        相关资源
        最近更新 更多