Пример #1
0
def execute(path, grammar_file_name, example_file_name, export_dot, export_png):
    '''U svrhe brzeg testiranja, metoda koja prima putanju do foldera, naziv fajla gde je gramatika i naziv fajla gde je
        primer programa u nasem jeziku i indikator da li da se eksportuju .dot i .png fajlovi'''

    meta_path = os.path.join(path, grammar_file_name)
    meta_name = os.path.splitext(meta_path)[0]
    metamodel = metamodel_from_file(meta_path)

    if export_dot:
        metamodel_export(metamodel, meta_name + '.dot')
        if export_png:
            graph = pydotplus.graph_from_dot_file(meta_name + '.dot')
            graph.write_png(meta_name + '.png')

    model_path = os.path.join(path, example_file_name)
    model_name = os.path.splitext(model_path)[0]

    model = metamodel.model_from_file(model_path)

    if export_dot:
        model_export(model, model_name + '.dot')
    if export_png:
        graph = pydotplus.graph_from_dot_file(model_name + '.dot')
        graph.write_png(model_name + '.png')

    return model
Пример #2
0
def show(tree):
    """Creates a DOT file of the tree and displays the tree

      Parameters
      ----------
      tree : PST
             Probabilistic suffix tree object
      """

    f = open("PST.dot", 'w')
    f.write("graph PST {\n")
    f.write("node0" + "[label = Root];\n")
    temp = [tree.root]
    index = [0]
    j = 1
    while len(temp):
        parent = temp.pop(0)
        i = index.pop(0)
        current = parent.getChild()
        while (current != None):
            f.write("node" + str(j) + "[label = " + str(current.getData()) +
                    "];\n")
            f.write("\"node" + str(i) + "\" -- " + "\"node" + str(j) +
                    "\"[label = " + str(current.getCount()) + "]" + ";\n")
            temp.append(current)
            current = current.getNext()
            index.append(j)
            j += 1
    f.write("}")
    f.close()
    graph = pydotplus.graph_from_dot_file("PST.dot")
    graph.write_png("PST.png")
    img = Image.open("PST.png")
    plt.imshow(img)
    plt.axis("off")
Пример #3
0
def read_dot(dot_file):
    """Reads directed graph that describes fuel reprocessing system structure
    from `*.dot` file.

    Parameters
    ----------
    dot_file : str
        Path to `.dot` file with reprocessing system structure.

    Returns
    --------
    mat_name : str
        Name of burnable material which reprocessing scheme described in `.dot`
        file.
    paths_list : list
        List of lists containing all possible paths between `core_outlet` and
        `core_inlet`.

    """
    graph_pydot = pydotplus.graph_from_dot_file(dot_file)
    digraph = nx.drawing.nx_pydot.from_pydot(graph_pydot)
    mat_name = digraph.__str__()
    # iterate over all possible paths between 'core_outlet' and 'core_inlet'
    paths_list = []
    all_simple_paths = nx.all_simple_paths(digraph,
                                           source='core_outlet',
                                           target='core_inlet')
    for path in all_simple_paths:
        paths_list.append(path)
    return mat_name, paths_list
    def summarize(self, file_path):
        if self._trained_model is None:
            raise ValueError('Cannot summarize an untrained model.')

        #Save feature importances
        with open(file_path + 'sklearn_decision_tree_feature_importances.txt', 'w') as f:
            indices = np.argsort(self._trained_model.feature_importances_)[::-1]
            for i in range (0, len(self._trained_model.feature_importances_), 1):
                f.write('{0}: feature {1} ({2}) (column number {3})\n'.format(i+1, self._column_names[indices[i]], self._trained_model.feature_importances_[indices[i]], indices[i]))

        #Save graph viz
        try:
            with open(file_path + 'sklearn_decision_tree.dot', 'w') as f:
                sklearn.tree.export_graphviz(self._trained_model, 
                                             out_file=f, 
                                             feature_names = self._column_names,
                                             class_names = self._class_names,
                                             filled = True,
                                             rounded = True,
                                             special_characters = True)

            #Save pdf
            graph = pydotplus.graph_from_dot_file(file_path + 'sklearn_decision_tree.dot')
            graph.write_pdf(file_path + 'sklearn_decision_tree.pdf')
        except:
            print('Warning: unable to save tree visualizations. Do you have GraphViz installed and in your PATH? (http://www.graphviz.org/)')

        #Save feature parameters
        with open(file_path + 'sklearn_decision_tree_parameters.txt', 'w') as f:
            f.write(json.dumps(self._best_parameters))
