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 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")]

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

>>> import pickle
>>> from pybnesian import load, 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(filename: str) object

Load the saved object (a Factor, a graph, a BayesianNetworkBase, etc…) in filename.

Parameters

filename – File name.

Returns

The object saved in the file.