标签: pydot

使用 class_names 使用 graphviz 的树节点的颜色

扩展先前的问题: 更改使用导出 graphviz 创建的决策树图的颜色

我将如何根据主导类(鸢尾花的种类)而不是二元区分为树的节点着色?这应该需要 iris.target_names(描述​​类的字符串)和 iris.target(类)的组合。

import pydotplus
from sklearn.datasets import load_iris
from sklearn import tree
import collections

clf = tree.DecisionTreeClassifier(random_state=42)
iris = load_iris()

clf = clf.fit(iris.data, iris.target)

dot_data = tree.export_graphviz(clf, out_file=None,
                                feature_names=iris.feature_names,
                                class_names=iris.target_names,
                                filled=True, rounded=True,
                                special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
nodes = graph.get_node_list()
edges = graph.get_edge_list()

colors = ('brown', 'forestgreen')
edges = collections.defaultdict(list)

for edge in graph.get_edge_list():
    edges[edge.get_source()].append(int(edge.get_destination()))

for edge in edges:
    edges[edge].sort()    
    for i in range(2):
        dest = graph.get_node(str(edges[edge][i]))[0]
        dest.set_fillcolor(colors[i])

graph.write_png('tree.png')
Run Code Online (Sandbox Code Playgroud)

decision-tree graph-visualization python-3.x pydot scikit-learn

5
推荐指数
1
解决办法
7125
查看次数

pydot中两个子图之间的边缘

有谁知道如何在pydot中的两个子图(簇)之间添加边?

callgraph = pydot.Dot(graph_type='digraph',fontname="Verdana")
cluster_foo=pydot.Cluster('foo',label='foo')
cluster_foo.add_node(pydot.Node('foo_method_1',label='method_1'))
callgraph.add_subgraph(cluster_foo)

cluster_bar=pydot.Cluster('bar',label='Component1')
cluster_bar.add_node(pydot.Node('bar_method_a'))
callgraph.add_subgraph(cluster_bar)
Run Code Online (Sandbox Code Playgroud)

我试过了:

callgraph.add_edge(pydot.Edge("foo","bar"))
Run Code Online (Sandbox Code Playgroud)

但不起作用.它只是在初始图形中创建了另外两个标记为"foo"和"bar"的节点,并在它们之间放置了边缘和边缘!

有人可以帮忙吗?

谢谢!

python graph edge graphviz pydot

4
推荐指数
1
解决办法
3317
查看次数

AttributeError:模块“pydot”在spyder中没有属性“graph_from_dot_data”

我正在尝试运行以下代码:

from sklearn.datasets import load_iris
from sklearn import tree
import pydot
clf = tree.DecisionTreeClassifier()
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
from sklearn.externals.six import StringIO
from pydot import *
dotfile = StringIO()
tree.export_graphviz(clf, out_file = dotfile)
pydot.graph_from_dot_data(dot_data.getvalue()).write_png("dtree2.png")
Run Code Online (Sandbox Code Playgroud)

我收到以下错误: AttributeError: module 'pydot' has no attribute 'graph_from_dot_data'

我已经努力寻找解决方案,但无法做到。请有人在这方面帮助我。

python pydot

4
推荐指数
1
解决办法
5039
查看次数

sklearn.tree.export_graphviz替代品

可以使用pydotpluspypi 来显示决策树,但它在我的机器上有问题(它说它不是用libexpat构建的,因此它只显示节点上的数字而不是带有一些信息的表)我想要使用替代方案.我已经尝试过使用networkx,但它需要pygraphviz读取.dot文件并制作它们的网络图.当我尝试使用也失败的pip安装它时.

所以现在我正在寻找一种可视化决策树的替代方法,可以使用pip或anaconda进行安装.

有哪些替代品?

编辑#1

产量conda list:

# packages in environment at /home/xiaolong/development/anaconda3/envs/coursera_ml_classification:
#
alabaster                 0.7.7                    py34_0    defaults
awscli                    1.6.2                     <pip>
babel                     2.3.3                    py34_0    defaults
backports                 1.0                      py34_0    defaults
backports-abc             0.4                       <pip>
backports.shutil-get-terminal-size 1.0.0                     <pip>
backports_abc             0.4                      py34_0    defaults
bcdoc                     0.12.2                    <pip>
boto                      2.33.0                    <pip>
botocore                  0.73.0                    <pip>
cairo                     1.12.18                       6    defaults
certifi                   2015.4.28                 <pip>
colorama                  0.2.5                     <pip>
cycler                    0.10.0                   py34_0    defaults
decorator                 4.0.9                    py34_0    defaults
docutils                  0.12                     py34_0    defaults
entrypoints               0.2 …
Run Code Online (Sandbox Code Playgroud)

python visualization decision-tree pydot scikit-learn

4
推荐指数
1
解决办法
2434
查看次数

Pydot没有打好换线?

蝙蝠 - Ubuntu 12.04,python 2.7,使用pydot 1.0.2

我正在尝试让pydot将树打印到.png.我正在制作我的节点:

subnode = pydot.Node(fullstr, label = c + "\n" + n)
graph.add_node(subnode)
Run Code Online (Sandbox Code Playgroud)

在这里,cn,fullstr只是字符串.

这很好,但是当我跑:

graph.write_png(output_path)
Run Code Online (Sandbox Code Playgroud)

我得到以下错误(哎呀!) - 请在休息后继续关注

Traceback (most recent call last):
  File "Ant.py", line 47, in <module>
    f.makeOutput("output/ant", display=True)
  File "/home/aespielberg/ppr/ppr/svggen/library/api/component.py", line 322, in makeOutput
    self.makeComponentTree(filedir + "/tree.png")
  File "/home/aespielberg/ppr/ppr/svggen/library/api/component.py", line 267, in makeComponentTree
    graph.write_png(fn)
  File "/usr/lib/pymodules/python2.7/pydot.py", line 1602, in <lambda>
    lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog))
  File "/usr/lib/pymodules/python2.7/pydot.py", line 1696, in write
    dot_fd.write(self.create(prog, …
Run Code Online (Sandbox Code Playgroud)

python png newline pydot

3
推荐指数
1
解决办法
1512
查看次数

export_graphviz中的"class_names"意外关键字错误

使用以下代码:

classes = ['ham', 'spam']
dot_data = StringIO()
with open("./plots/ritesh.dot", "w") as f:
    export_graphviz(dt_old.named_steps['classifier'], out_file=f, feature_names=vocab1, class_names=classes)
Run Code Online (Sandbox Code Playgroud)

我收到错误作为意外的关键字参数.

Traceback (most recent call last):
  File "DecisionTree.py", line 198, in <module>
    main()
  File "DecisionTree.py", line 133, in main
    export_graphviz(dt_old.named_steps['classifier'], out_file=f, feature_names=vocab1, class_names=classes)
TypeError: export_graphviz() got an unexpected keyword argument 'class_names'
Run Code Online (Sandbox Code Playgroud)

但是在scikit-learn doc中明确提到了这一点

sklearn.tree.export_graphviz(decision_tree, out_file='tree.dot', max_depth=None, feature_names=None, class_names=None, label='all', filled=False, leaves_parallel=False, impurity=True, node_ids=False, proportion=False, rotate=False, rounded=False, special_characters=False)
Run Code Online (Sandbox Code Playgroud)

TypeError的原因是什么?

graphviz python-2.7 pydot scikit-learn

3
推荐指数
1
解决办法
1465
查看次数

AttributeError: 'list' 对象没有属性 'create_png'

这将数据分类为决策树。决策树已创建,但我无法查看决策树。

import numpy as np
from sklearn import linear_model, datasets, tree
import matplotlib.pyplot as plt
iris = datasets.load_iris()
f = open('decision_tree_data.txt')
x_train = []
y_train = []
for line in f:
    line = np.asarray(line.split(),dtype = np.float32)
    x_train.append(line[:-1])
    y_train.append(line[:-1])
x_train = np.asmatrix(x_train)
y_train = np.asmatrix(y_train)
model = tree.DecisionTreeClassifier()
model.fit(x_train,y_train)
from sklearn.externals.six import StringIO
import pydot
from IPython.display import Image
dot_data = StringIO()
tree.export_graphviz(model, out_file=dot_data,  
                     feature_names=iris.feature_names,  
                     class_names=iris.target_names,  
                     filled=True, rounded=True,  
                     special_characters=True)  
graph = pydot.graph_from_dot_data(dot_data.getvalue()) 
Image(graph.create_png())
Run Code Online (Sandbox Code Playgroud)

machine-learning graphviz decision-tree python-3.x pydot

3
推荐指数
1
解决办法
4549
查看次数

keras 和 pydot 中的 plot_model 问题

我读过类似的问题 - 我的错误似乎有所不同,因为提出的解决方案不能解决我的问题。

我在绘制 keras 模型图时遇到问题。

我已经使用自制软件安装了 graphviz 二进制文件

我已经使用 pip 安装了 graphviz python 包装器和 pydot(也尝试过使用 conda,因为这在过去似乎是一个问题)。

使用 python 3.5

跑步:

from keras.utils import plot_model plot_model(cnn_model, to_file='cnn_model.png')

我收到错误:

导入错误:无法导入 pydot。您必须安装 pydot 和 graphvizpydotprint才能工作。

跟踪:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/Users/jusjosgra/anaconda/lib/python3.5/site-packages/keras/utils/vis_utils.py in _check_pydot()
     26         # so no specific class can be caught.
---> 27         raise ImportError('Failed to import pydot. You must install pydot'
     28                           ' and graphviz for `pydotprint` to work.')

AttributeError: 'NoneType' object has no attribute …
Run Code Online (Sandbox Code Playgroud)

python graphviz pydot keras

3
推荐指数
3
解决办法
2万
查看次数

多节点样式

根据此页面:http : //www.graphviz.org/content/node-shapes Graphviz 支持每个节点的多种样式。

我正在尝试制作一个带有红色填充物的圆形盒子。在链接的页面上,多个样式用逗号分隔,所以我在 Python 中尝试使用pydot

graph.add_node( pydot.Node( 'external', shape='box', style='rounded,filled', fillcolor='red' ) )
Run Code Online (Sandbox Code Playgroud)

但这会引发错误。我还尝试用空格分隔或传递样式列表。无法让它工作

有没有人设法将多种样式应用于节点?

python styles nodes pydot

2
推荐指数
1
解决办法
1146
查看次数

使用PyDot排列Dot图形的头部?

我正在制作一个动态生成的实验室实验图.这就是现在的样子:

实验图

理想情况下,我希望蓝色节点在顶部排成一行,这样无论导致它们的历史有多大,当前的实验都是可见的.有没有办法在GraphViz中做到这一点?我正在使用PyDot,但也打开手动编辑点图.

我在这里发现了一个可能相关的问题,是否会将它们放在子图帮助中?

编辑:这是当前的点代码.

digraph depgraph {
rankdir=BT;
dpi=400;
"/experiments/2013-12-19_planmacro" [shape=rectangle, href="/experiments/2013-12-19_planmacro", fontsize=11, color="#61BD4D", label="Plan 96-well plate montage macro", penwidth=2];
"/experiments/2013-07-01_fluoromax" [shape=rectangle, href="/experiments/2013-07-01_fluoromax", fontsize=11, color="#cccccc", label="Testing OD730", penwidth=2];
"/experiments/2013-06-12_cloning" [shape=rectangle, href="/experiments/2013-06-12_cloning", fontsize=11, color="#cccccc", label="Re-cloning TFs", penwidth=2];
"/experiments/2014-01-02_startwt" [shape=rectangle, href="/experiments/2014-01-02_startwt", fontsize=11, color="#61BD4D", label="Start WT Cultures", penwidth=2];
"/experiments/2013-06-04_learning" [shape=rectangle, href="/experiments/2013-06-04_learning", fontsize=11, color="#cccccc", label="Learning R + Bioconductor", penwidth=2];
"/experiments/2013-07-xx_induction" [shape=rectangle, href="/experiments/2013-07-xx_induction", fontsize=11, color="#61BD4D", label="induction again", penwidth=2];
"/experiments/2013-06-04_bg11" [shape=rectangle, href="/experiments/2013-06-04_bg11", fontsize=11, color="#cccccc", label="BG11 Media + Plates", penwidth=2];
"/experiments/2013-06-13_chipseq" [shape=rectangle, href="/experiments/2013-06-13_chipseq", fontsize=11, color="#61BD4D", …
Run Code Online (Sandbox Code Playgroud)

python graph dot graphviz pydot

1
推荐指数
1
解决办法
1448
查看次数

Python编码风格-多个return语句

对于同一任务,我编写了两个不同的函数。我想知道哪个更优雅。

任务是检查pydot对象是否包含请求的节点,如果是,则返回节点和图形对象。如果该节点不存在,则需要创建该节点。

为了获得节点的名称,我使用pydot对象get_nodes()函数。但是,如果尚未引入任何节点,则此函数将返回一个空列表。因此,在遍历值之前,我进行了一个空列表检查。

第一个变体(“ variant1”)很容易理解。在进行长度检查(这是由于所必需的)之后node.get_name(),它循环到节点名称,一旦找到要搜索的节点,就返回该节点和图形。如果没有,它将调用一个函数来创建节点并更新图形。尽管此功能易于理解,但恕我直言,它并不美观。它包含两个“ return”语句:

def variant1(node_name, graph):

    if len(graph.get_nodes()) > 0:

        for node in graph.get_nodes():
            if node_name == node.get_name():
                return node, graph

    return create_node(node_name, graph)
Run Code Online (Sandbox Code Playgroud)

第二种变体要复杂得多。一旦在图中找到该节点,它就会断开并直接跳到最后一行(“返回节点,图”)。此变体只有一个return语句。

def variant2(node_name, graph):

    if len(graph.get_nodes()) > 0:

        for node in graph.get_nodes():
            if node_name == node.get_name():
                break

        else:
            # the node doesnt exist. create it and update the graph
            node, graph = create_node(node_name, graph)

    else:
        # create the first node in the graph
        node, graph …
Run Code Online (Sandbox Code Playgroud)

python coding-style pydot

1
推荐指数
1
解决办法
1万
查看次数

keras.utils.plot_model 没有显示图形

我正在学习 Keras 和 TensorFlow,我正在尝试运行一个包含 keras.utils.plot_model 指令的示例代码,但他没有向我展示图形,代码的另一部分工作得很好,但最后,我看不到程序应该显示的图形。我有 2 天的时间试图解决这个问题,但我做不到。这是代码:

import numpy as np    
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

inputs = keras.Input(shape=(784,))
print(inputs.shape) 
print(inputs.dtype) 

dense = layers.Dense(64, activation="relu")
x = dense(inputs) 
x = layers.Dense(64, activation="relu")(x) 
outputs = layers.Dense(10)(x)

model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model")
print(model.summary())

keras.utils.plot_model(model, "my_first_model.png")

Run Code Online (Sandbox Code Playgroud)

这是模型结果,没有显示图形:

(None, 784)
<dtype: 'float32'>
2020-06-14 13:24:33.233826: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Model: "mnist_model"
_________________________________________________________________
Layer (type)                 Output …
Run Code Online (Sandbox Code Playgroud)

python pydot keras tensorflow

0
推荐指数
1
解决办法
825
查看次数