Пример #5
0
    def pydot_checks(self, G):
        G.add_edge('A','B')
        G.add_edge('A','C')
        G.add_edge('B','C')
        G.add_edge('A','D')
        G.add_node('E')
        P = nx.to_pydot(G)
        G2 = G.__class__(nx.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true( P.write_raw(fname) )

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true( n1 == n2 )

        e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
        e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
        assert_true( sorted(e1)==sorted(e2) )

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
Пример #6
0
def drawDecisionTree(data, name):
    data['change next day class'] = data['change next day'].apply(classify)
    X_train, X_test, y_train, y_test = train_test_split(
        data[[
            'rate of increase', 'increase length', 'rate of decrease',
            'decrease length'
        ]],
        data['change next day class'],
        test_size=0.2,
        random_state=42)
    tree = DecisionTreeClassifier(max_depth=6, random_state=0)
    tree.fit(X_train, y_train)
    print('Train score:{:.3f}'.format(tree.score(X_train, y_train)))
    print('Test score:{:.3f}'.format(tree.score(X_test, y_test)))
    #生成可视化图
    export_graphviz(tree,
                    out_file="tree.dot",
                    feature_names=[
                        'rate of increase', 'increase length',
                        'rate of decrease', 'decrease length'
                    ],
                    impurity=False,
                    filled=True)
    #展示可视化图
    graph = pydotplus.graph_from_dot_file('tree.dot')
    graph.write_pdf(name + '.pdf')
Пример #7
0
def treeClassifier():
    dtc = DecisionTreeClassifier(max_depth=4)

    x, y = retrieveData(make_floats=False)

    train_size = 25000

    x_train = x[:train_size]
    y_train = y[:train_size]

    x_test = x[train_size:]
    y_test = y[train_size:]

    dtc.fit(x_train, y_train)
    dot_data = tree.export_graphviz(dtc, out_file="tree.dot", 
                         feature_names=["LIMIT_BAL","SEX","EDUCATION","MARRIAGE","AGE","PAY_0","PAY_2","PAY_3","PAY_4","PAY_5","PAY_6","BILL_AMT1","BILL_AMT2","BILL_AMT3","BILL_AMT4","BILL_AMT5","BILL_AMT6","PAY_AMT1","PAY_AMT2","PAY_AMT3","PAY_AMT4","PAY_AMT5","PAY_AMT6"],
                         class_names=["NO", "YES"], 
                         filled=True, rounded=True,  
                         special_characters=True)  


    graph = pydotplus.graph_from_dot_file('tree.dot')
    graph.write_png("tree.png")

    print("accuracy =", dtc.score(x_test, y_test))
Пример #8
0
def plot_simple_tree(clf, output_simple_tree):

    class_names = ['Control', 'VIH']
    dot_data = StringIO()

    export_graphviz(clf,
                    out_file=dot_data,
                    feature_names=feature_cols,
                    filled=True,
                    rounded=True,
                    impurity=False,
                    class_names=class_names,
                    precision=4)

    #PATH = '/home/clescoat/Documents/ProteomX/treett.dot'
    f = pydotplus.graph_from_dot_file(dot_data).to_string()

    print(f)

    # suppress samples / value in all nodes
    f = re.sub("samples = \d{1,2}", '', f)
    f = re.sub("value = \[[0-9]{0,2}\.?[0-9]{0,4}, [0-9]{0,2}\.?[0-9]{0,4}\]", '', f)
    f = re.sub("\\\\n", '', f)
    f = re.sub("\dclass", '\nclass', f)

    # suppress "class" in decision nodes
    f = re.sub("\d\nclass = [a-zA-Z]*", '', f)

    with open('tree_modifiedtt.dot', 'w') as file:
        file.write(f)

    (graph,) = pydot.graph_from_dot_file("tree_modifiedtt.dot")
    graph.write_png('tree_finaltt.png')
Пример #9
0
def build_graph(dotfile):
    dot_graph = pydotplus.graph_from_dot_file(dotfile)
    graph = {}
    graph['graph_name'] = dot_graph.get_name().strip('"')
    print('graph_name:', dot_graph.get_name().strip('"'))
    graph['nodes'] = {}
    for node in dot_graph.get_nodes():
        label = node.obj_dict['attributes']['label'].strip('"')
        if label in graph['nodes'].keys():
            print('Two same functions exist in one graph.')
            exit()
        graph['nodes'][label] = []
    for edge in dot_graph.get_edges():
        source_node_list = dot_graph.get_node(edge.get_source())
        desti_node_list = dot_graph.get_node(edge.get_destination())
        if len(source_node_list) != 1 or len(desti_node_list) != 1:
            print(
                'node do not exist or there are more than one node with the same name.'
            )
            exit()
        source_label = source_node_list[0].obj_dict['attributes'][
            'label'].strip('"')
        desti_node_label = desti_node_list[0].obj_dict['attributes'][
            'label'].strip('"')
        graph['nodes'][source_label].append(desti_node_label)
    return graph
Пример #10
0
    def pydot_checks(self, G):
        G.add_edge('A', 'B')
        G.add_edge('A', 'C')
        G.add_edge('B', 'C')
        G.add_edge('A', 'D')
        G.add_node('E')
        P = nx.nx_pydot.to_pydot(G)
        G2 = G.__class__(nx.nx_pydot.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true(P.write_raw(fname))

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true(n1 == n2)

        e1 = [(e.get_source(), e.get_destination()) for e in P.get_edge_list()]
        e2 = [(e.get_source(), e.get_destination())
              for e in Pin.get_edge_list()]
        assert_true(sorted(e1) == sorted(e2))

        Hin = nx.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
    def display_DT(self, estimator, features, classes, newimg='tree.png', tmpimg='tree.dot', precision=2):
        from sklearn.tree import export_graphviz
        import io
        import pydotplus
        #graph = Source(export_graphviz(estimator, out_file=None
        #                                    , feature_names=features, class_names=['0', '1']
        #                                    , filled=True))
        #display(SVG(graph.pipe(format='svg')))
        # plot_tree(estimator, filled=True)
        # plt.show()
        # return

        # Export as dot file
        export_graphviz(estimator, out_file=tmpimg,
                                   feature_names=features,
                                   class_names=classes,
                                   rounded=True, proportion=False,
                                   precision=3, filled=True)
        #from subprocess import call
        #call(['dot', '-Tpng', tmpimg, '-o', newimg, '-Gdpi=600'])
        # os.system('dot -Tpng {} -o {}, -Gdpi=600'.format(tmpimg, newimg))
        # Display in python
        #import matplotlib.pyplot as plt

        # Draw graph
        #graph = graphviz.Source(dot_data)
        #dotfile = io.StringIO()
        graph = pydotplus.graph_from_dot_file(tmpimg)
        graph.write_png(newimg)
        print(graph)
    def load_dot_file(self, path):
        pydot_graph = pydotplus.graph_from_dot_file(path)

        coordinates_exist = self._check_for_coordinates(pydot_graph)
        if coordinates_exist:
            self._pydot_graph = pydot_graph
        else:
            raise NoCoordinatesInDotData()
Пример #13
0
def generate_tree_config_diagram(model, feature_names):
    model_type = model.__class__.__name__
    output_file_name = model_type + '.dot'
    dot_data = tree.export_graphviz(model, out_file = output_file_name,
                                 feature_names=feature_names, filled   = True
                                    , rounded  = True
                                    , special_characters = True)
    graph = pydotplus.graph_from_dot_file(output_file_name)  
    graph.write_png(model_type + "_diagram.png")
Пример #14
0
    def save(self):
        nx.drawing.nx_pydot.write_dot(self.g, 'output/graph.dot')
        gdot = pydotplus.graph_from_dot_file('output/graph.dot')
        gdot.write_png('output/graph.png')

        plt.figure()
        self.drawLegend()
        plt.tight_layout()
        plt.savefig('output/legend.png', format='png')
    def summarize(self, file_path):
        if self._trained_model is None:
            raise ValueError('Cannot summarize an untrained model.')

        #Save feature importances
        with open(file_path + 'sklearn_extra_trees_feature_importances.txt',
                  'w') as f:
            indices = np.argsort(
                self._trained_model.feature_importances_)[::-1]
            for i in range(0, len(self._trained_model.feature_importances_),
                           1):
                f.write('{0}: feature {1} ({2}) (column number {3})\n'.format(
                    i + 1, self._column_names[indices[i]],
                    self._trained_model.feature_importances_[indices[i]],
                    indices[i]))

        #Save graph viz
        try:
            tree_index = 0
            for estimator in self._trained_model.estimators_:
                with open(
                        file_path +
                        'sklearn_extra_trees_{0}.dot'.format(tree_index),
                        'w') as f:
                    sklearn.tree.export_graphviz(
                        estimator,
                        out_file=f,
                        feature_names=self._column_names,
                        class_names=self._class_names,
                        filled=True,
                        rounded=True,
                        special_characters=True)

                #Save pdf
                graph = pydotplus.graph_from_dot_file(
                    file_path +
                    'sklearn_extra_trees_{0}.dot'.format(tree_index))
                graph.write_pdf(
                    file_path +
                    'sklearn_extra_trees_{0}.pdf'.format(tree_index))
                tree_index += 1

            merger = PyPDF2.PdfFileMerger()
            for i in range(0, tree_index, 1):
                with open(file_path + 'sklearn_extra_trees_{0}.pdf'.format(i),
                          'rb') as f:
                    merger.append(PyPDF2.PdfFileReader(f))
            merger.write(file_path + 'sklearn_extra_trees_all.pdf')
        except Exception:
            print(
                'Warning: unable to save tree visualizations. Do you have GraphViz installed and in your PATH? (http://www.graphviz.org/)'
            )

        #Save feature parameters
        with open(file_path + 'sklearn_extra_trees_parameters.txt', 'w') as f:
            f.write(json.dumps(self._best_parameters))
Пример #16
0
def show_tree_graph(train_X, tree_model):
    export_graphviz(tree_model, out_file='tree_dot', feature_names=train_X.columns, class_names=['0', '1'], filled=True, rounded=True)
    g = pydotplus.graph_from_dot_file(path='tree_dot')
    gg = g.create_png()
    img = io.BytesIO(gg)
    img2 = Image.open(img)

    plt.figure(figsize=(img2.width/100, img2.height/100), dpi=100)
    plt.imshow(img2)
    plt.axis('off')
    plt.show()
Пример #17
0
def draw_file(model, dot_file, png_file, feature_names, class_names):
    os.environ["PATH"] += os.pathsep + 'D:/Anaconda3/Library/bin/graphviz'
    dot_data = tree.export_graphviz(model, out_file=dot_file,
                                    feature_names=feature_names,
                                    class_names=class_names,
                                    filled=True,
                                    rounded=True,
                                    special_characters=True)

    graph = pydotplus.graph_from_dot_file(dot_file)
    graph.write_png(png_file)
Пример #18
0
    def Plot_Decision_Tree(self, name, features, classes, classifier):
        tree.export_graphviz(classifier,
                             out_file=str(name) + '_d_tree.dot',
                             feature_names=features,
                             class_names=classes,
                             filled=False,
                             rounded=True,
                             impurity=True)

        graph = pydotplus.graph_from_dot_file(str(name) + "_d_tree.dot")
        graph.write_png(str(name) + "_d_tree.png")
 def drawTreeFromDot(self, fileloc):
     graph = pydotplus.graph_from_dot_file(fileloc)
     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('white')
     graph.write_png('tree.png')
Пример #20
0
def draw_file(model, dot_file, png_file, feature_names):
    dot_data = tree.export_graphviz(model,
                                    out_file=dot_file,
                                    feature_names=feature_names,
                                    filled=True,
                                    rounded=True,
                                    special_characters=True)
    graph = pydotplus.graph_from_dot_file(dot_file)
    thisIsTheImage = Image(graph.create_png())
    display(thisIsTheImage)
    #print(dt.tree_.feature)
    from subprocess import check_call
    check_call(['dot', '-Tsvg', dot_file, '-o', png_file])
Пример #21
0
def draw(alfabeto, estados, inicio, trans, final, nro_vuelta):
    g = gv.Digraph(format='dot')
    g.graph_attr['rankdir'] = 'LR'
    g.node('ini', shape="point")
    for e in estados:
        try:
            current = e[1]
            e = e[0]
        except:
            current = False
            e = e
        if e in final:
            if current is True:
                g.node(e, shape="doublecircle", color='blue')
            else:
                g.node(e, shape="doublecircle")
        else:
            if current is True:
                g.node(e, shape="circle", color='blue')
            else:
                g.node(e, shape="circle")
        if e in inicio:
            if nro_vuelta == 0:
                g.edge('ini', e, color='blue', weight='2')
            else:
                g.edge('ini', e)

    for t in trans:
        if t[2] not in alfabeto:
            return 0
        try:
            if t[3] is True:
                g.edge(t[0], t[1], label=str(t[2]), color='blue', weight='2')
            else:
                g.edge(t[0], t[1], label=str(t[2]))
        except:
            g.edge(t[0], t[1], label=str(t[2]))
    g.render(filename="temp/dot/temp", view=False)
    graph = pydotplus.graph_from_dot_file('temp/dot/temp.dot')
    graph.write_jpg('temp/dot/Digraph_' + str(nro_vuelta) + '.png')
    from PIL import Image
    im = Image.open('temp/dot/Digraph_' + str(nro_vuelta) + '.png')
    bg = Image.new("RGB", im.size, (255, 255, 255))
    bg.paste(im)
    if bg.size[0] >= 410:
        basewidth = 410
        wpercent = (basewidth / float(bg.size[0]))
        hsize = int((float(bg.size[1]) * float(wpercent)))
        bg = bg.resize((basewidth, hsize), Image.ANTIALIAS)
    bg.save('temp/Digraph_' + str(nro_vuelta) + '.gif')
    shutil.rmtree('temp/dot')
Пример #22
0
def draw(alfabeto, estados, inicio, trans, final, nro_vuelta):
    g = gv.Digraph(format='dot')
    g.graph_attr['rankdir'] = 'LR'
    g.node('ini', shape="point")
    for e in estados:
        try:
            current = e[1]
            e = e[0]
        except:
            current = False
            e = e
        if e in final:
            if current is True:
                g.node(e, shape="doublecircle", color='blue')
            else:
                g.node(e, shape="doublecircle")
        else:
            if current is True:
                g.node(e, shape="circle", color='blue')
            else:
                g.node(e, shape="circle")
        if e in inicio:
            if nro_vuelta == 0:
                g.edge('ini', e, color='blue', weight='2')
            else:
                g.edge('ini', e)

    for t in trans:
        if t[2] not in alfabeto:
            return 0
        try:
            if t[3] is True:
                g.edge(t[0], t[1], label=str(t[2]), color='blue', weight='2')
            else:
                g.edge(t[0], t[1], label=str(t[2]))
        except:
            g.edge(t[0], t[1], label=str(t[2]))
    g.render(filename="temp/dot/temp", view=False)
    graph = pydotplus.graph_from_dot_file('temp/dot/temp.dot')
    graph.write_jpg('temp/dot/Digraph_'+str(nro_vuelta)+'.png')
    from PIL import Image
    im = Image.open('temp/dot/Digraph_'+str(nro_vuelta)+'.png')
    bg = Image.new("RGB", im.size, (255,255,255))
    bg.paste(im)
    if bg.size[0] >= 410:
        basewidth = 410
        wpercent = (basewidth/float(bg.size[0]))
        hsize = int((float(bg.size[1])*float(wpercent)))
        bg = bg.resize((basewidth,hsize), Image.ANTIALIAS)
    bg.save('temp/Digraph_'+str(nro_vuelta)+'.gif')
    shutil.rmtree('temp/dot')
Пример #23
0
    def _render_with_pydot(self, filename):
        # f = open(filename, 'rt')
        # graph_data = f.read()
        # f.close()

        # g = pydotplus.parse_from_dot_data(graph_data)
        g = pydotplus.graph_from_dot_file(filename)

        if not isinstance(g, list):
            g = [g]

        jpe_data = NULL_SEP.join([_g.create(format='jpe') for _g in g])

        return sha256(jpe_data).hexdigest()
Пример #24
0
    def _render_with_pydot(self, filename):
        # f = open(filename, 'rt')
        # graph_data = f.read()
        # f.close()

        # g = pydotplus.parse_from_dot_data(graph_data)
        g = pydotplus.graph_from_dot_file(filename)

        if not isinstance(g, list):
            g = [g]

        jpe_data = NULL_SEP.join([_g.create(format='jpe') for _g in g])

        return sha256(jpe_data).hexdigest()
Пример #25
0
def decisionTree():
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(iris.data, iris.target)
    with open("D://iris.dot", 'w') as f:
        f = tree.export_graphviz(clf, out_file=f,
                         feature_names=iris.feature_names,  
                         class_names=iris.target_names,  
                         filled=True, rounded=True,  
                         special_characters=True) 
    from IPython.display import Image
    import pydotplus 
    dot_data = pydotplus.graph_from_dot_file("D://iris.dot")
    Image(dot_data.create_png())  
    dot_data.write_pdf("D://iris.pdf") 
Пример #26
0
def dectree_model3():
    X = upsampled[['MF_01', 'eTIV', 'nWBV']]
    y = upsampled['MMSE_Group_Status']

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        test_size=0.25,
                                                        random_state=42)

    scaler = RobustScaler()
    scaler.fit(X_train)
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    dt = DecisionTreeClassifier(max_depth=2)
    dt1_model = dt.fit(X_train_scaled, y_train)
    dt1_model_r2 = dt1_model.score(X_test_scaled, y_test)
    y3_pred = dt1_model.predict(X_test_scaled)

    conf_matrix3 = confusion_matrix(y_test, y3_pred)
    class_report3 = classification_report(y_test, y3_pred)
    precision3 = precision_score(y_test, y3_pred)

    fpr3, tpr3, thresholds3 = roc_curve(y_test, y3_pred, pos_label=1)
    auc_dt3 = auc(fpr3, tpr3)
    plt.figure(5)
    plt.plot(fpr3, tpr3, marker='.', label='Model 3 (AUC = %0.3f)' % auc_dt3)
    plt.xlabel('False Positive Rate (1 - Specificity)')
    plt.ylabel('True Positive Rate (Sensitivity)')
    plt.legend()
    plt.show()

    dt1_feature_names = ['Sex', 'eTIV', 'nWBV']
    dt_class_names = ['Impaired',
                      'Intact']  # Needs to be in ascending numerical order
    export_graphviz(dt1_model,
                    out_file='tree1.dot',
                    feature_names=dt1_feature_names,
                    class_names=dt_class_names,
                    filled=True)
    dt1_graph = pydotplus.graph_from_dot_file('tree1.dot')

    result3 = [
        3, 'Decision Tree (without CDR)', dt1_model_r2, tpr3, 1 - fpr3,
        auc_dt3, precision3
    ]

    return dt1_model_r2, conf_matrix3, class_report3, dt1_graph, result3, precision3
Пример #27
0
def judge_new_dotfile(dotfile, graphs):
    dot_graph = pydotplus.graph_from_dot_file(dotfile)
    node1_label = dot_graph.get_node(
        'Node1')[0].obj_dict['attributes']['label'].strip('"')
    desti = []
    for edge in dot_graph.get_edges():
        if edge.get_source() == 'Node1':
            desti.append(
                dot_graph.get_node(edge.get_destination())
                [0].obj_dict['attributes']['label'].strip('"'))
    for graph in graphs:
        if node1_label in graph['nodes'].keys():
            desti_list = graph['nodes'][node1_label]
            if compare_two_lists(desti, desti_list) is True:
                return True
    return False
Пример #28
0
def dectree_model4():
    X = upsampled[['MF_01', 'CDR', 'eTIV', 'nWBV']]
    y = upsampled['MMSE_Group_Status']

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        test_size=0.25,
                                                        random_state=42)

    scaler = RobustScaler()
    scaler.fit(X_train)
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    dt = DecisionTreeClassifier(max_depth=2)
    dt2_model = dt.fit(X_train_scaled, y_train)
    dt2_model_r2 = dt2_model.score(X_test_scaled, y_test)
    y4_pred = dt2_model.predict(X_test_scaled)

    conf_matrix4 = confusion_matrix(y_test, y4_pred)
    class_report4 = classification_report(y_test, y4_pred)
    precision4 = precision_score(y_test, y4_pred)

    fpr4, tpr4, thresholds4 = roc_curve(y_test, y4_pred, pos_label=1)
    auc_dt4 = auc(fpr4, tpr4)
    plt.figure(5)
    plt.plot(fpr4, tpr4, marker='.', label='Model 4 (AUC = %0.3f)' % auc_dt4)
    plt.xlabel('False Positive Rate (1 - Specificity)')
    plt.ylabel('True Positive Rate (Sensitivity)')
    plt.legend()
    plt.show()

    dt2_feature_names = ['Sex', 'CDR', 'eTIV', 'nWBV']
    dt_class_names = ['Intact', 'Impaired']
    export_graphviz(dt2_model,
                    out_file='tree2.dot',
                    feature_names=dt2_feature_names,
                    class_names=dt_class_names,
                    filled=True)
    dt2_graph = pydotplus.graph_from_dot_file('tree2.dot')

    result4 = [
        4, 'Decision Tree (with CDR)', dt2_model_r2, tpr4, 1 - fpr4, auc_dt4,
        precision4
    ]

    return dt2_model_r2, conf_matrix4, class_report4, dt2_graph, result4, precision4
