当前位置: 首页>>代码示例>>Python>>正文


Python pydotplus.graph_from_dot_data函数代码示例

本文整理汇总了Python中pydotplus.graph_from_dot_data函数的典型用法代码示例。如果您正苦于以下问题:Python graph_from_dot_data函数的具体用法?Python graph_from_dot_data怎么用?Python graph_from_dot_data使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了graph_from_dot_data函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_attribute_with_implicit_value

    def test_attribute_with_implicit_value(self):

        d = 'digraph {\na -> b[label="hi", decorate];\n}'
        g = pydotplus.graph_from_dot_data(d)
        attrs = g.get_edges()[0].get_attributes()

        self.assertEqual('decorate' in attrs, True)
开发者ID:carlos-jenkins,项目名称:pydotplus,代码行数:7,代码来源:pydot_unittest.py

示例2: train_network

    def train_network(self):
        """ Pure virtual method for training the network
        """
        db_query = self._database_session.query(PregameHitterGameEntry)
        mlb_training_data, mlb_evaluation_data = self.get_train_eval_data(db_query, 0.8)
        X_train, Y_train = self.get_stochastic_batch(mlb_training_data, self.SIZE_TRAINING_BATCH)
        self._decision_tree.fit(X_train, Y_train)
        dot_data = StringIO()
        tree.export_graphviz(self._decision_tree, out_file=dot_data,
                             feature_names=PregameHitterGameEntry.get_input_vector_labels())
        graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
        graph.write_pdf("hitter_tree.pdf")
        x_test_actual = list()
        y_test_actual = list()
        for data in mlb_evaluation_data:
            try:
                postgame_entry = self._database_session.query(PostgameHitterGameEntry).filter(PostgameHitterGameEntry.rotowire_id == data.rotowire_id,
                                                                                              PostgameHitterGameEntry.game_date == data.game_date).one()
                y_test_actual.append([postgame_entry.actual_draftkings_points])
                x_test_actual.append(data.to_input_vector())
            except NoResultFound:
                print "Ignoring hitter %s since his postgame stats were not found." % data.rotowire_id
                continue

        self._database_session.close()
开发者ID:karlwichorek,项目名称:mlbscrape-python,代码行数:25,代码来源:train_regression.py

示例3: test_graph_with_shapefiles

    def test_graph_with_shapefiles(self):

        shapefile_dir = os.path.join(TEST_DIR, 'from-past-to-future')
        dot_file = os.path.join(shapefile_dir, 'from-past-to-future.dot')

        pngs = [
            os.path.join(shapefile_dir, fname)
            for fname in os.listdir(shapefile_dir)
            if fname.endswith('.png')
        ]

        f = open(dot_file, 'rt')
        graph_data = f.read()
        f.close()

        g = pydotplus.graph_from_dot_data(graph_data)

        g.set_shape_files(pngs)

        jpe_data = g.create(format='jpe')

        hexdigest = sha256(jpe_data).hexdigest()

        hexdigest_original = self._render_with_graphviz(dot_file)

        self.assertEqual(hexdigest, hexdigest_original)
开发者ID:carlos-jenkins,项目名称:pydotplus,代码行数:26,代码来源:pydot_unittest.py

示例4: line_dot

    def line_dot(self, code):
        """
        %dot CODE - render code as Graphviz image

        This line magic will render the Graphiz CODE, and render 
        it as an image.

        Example:
            %dot graph A { a->b };

        """
        try:
            if os.name == 'nt':
                import pydotplus as pydot
            else:
                import pydotplus as pydot
                #import pydot
        except:
            raise Exception("You need to install pydot")
        graph = pydot.graph_from_dot_data(str(code))
        svg = graph.create_svg()
        if hasattr(svg, "decode"):
            svg = svg.decode("utf-8")
        html = HTML(svg)
        self.kernel.Display(html)
开发者ID:mjbright,项目名称:metakernel,代码行数:25,代码来源:dot_magic.py

示例5: create_tree

def create_tree(X, Y):
    clf = tree.DecisionTreeClassifier(criterion="entropy")
    clf = clf.fit(X, Y)

    from IPython.display import Image
    import pydotplus

    dot_data = StringIO()
    # tree.export_graphviz(clf, out_file=dot_data)
    # feature_names = ['Gender', 'Age']
    feature_names = ["Gender", "0-5", "6-12", "13-19", "20-27", "28-35", "36-50", "55+"]
    target_names = []

    for i in range(1, len(Y) + 1):
        target_names.append("Ad #" + str(i))

    tree.export_graphviz(
        clf,
        out_file=dot_data,
        feature_names=feature_names,
        class_names=target_names,
        filled=True,
        rounded=True,
        special_characters=True,
    )

    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    graph.write_pdf("Tree.pdf")

    return clf
开发者ID:M-Anwar,项目名称:ARGEL,代码行数:30,代码来源:DecTree.py

