Участок интерактивного решения в ноутбуке Jupyter - программирование
Подтвердить что ты не робот

Участок интерактивного решения в ноутбуке Jupyter

Есть ли способ построить дерево решений в Jupyter Notebook, чтобы я мог интерактивно исследовать его узлы? Я думаю о чем-то подобном dt. Это пример из KNIME.

Я нашел https://planspace.org/20151129-see_sklearn_trees_with_d3/ и https://bl.ocks.org/ajschumacher/65eda1df2b0dd2cf616f, и я знаю, что вы можете запустить d3 в Jupyter, но я не нашел пакетов, которые делают это,

4b9b3361

Ответ 1

Обновленный ответ с разборным графиком с использованием d3js в Jupyter Notebook

Начало 1-й ячейки в блокноте

%%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>

Конец 1-й ячейки в блокноте

Начало второй ячейки в блокноте

%%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"
    }
   ]
}

График enter image description here

Нажмите на факел, который является корневым узлом, остальные узлы рухнут

enter image description here

Репозиторий Github для ноутбука, используемый здесь: Сложное дерево в записной книжке ipython

Рекомендации

Старый ответ

Я нашел этот учебник здесь для интерактивной визуализации дерева решений в Jupyter Notebook.

Установить graphviz

Для этого есть два шага: Шаг 1: Установите graphviz для python, используя pip

pip install graphviz

Шаг 2: Затем вам нужно установить графический интерфейс отдельно. Проверьте эту ссылку. Затем, основываясь на вашей системной ОС, вам необходимо установить путь следующим образом:

Для Windows и Mac OS проверьте эту ссылку. Для Linux/Ubuntu проверьте эту ссылку

Установка 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                               

Загрузите набор данных, скажем, например, набор данных диафрагмы в этом случае

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)

Вы получите следующий график enter image description here

Вы можете изменить параметры в интерактивном режиме в выходной ячейке, используя следующие значения

enter image description here

Другое дерево решений по тем же данным, но с различными параметрами enter image description here

Рекомендации:

Ответ 2

1. Если вы просто хотите использовать D3 в Jupyter, вот учебник: https://medium.com/@stallonejacob/d3-in-juypter-notebook-685d6dca75c8

enter image description here

enter image description here

2. Для создания интерактивного дерева решений, вот еще один интересный инструментарий GUI, называемый TMVAGui.

В этом код является только одним слоем: factory.DrawDecisionTree(dataset, "BDT")

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

Ответ 3

Существует модуль под названием 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 файл вашего дерева решений. Надеюсь это поможет!

Ответ 4

Я нашел проект GitHub, основанный на интерактивном построении дерева решений. Возможно, это может помочь:

Это основано на библиотеке r2d3, которая принимает сценарий Json и создает интерактивное отображение дерева решений.

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