Пример #29
0
 def browseFiles():
     global G
     filename = filedialog.askopenfilename(
         initialdir="/",
         title="Select a File",
         filetypes=(("Pliki dot", "*.dot*"), ("Wszystkie pliki", "*.*")))
     if type(filename) is str:
         G = pydotplus.graph_from_dot_file(filename)
         # nodeLabeling(G,0)
         edgeLabeling(G)
         SaveGraphPng()
         # print("hooray")
         now = datetime.now()
         UpdateStatisticsLabel()
         current_time = now.strftime("%H:%M:%S")
         LogListBox.insert(END, current_time + " Graf wczytany poprawnie")
         label_file_explorer.configure(text="File Opened: " + filename)
Пример #30
0
    def _render_with_pydot(self, filename):
        # f = open(filename, 'rt')
        # graph_data = f.read()
        # f.close()

        # g = pydotplus.parse_from_dot_data(graph_data)
        # 根据filename绘制总图
        g = pydotplus.graph_from_dot_file(filename)

        # 如果总图的类型不是list,将其改变为list
        if not isinstance(g, list):
            g = [g]

            # 使用NULL_SEP将总图的元素进行处理后添加到一起
        jpe_data = NULL_SEP.join([_g.create(format='jpe') for _g in g])

        # 使用sha256对jpe_data进行加密,hexdigest的含义是返回十六进制的摘要
        return sha256(jpe_data).hexdigest()