示例6: cell_dot

    def cell_dot(self):
        """
        %%dot - render contents of cell as Graphviz image

        This cell magic will send the cell to the browser as
        HTML.

        Example:
            %%dot

            graph A { a->b };
        """
        try:
            if os.name == 'nt':
                import pydotplus as pydot
            else:
                import pydot
        except:
            raise Exception("You need to install pydot")
        graph = pydot.graph_from_dot_data(str(self.code))
        svg = graph.create_svg()
        if hasattr(svg, "decode"):
            svg = svg.decode("utf-8")
        html = HTML(svg)
        self.kernel.Display(html)
        self.evaluate = False
开发者ID:mjbright,项目名称:metakernel,代码行数:26,代码来源:dot_magic.py

示例7: run_DT_model_2

def run_DT_model_2(df, criteria_col):
    # run the tree for various 0,1 lebel (e.g. : high value or not..)
    from sklearn.metrics import confusion_matrix
    from sklearn.cross_validation import train_test_split
    from sklearn.externals.six import StringIO
    from IPython.display import Image  
    import pydotplus
    print ('criteria_col  =  ', criteria_col)
    tree_col = [criteria_col,'Frequency', 'LTV', 'period_no_use','AverageTimeToOrder',
          'late_by_collection', 'late_by_delivery', 'tickets', 'recleaned_orders',
         'cancalled_orders', 'voucher_used']
    df_train_ = df 
    #df_train_tree = df_train_[tree_col]
    tree_data = df_train_[tree_col]
    tree_data = tree_data.dropna()
    tree_train, tree_test = train_test_split(tree_data,
                                           test_size=0.2, 
                                           random_state=200,
                                           stratify=tree_data[criteria_col])
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(tree_train.iloc[:,1:], tree_train[criteria_col])
    print (clf.score(tree_test.iloc[:,1:], tree_test[criteria_col]))
    # confusion matrix 
    print (confusion_matrix(tree_test[criteria_col], clf.predict(tree_test.iloc[:,1:])))
    # visualize the tree 
    dot_data = StringIO()
    tree.export_graphviz(clf,
                       out_file=dot_data,
                       feature_names=tree_col[1:],
                       filled=True, 
                       rounded=True)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    return Image(graph.create_png()), tree_train, tree_test
开发者ID:yennanliu,项目名称:analysis,代码行数:33,代码来源:utility_ML.py

示例8: DecisionTree

    def DecisionTree(self, dados):

        database = np.array(zip(dados[:, 4], dados[:, 5], dados[:, 11], dados[:, 12], dados[:, 19], dados[:, 20],
                               dados[:, 28], dados[:, 29], dados[:, 8], dados[:, 16], dados[:, 24], dados[:, 32]))
        class_names = ('implementacao_estimado','implementacao_real','correcao_est','correcao_real','teste_est',
                 'teste_real','elaboracao_estimado', 'elaboracao_real','perfil_imple','perfil_cor','perfil_teste',
                 'perfil_elab')
        kind = []
        for dado in dados[:, 33]:
            if(float(dado) <= 1.5):
                kind.append('class1')
            elif (float(dado) <= 2.0):
                kind.append('class2')
            elif (float(dado) <= 2.5):
                kind.append('class3')
            elif (float(dado) <= 3.0):
                kind.append('class4')
            elif (float(dado) <= 3.5):
                kind.append('class5')
            elif (float(dado) <= 4.0):
                kind.append('class6')
            elif (float(dado) <= 4.5):
                kind.append('class7')
            else:
                kind.append('class8')

        target = np.array(kind)

        clf = tree.DecisionTreeClassifier()
        clf = clf.fit(database, target)

        with open("projetos.dot", 'w') as f:
            f = tree.export_graphviz(clf, out_file=f)

        os.unlink('projetos.dot')

        dot_data = tree.export_graphviz(clf, out_file=None)
        graph = pydotplus.graph_from_dot_data(dot_data)
        graph.write_pdf('projetos.pdf')

        dot_data = tree.export_graphviz(clf, out_file=None,
                                             feature_names=class_names,
                                             class_names=target,
                                             filled=True, rounded=True,
                                             special_characters=True)
        graph = pydotplus.graph_from_dot_data(dot_data)
        Image(graph.create_png())
开发者ID:anaFernandes,项目名称:EVM,代码行数:47,代码来源:K_Means.py

示例9: test_multiple_graphs

    def test_multiple_graphs(self):

        graph_data = 'graph A { a->b };\ngraph B {c->d}'

        graphs = pydotplus.graph_from_dot_data(graph_data)

        self.assertEqual(len(graphs), 2)

        self.assertEqual([g.get_name() for g in graphs], ['A', 'B'])
开发者ID:carlos-jenkins,项目名称:pydotplus,代码行数:9,代码来源:pydot_unittest.py

