Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
###### Visualizing a Single Decision Tree #########
# Import tools needed for visualization
from sklearn.tree import export_graphviz
import pydot
# Pull out one tree from the forest
tree = rf.estimators_[5]
# Import tools needed for visualization
from sklearn.tree import export_graphviz
# Pull out one tree from the forest
tree = rf.estimators_[5]
# Export the image to a dot file
export_graphviz(tree, out_file='tree.dot', feature_names=feature_list, rounded=True, precision=1)
# Use dot file to create a graph
(graph,) = pydot.graph_from_dot_file('tree.dot')
# Write graph to a png file
graph.write_png('tree.png')
# Limit depth of tree to 3 levels
rf_small = RandomForestRegressor(n_estimators=10, max_depth=3)
rf_small.fit(train_features, train_labels)
# Extract the small tree
tree_small = rf_small.estimators_[5]
# Save the tree as a png image
export_graphviz(tree_small, out_file='small_tree.dot', feature_names=feature_list, rounded=True, precision=1)
(graph,) = pydot.graph_from_dot_file('small_tree.dot')
graph.write_png('small_tree.png')
######## Variable Importances ############
# Export the image to a dot file
export_graphviz(tree, out_file='tree.dot', feature_names=feature_list, rounded=True, precision=1)
# Use dot file to create a graph
(graph,) = pydot.graph_from_dot_file('tree.dot')
# Write graph to a png file
graph.write_png('tree.png')
# Limit depth of tree to 3 levels
rf_small = RandomForestRegressor(n_estimators=10, max_depth=3)
rf_small.fit(train_features, train_labels)
# Extract the small tree
tree_small = rf_small.estimators_[5]
# Save the tree as a png image
export_graphviz(tree_small, out_file='small_tree.dot', feature_names=feature_list, rounded=True, precision=1)
(graph,) = pydot.graph_from_dot_file('small_tree.dot')
graph.write_png('small_tree.png')
######## Variable Importances ############
# Get numerical feature importances
importances = list(rf.feature_importances_)
# List of tuples with variable and importance
feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]
# Sort the feature importances by most important first
feature_importances = sorted(feature_importances, key=lambda x: x[1], reverse=True)
# Print out the feature and importances
[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances]
######## Visualizations ################
import matplotlib.pyplot as plt
# Set the style
def main(args=None):
parser = argparse.ArgumentParser(description='Attack Tree to CAIRIS Model converter')
parser.add_argument('dotFile',help='attack tree model to import (Dot format)')
parser.add_argument('--context',dest='contextName',help='attack context')
parser.add_argument('--author',dest='originatorName',help='author/s')
parser.add_argument('--out',dest='outFile',help='output file (CAIRIS format)')
args = parser.parse_args()
dotInstance = pydot.graph_from_dot_file(args.dotFile)
xmlBuf = dotToObstacleModel(dotInstance[0],args.contextName,args.originatorName)
f = open(args.outFile,'w')
f.write(xmlBuf)
f.close()
def OnPopupItemGraph(self, event):
for row in self.ReportGrid.GetSelectedRows():
label = self.ReportGrid.GetCellValue(row,0)
id = self.ReportGrid.GetCellValue(row,1)
### plot the graph
### TODO link with properties frame
for fct in ('extTransition','intTransition', 'outputFnc', 'timeAdvance'):
filename = "%s(%s)_%s.dot"%(label,str(id),fct)
path = os.path.join(tempfile.gettempdir(), filename)
### if path exist
if os.path.exists(path):
graph = pydot.graph_from_dot_file(path)
filename_png = os.path.join(tempfile.gettempdir(),"%s(%s)_%s.png"%(label,str(id),fct))
graph.write_png(filename_png, prog='dot')
pylab.figure()
img = pylab.imread(filename_png)
pylab.imshow(img)
fig = pylab.gcf()
fig.canvas.set_window_title(filename)
pylab.axis('off')
pylab.show()
def loadWorkflowFromDotFile( dotfile, workflowcls = None ):
"""Create a graph from the given dotfile and create a workflow from it.
The workflow will be fully intiialized with connected process instances.
The all compatible plugs will automatically be connected for all processes
connected in the dot file
:param workflowcls: if not None, a dgengine.Graph compatible class to be used
for workflow creation. Defaults to automation.workflow.Workflow.
:return: List of initialized workflow classes - as they can be nested, the
creation of one workflow can actually create several of them"""
import pydot
import processes
from workflow import Workflow
wflclass = workflowcls or Workflow
dotgraph = pydot.graph_from_dot_file( dotfile )
if not dotgraph:
raise AssertionError( "Returned graph from file %r was None" % dotfile )
# use the filename as name
edge_lut = {} # string -> processinst
wfl = wflclass( name=dotfile.namebase() )
for node in dotgraph.get_node_list():
# can have initializers
nodeid = node.get_name().strip( '"' )
# ignore default node
if nodeid == "node":
continue
y = radius*math.sin(angle)
file.write(" %d[pos=\"%f,%f!\",shape=circle];\n"%(i-1, x, y))
for i in range(len(connections)):
for j in connections[i]:
if j not in messages[i]: file.write("%d->%d\n"%(i, j))
for j in messages[i]:
file.write("%d->%d[color=\"red\"];\n"%(i, j))
file.write("labelloc=\"t\";\n")
file.write("label=\"%s\";\n"%label)
file.write("}\n")
file.close()
(graph,) = pydot.graph_from_dot_file("%s.dot"%filename)
graph.write_png('%s.png'%filename)
# Create dot file by using extra/gprof2dot/gprof2dot.py
# http://code.google.com/p/jrfonseca/wiki/Gprof2Dot
dotFilePointer = codecs.open(dotOutputFile, 'wt', UNICODE_ENCODING)
parser = gprof2dot.PstatsParser(profileOutputFile)
profile = parser.parse()
profile.prune(0.5 / 100.0, 0.1 / 100.0)
dot = gprof2dot.DotWriter(dotFilePointer)
dot.graph(profile, gprof2dot.TEMPERATURE_COLORMAP)
dotFilePointer.close()
infoMsg = "converting dot file into a graph image '%s'" % imageOutputFile
logger.info(infoMsg)
# Create graph image (png) by using pydot (python-pydot)
# http://code.google.com/p/pydot/
pydotGraph = pydot.graph_from_dot_file(dotOutputFile)
# Reference: http://stackoverflow.com/questions/38176472/graph-write-pdfiris-pdf-attributeerror-list-object-has-no-attribute-writ
if isinstance(pydotGraph, list):
pydotGraph = pydotGraph[0]
try:
pydotGraph.write_png(imageOutputFile)
except OSError:
errMsg = "profiling requires graphviz installed "
errMsg += "(Hint: 'sudo apt install graphviz')"
logger.error(errMsg)
else:
infoMsg = "displaying interactive graph with xdot library"
logger.info(infoMsg)
# Display interactive Graphviz dot file by using extra/xdot/xdot.py
def gen_graph_from_gv(ifile, odir, oformat="png"):
(graph,) = pydot.graph_from_dot_file(ifile)
gen_graph_func = getattr(graph, "write_" + oformat)
filename = os.path.basename(ifile)
ofile = odir + "/" + os.path.splitext(filename)[0] + "." + oformat
gen_graph_func(ofile)
def read_dot(filename):
""" Read a graphviz dot file using pydot
Parameters
----------
filename: str
A DOT (graphviz) filename
Returns
-------
MultiGraph
A networkx MultiGraph file
"""
try:
import pydot
pydot_graph = pydot.graph_from_dot_file(filename)[0]
return _from_pydot(pydot_graph)
except ImportError:
raise ImportError('Importing graphviz files requires the pydot '
'library')
# Create dot file by using extra/gprof2dot/gprof2dot.py
# http://code.google.com/p/jrfonseca/wiki/Gprof2Dot
dotFilePointer = codecs.open(dotOutputFile, 'wt', UNICODE_ENCODING)
parser = gprof2dot.PstatsParser(profileOutputFile)
profile = parser.parse()
profile.prune(0.5 / 100.0, 0.1 / 100.0)
dot = gprof2dot.DotWriter(dotFilePointer)
dot.graph(profile, gprof2dot.TEMPERATURE_COLORMAP)
dotFilePointer.close()
infoMsg = "converting dot file into a graph image '%s'" % imageOutputFile
logger.info(infoMsg)
# Create graph image (png) by using pydot (python-pydot)
# http://code.google.com/p/pydot/
pydotGraph = pydot.graph_from_dot_file(dotOutputFile)
pydotGraph.write_png(imageOutputFile)
infoMsg = "displaying interactive graph with xdot library"
logger.info(infoMsg)
# Display interactive Graphviz dot file by using extra/xdot/xdot.py
# http://code.google.com/p/jrfonseca/wiki/XDot
win = xdot.DotWindow()
win.connect('destroy', gtk.main_quit)
win.set_filter("dot")
win.open_file(dotOutputFile)
gobject.timeout_add(1000, win.update, dotOutputFile)
gtk.main()