Пример #31
0
    def print_network(self):
        f = open('graph.dot', 'w+')
        # print('digraph G {')
        f.write('digraph G {\r\n')
        for node in self.nodes:
            data = 'Keys:\n-------------\n'
            # print(f'{node.node_id} -> {node.successor.node_id}')
            f.write(f'{node.node_id} -> {node.successor.node_id}\r\n')
            for key in sorted(node.data.keys()):
                data += f'key: {key} - data: \'{node.data[key]}\'\n'

            fingers = 'Finger Table:\n-------------\n'
            for i in range(self.m):

                fingers += f'{(node.node_id + 2 ** i) % self.ring_size} : {node.fingers_table[i].node_id}\n'

            if data != '' and data != 'Keys:\n-------------\n':
                # print(f'data_{node.node_id} [label='{data}', shape=box]')
                f.write(
                    f'data_{node.node_id} [label=\"{data}\", shape=box]\r\n')
                # print(f'{node.node_id}->data_{node.node_id}')
                f.write(f'{node.node_id}->data_{node.node_id}\r\n')

            if fingers != '':
                # print(f'fingers_{node.node_id} [label='{fingers}', shape=box]')
                f.write(
                    f'fingers_{node.node_id} [label=\"{fingers}\", shape=box]\r\n'
                )
                # print(f'{node.node_id}->fingers_{node.node_id}')
                f.write(f'{node.node_id}->fingers_{node.node_id}\r\n')

        # print('}')
        f.write('}')
        f.close()

        try:
            graph_a = pydotplus.graph_from_dot_file('graph.dot')
            graph_a.write_png('graph.png', prog='circo')
            graph_image = Image.open('graph.png')
            graph_image.show()
        except pydotplus.graphviz.InvocationException:
            pass
