Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 1.43 KB

serialization.rst

File metadata and controls

42 lines (32 loc) · 1.43 KB

Serialization

All the relevant objects (graphs, factors, Bayesian networks, etc) can be saved/loaded using the pickle format.

These objects can be saved using directly pickle.dump and pickle.load. For example:

>>> import pickle >>> from pybnesian.graph import Dag >>> g = Dag(["a", "b", "c", "d"], [("a", "b")]) >>> with open("saved_graph.pickle", "wb") as f: ... pickle.dump(g, f) >>> with open("saved_graph.pickle", "rb") as f: ... lg = pickle.load(f) >>> assert lg.nodes() == ["a", "b", "c", "d"] >>> assert lg.arcs() == [("a", "b")]

import os os.remove('saved_graph.pickle')

We can reduce some boilerplate code using the save methods: Factor.save() <pybnesian.factors.Factor.save>, UndirectedGraph.save() <pybnesian.graph.UndirectedGraph.save>, DirectedGraph.save() <pybnesian.graph.DirectedGraph.save>, BayesianNetworkBase.save() <pybnesian.factors.BayesianNetworkBase.save>, etc... Also, the pybnesian.load can load any saved object:

>>> import pickle >>> from pybnesian import load >>> from pybnesian.graph import Dag >>> g = Dag(["a", "b", "c", "d"], [("a", "b")]) >>> g.save("saved_graph") >>> lg = load("saved_graph.pickle") >>> assert lg.nodes() == ["a", "b", "c", "d"] >>> assert lg.arcs() == [("a", "b")]

pybnesian.load