示例10: export_graph

 def export_graph(self, clf, labels, file_name):
     dot_data = StringIO()
     tree.export_graphviz(clf,
                          out_file=dot_data,
                          feature_names=self.__features_name,
                          class_names=labels,
                          filled=True, rounded=True,
                          impurity=False)
     graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
     graph.write_pdf('{}.pdf'.format(file_name))
开发者ID:Arki2pac,项目名称:smart-forklift,代码行数:10,代码来源:main.py

示例11: graph_decision_tree

def graph_decision_tree(model, class_names):
    
    model_dot = StringIO() 
    tree.export_graphviz(model, out_file=model_dot,
                         feature_names=features,
                         class_names=class_names,
                         filled=True, rounded=True,  
                         special_characters=True) 
    graph = pydotplus.graph_from_dot_data(model_dot.getvalue()) 
    graph.write_pdf("model"+class_names[1]+".pdf")
开发者ID:elena-sharova,项目名称:poker_hand,代码行数:10,代码来源:poker_hand.py

示例12: visualize_tree

def visualize_tree(clf, feature_names, class_names, output_file,
                   method='pdf'):
    dot_data = StringIO()
    tree.export_graphviz(clf, out_file=dot_data,
                         feature_names=iris.feature_names,
                         class_names=iris.target_names,
                         filled=True, rounded=True,
                         special_characters=True,
                         impurity=False)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    if method == 'pdf':
        graph.write_pdf(output_file + ".pdf")
    elif method == 'inline':
        Image(graph.create_png())

    return graph
开发者ID:yassineAlouini,项目名称:kaggle-tools,代码行数:16,代码来源:visualize_tree.py

示例13: train_tree_classifer

def train_tree_classifer(features, labels, model_output_path):
    """
    train_tree_classifer will train a DecisionTree and write it out to a pdf file

    features: 2D array of each input feature for each sample
    labels: array of string labels classifying each sample
    model_output_path: path for storing the trained tree model
    """
    # save 20% of data for performance evaluation
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(features, labels, test_size=0.2)

    param = [
        {
            "max_depth": [None, 10, 100, 1000, 10000]
        }
    ]

    dtree = tree.DecisionTreeClassifier(random_state=0)

    # 10-fold cross validation, use 4 thread as each fold and each parameter set can be train in parallel
    clf = grid_search.GridSearchCV(dtree, param,
            cv=10, n_jobs=20, verbose=3)

    clf.fit(X_train, y_train)

    if os.path.exists(model_output_path):
        joblib.dump(clf.best_estimator_, model_output_path)
    else:
        print("Cannot save trained tree model to {0}.".format(model_output_path))

    dot_data = tree.export_graphviz(clf.best_estimator_, out_file=None)
    graph = pydotplus.graph_from_dot_data(dot_data)
    graph.write_pdf('best_tree.pdf')

    print("\nBest parameters set:")
    print(clf.best_params_)

    y_predict=clf.predict(X_test)

    labels=sorted(list(set(labels)))
    print("\nConfusion matrix:")
    print("Labels: {0}\n".format(",".join(labels)))
    print(confusion_matrix(y_test, y_predict, labels=labels))

    print("\nClassification report:")
    print(classification_report(y_test, y_predict))
开发者ID:mwleeds,项目名称:android-malware-analysis,代码行数:46,代码来源:sklearn_tree.py

示例14: train

    def train(self, training_set, training_target, fea_index):

        clf = tree.DecisionTreeClassifier(criterion="entropy", min_samples_split=30, class_weight="balanced")
        clf = clf.fit(training_set, training_target)

        class_names = np.unique([str(i) for i in training_target])
        feature_names = [attr_list[i] for i in fea_index]

        dot_data = tree.export_graphviz(clf, out_file=None,
                                        feature_names=feature_names,
                                        class_names=class_names,
                                        filled=True, rounded=True,
                                        special_characters=True)

        graph = pydotplus.graph_from_dot_data(dot_data)
        graph.write_pdf("output/tree-vis.pdf")
        joblib.dump(clf, 'output/CART.pkl')
开发者ID:StevenLOL,项目名称:kdd99-scikit,代码行数:17,代码来源:CART_Trainer.py

示例15: render_output_pydot

    def render_output_pydot(self, dotdata, **kwargs):
        """Renders the image using pydot"""
        if not HAS_PYDOT:
            raise CommandError("You need to install pydot python module")

        graph = pydot.graph_from_dot_data(dotdata)
        if not graph:
            raise CommandError("pydot returned an error")
        output_file = kwargs['outputfile']
        formats = ['bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf',
                   'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap',
                   'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf',
                   'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg',
                   'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot']
        ext = output_file[output_file.rfind('.') + 1:]
        format = ext if ext in formats else 'raw'
        graph.write(output_file, format=format)
开发者ID:ConsumerAffairs,项目名称:django-extensions,代码行数:17,代码来源:graph_models.py


注:本文中的pydotplus.graph_from_dot_data函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。