Пример #32
0
def draw_tree(model, features):
    import pydotplus
    from IPython.display import Image
    from sklearn import tree

    # Create DOT data
    tree.export_graphviz(
        model,
        out_file="loan_default_tree.dot",
        filled=True,
        impurity=False,
        precision=2,  #rotate  =True
        feature_names=features,
        proportion=True,
        label=None,
        rounded=True,
        class_names=['Non-Default', 'Default'])

    graph = pydotplus.graph_from_dot_file("loan_default_tree.dot")
    # Show graph
    return Image(graph.create_png())
Пример #33
0
def write_Tree(fname_outdir, clf, cols_features):
    # Translate inequalities to their HTML code
    patterns = {
        '<=': '&le;',
        '>=': '&ge;',
        '<': '&lt;',
        '>': '&gt;',
    }
    cols_features = [ reduce(lambda x, y: x.replace(y, patterns[y]), patterns, cols_feature)
                      for cols_feature in cols_features ]
    # Write rules to file
    # REMEMBER: Rules refer ONLY to the TRAINING data!
    fname_DT_rules = fname_outdir + r'/DT_rules_output.txt'
    old_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()
    get_code(clf, cols_features) # get_code() is a function from helper_functions.py
    sys.stdout = old_stdout
    # end capture
    to_text = mystdout.getvalue()
    # write file
    text_file = open(fname_DT_rules, "w")
    text_file.write(to_text)
    text_file.close()

    # Using pyplotplus and graphviz (both must be installed on the computer for this bit to work) 
    # in order to visualize the decision tree

    # ERROR!! there's some bug with deep trees (max_depth > 5)
    outfile= fname_outdir + r'/tree.dot'
    pngfile= fname_outdir + r'/tree.png'
    dot_data = StringIO()  
    tree.export_graphviz(clf, out_file=outfile,  
                         feature_names=cols_features,  
                         class_names=['Bad', 'Good'],  
                         filled=True, rounded=True,  
                         special_characters=True)  

    graph = pydotplus.graph_from_dot_file(outfile)
    graph.write_png(pngfile)
