本文整理汇总了Python中sklearn.tree.export_graphviz方法的典型用法代码示例。如果您正苦于以下问题:Python tree.export_graphviz方法的具体用法?Python tree.export_graphviz怎么用?Python tree.export_graphviz使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.tree
的用法示例。
在下文中一共展示了tree.export_graphviz方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visualize_tree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def visualize_tree(data,clf,clf_name):
features = data.columns
features = features[:-1]
class_names = list(set(data.iloc[:,-1]))
dot_data = tree.export_graphviz(clf, out_file=None, \
feature_names=features,class_names=class_names, \
filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('dtree_render_'+clf_name,view=True)
# Function to perform training with giniIndex.
示例2: test_plot_tree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def test_plot_tree(pyplot):
# mostly smoke tests
# Check correctness of export_graphviz
clf = DecisionTreeClassifier(max_depth=3,
min_samples_split=2,
criterion="gini",
random_state=2)
clf.fit(X, y)
# Test export code
feature_names = ['first feat', 'sepal_width']
nodes = plot_tree(clf, feature_names=feature_names)
assert len(nodes) == 3
assert nodes[0].get_text() == ("first feat <= 0.0\nentropy = 0.5\n"
"samples = 6\nvalue = [3, 3]")
assert nodes[1].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [3, 0]"
assert nodes[2].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [0, 3]"
示例3: createTree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def createTree(matrix,label):
kmeans = KMeans(n_clusters=moa_clusters, random_state=0).fit(matrix)
vector = map(int,kmeans.labels_)
pc_10 = int(len(querymatrix1)*0.01)
clf = tree.DecisionTreeClassifier(min_samples_split=min_sampsplit,min_samples_leaf=min_leafsplit,max_depth=max_d)
clf.fit(matrix,vector)
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,
feature_names=label,
class_names=map(str,list(set(sorted(kmeans.labels_)))),
filled=True, rounded=True,
special_characters=True,
proportion=False,
impurity=True)
out_tree = dot_data.getvalue()
out_tree = out_tree.replace('True','Inactive').replace('False','Active').replace(' ≤ 0.5', '').replace('class', 'Predicted MoA')
graph = pydot.graph_from_dot_data(str(out_tree))
try:
graph.write_jpg(output_name_tree)
except AttributeError:
graph = pydot.graph_from_dot_data(str(out_tree))[0]
graph.write_jpg(output_name_tree)
return
#initializer for the pool
示例4: show_pdf
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def show_pdf(clf):
'''
可视化输出
把决策树结构写入文件: http://sklearn.lzjqsdd.com/modules/tree.html
Mac报错: pydotplus.graphviz.InvocationException: GraphViz's executables not found
解决方案: sudo brew install graphviz
参考写入: http://www.jianshu.com/p/59b510bafb4d
'''
# with open("testResult/tree.dot", 'w') as f:
# from sklearn.externals.six import StringIO
# tree.export_graphviz(clf, out_file=f)
import pydotplus
from sklearn.externals.six import StringIO
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("../../../output/3.DecisionTree/tree.pdf")
# from IPython.display import Image
# Image(graph.create_png())
示例5: show_pdf
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def show_pdf(clf):
'''
可视化输出
把决策树结构写入文件: http://sklearn.lzjqsdd.com/modules/tree.html
Mac报错: pydotplus.graphviz.InvocationException: GraphViz's executables not found
解决方案: sudo brew install graphviz
参考写入: http://www.jianshu.com/p/59b510bafb4d
'''
# with open("testResult/tree.dot", 'w') as f:
# from sklearn.externals.six import StringIO
# tree.export_graphviz(clf, out_file=f)
import pydotplus
from sklearn.externals.six import StringIO
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("output/3.DecisionTree/tree.pdf")
# from IPython.display import Image
# Image(graph.create_png())
示例6: visualize_tree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
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
# An example using the iris dataset
示例7: visualize_tree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def visualize_tree(data,clf,clf_name):
features = data.columns
features = features[:-1]
class_names = list(set(data.iloc[:,-1]))
dot_data = tree.export_graphviz(clf, out_file=None, feature_names=features,class_names=class_names, filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
graph.render('dtree_render_'+clf_name,view=True)
# Function to perform training with giniIndex.
示例8: test_graphviz_errors
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def test_graphviz_errors():
# Check for errors of export_graphviz
clf = DecisionTreeClassifier(max_depth=3, min_samples_split=2)
# Check not-fitted decision tree error
out = StringIO()
assert_raises(NotFittedError, export_graphviz, clf, out)
clf.fit(X, y)
# Check if it errors when length of feature_names
# mismatches with number of features
message = ("Length of feature_names, "
"1 does not match number of features, 2")
assert_raise_message(ValueError, message, export_graphviz, clf, None,
feature_names=["a"])
message = ("Length of feature_names, "
"3 does not match number of features, 2")
assert_raise_message(ValueError, message, export_graphviz, clf, None,
feature_names=["a", "b", "c"])
# Check error when argument is not an estimator
message = "is not an estimator instance"
assert_raise_message(TypeError, message,
export_graphviz, clf.fit(X, y).tree_)
# Check class_names error
out = StringIO()
assert_raises(IndexError, export_graphviz, clf, out, class_names=[])
# Check precision error
out = StringIO()
assert_raises_regex(ValueError, "should be greater or equal",
export_graphviz, clf, out, precision=-1)
assert_raises_regex(ValueError, "should be an integer",
export_graphviz, clf, out, precision="1")
示例9: test_friedman_mse_in_graphviz
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def test_friedman_mse_in_graphviz():
clf = DecisionTreeRegressor(criterion="friedman_mse", random_state=0)
clf.fit(X, y)
dot_data = StringIO()
export_graphviz(clf, out_file=dot_data)
clf = GradientBoostingClassifier(n_estimators=2, random_state=0)
clf.fit(X, y)
for estimator in clf.estimators_:
export_graphviz(estimator[0], out_file=dot_data)
for finding in finditer(r"\[.*?samples.*?\]", dot_data.getvalue()):
assert_in("friedman_mse", finding.group())
示例10: createTree
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def createTree(matrix,label):
vector = [1] * len(querymatrix1) + [0] * len(querymatrix2)
ratio = float(len(vector)-sum(vector))/float(sum(vector))
sw = np.array([ratio if i == 1 else 1 for i in vector])
pc_10 = int(len(querymatrix1)*0.01)
clf = tree.DecisionTreeClassifier(min_samples_split=min_sampsplit,min_samples_leaf=min_leafsplit,max_depth=max_d)
clf.fit(matrix,vector)
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,
feature_names=label,
class_names=['File2','File1'],
filled=True, rounded=True,
special_characters=True,
proportion=False,
impurity=True)
out_tree = dot_data.getvalue()
out_tree = out_tree.replace('True','Inactive').replace('False','Active').replace(' ≤ 0.5', '')
graph = pydot.graph_from_dot_data(str(out_tree))
try:
graph.write_jpg(output_name_tree)
except AttributeError:
graph = pydot.graph_from_dot_data(str(out_tree))[0]
graph.write_jpg(output_name_tree)
return
#initializer for the pool
示例11: graphviz
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def graphviz(self):
if self.clf is None:
log("Loading model...")
self.clf = joblib.load("clf.pkl")
dot_data = tree.export_graphviz(self.clf, out_file="pigaios.dot", \
filled=True, rounded=True, \
special_characters=True)
os.system("dot -Tx11 pigaios.dot")
#-------------------------------------------------------------------------------
示例12: visualize
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def visualize(tree, save_path):
"""Generate PDF of a decision tree.
@param tree: DecisionTreeClassifier instance
@param save_path: string
where to save tree PDF
"""
dot_data = export_graphviz(tree, out_file=None,
filled=True, rounded=True)
graph = pydotplus.graph_from_dot_data(dot_data)
graph = make_graph_minimal(graph) # remove extra text
if not save_path is None:
graph.write_pdf(save_path)
示例13: test_objectmapper
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def test_objectmapper(self):
df = pdml.ModelFrame([])
self.assertIs(df.tree.DecisionTreeClassifier, tree.DecisionTreeClassifier)
self.assertIs(df.tree.DecisionTreeRegressor, tree.DecisionTreeRegressor)
self.assertIs(df.tree.ExtraTreeClassifier, tree.ExtraTreeClassifier)
self.assertIs(df.tree.ExtraTreeRegressor, tree.ExtraTreeRegressor)
self.assertIs(df.tree.export_graphviz, tree.export_graphviz)
示例14: sample_1033_1
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def sample_1033_1():
"""
10.3.3 通过决策树分类,绘制出决策图
这里需要安装dot graphviz,才能通过os.system("dot -T png graphviz.dot -o graphviz.png")生成png
:return:
"""
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
import os
estimator = DecisionTreeClassifier(max_depth=2, random_state=1)
# noinspection PyShadowingNames
def graphviz_tree(estimator, features, x, y):
if not hasattr(estimator, 'tree_'):
print('only tree can graphviz!')
return
estimator.fit(x, y)
# 将决策模型导出graphviz.dot文件
tree.export_graphviz(estimator.tree_, out_file='graphviz.dot',
feature_names=features)
# 通过dot将模型绘制决策图,保存png
os.system("dot -T png graphviz.dot -o graphviz.png")
global g_with_date_week_noise
g_with_date_week_noise = True
train_x, train_y_regress, train_y_classification, pig_three_feature, \
test_x, test_y_regress, test_y_classification, kl_another_word_feature_test = sample_1031_1()
# 这里会使用到特征的名称列pig_three_feature.columns[1:]
graphviz_tree(estimator, pig_three_feature.columns[1:], train_x,
train_y_classification)
import PIL.Image
PIL.Image.open('graphviz.png').show()
示例15: export_model
# 需要导入模块: from sklearn import tree [as 别名]
# 或者: from sklearn.tree import export_graphviz [as 别名]
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'decision_tree')
## UNDER DEVELOPMENT CODE FOR PRINTING TREES
# def get_tree(self):
# return self.alg.tree_
# Print the tree in visual format
# Inputs:
# export_pdf - if True, a pdf will be exported with the
# filename as specified in pdf_name argument
# pdf_name - name of the pdf file if export_pdf is True
# def printTree(self, export_pdf=True, file_name="Decision_Tree.pdf"):
# dot_data = StringIO()
# export_graphviz(
# self.alg, out_file=dot_data, feature_names=self.predictors,
# filled=True, rounded=True, special_characters=True)
# export_graphviz(
# self.alg, out_file='data.dot', feature_names=self.predictors,
# filled=True, rounded=True, special_characters=True
# )
# graph = pydot.graph_from_dot_data(dot_data.getvalue())
# if export_pdf:
# graph.write_pdf(file_name)
# return graph
#####################################################################
##### RANDOM FOREST
#####################################################################