Пример #34
0
def read_graphs():
    POSTAL_FILE = 'postal.dot'

    nodes = set()
    edges = []
    starting_states = set()
    ending_states = set()

    dotfile = source(POSTAL_FILE)
    logging.info('reading file %s', dotfile)
    for g in graph_from_dot_file(dotfile):
        logging.info('started graph %s', g.get_name())
        for e in g.get_edges():
            def error(message, *args):
                full_message = message % args + ': ' + e.to_string()
                logging.error(full_message)
                raise RuntimeError(full_message)

            l = [e.get_source(), e.get_destination()]

            label = e.get_label()
            if label is not None:
                if label not in ['"+"', '"-"']:
                    error('Unknown label %s', label)
                if not l[1].startswith('T_'):
                    error('positive/negative needs T_ as destination')
                l.append(label.replace('"', ''))
            else:
                if re.match('A_|S_|T_', l[0]) is None:
                    error('receptor must start signed edge')
                l.append(label)
            # validation start
            if l[0].startswith('A_'):
                error("A_ can't be source", e)
            elif l[0].startswith('T_'):
                if not (l[1].startswith('S_') or l[1].startswith('A_')):
                    error('bad destination for T')
            elif l[0].startswith('S_'):
                if not l[1].startswith('T_'):
                    error('source S_ requires destination T_')
            else:
                if not l[1].startswith('T_'):
                    error('receptors require destination T_')
            if l[1].startswith('A_'):
                if not l[0].startswith('T_'):
                    error(' A_ as destination requires  T_ as source')
            elif l[1].startswith('S_'):
                if not l[0].startswith('T_'):
                    error('source T_ requires destination S_')
            elif l[1].startswith('T_'):
                pass
            else:
                error("receptor can't be destination")
            # validation end
            # starting node search start
            if l[0].startswith('S_'):
                starting_states.add(l[0])
            if l[1].startswith('S_'):
                ending_states.add(l[1])
            # starting node search end
            # check known receptors start
            for x in l[0:2]:
                prefix, tail = x.split('_', 1)
                if prefix in VALIDATORS:
                    validators = VALIDATORS.get(prefix)
                    if validators is None:
                        error('validator not found for %s', x)
                    arguments = tail.split('_')
                    if len(arguments) != len(validators):
                        error('bad arity for prefix %s, arguments %s, node %s',
                              prefix, arguments, x)
                    if not all(v(a) for v, a in zip(validators, arguments)):
                        error('invalid arguments  for '
                              'prefix %s, arguments %s, node %s',
                              prefix, arguments, x)
                else:
                    if prefix not in ['S', 'T']:
                        error('unknown prefix %s', prefix)
            # check known receptors end
            edges.append(l)
            nodes.update(l[0:2])
    logger.debug(edges)
    logger.debug(nodes)
    states_difference = starting_states - ending_states
    if len(states_difference) != 1:
        error('1 starting state required %s', str(states_difference))
    else:
        START_STATE = list(states_difference)[0]
    return edges, nodes, START_STATE