Sampling Data¶
Sampling data from a BBN is possible. The algorithm uses logic sampling with rejection
[Hen88].
Simple Sampling¶
This code demonstrates simple sampling.
1from pybbn.graph.dag import Bbn
2from pybbn.graph.edge import Edge, EdgeType
3from pybbn.graph.node import BbnNode
4from pybbn.graph.variable import Variable
5from pybbn.sampling.sampling import LogicSampler
6
7a = BbnNode(Variable(0, 'a', ['on', 'off']), [0.5, 0.5])
8b = BbnNode(Variable(1, 'b', ['on', 'off']), [0.5, 0.5, 0.4, 0.6])
9c = BbnNode(Variable(2, 'c', ['on', 'off']), [0.7, 0.3, 0.2, 0.8])
10
11bbn = Bbn() \
12 .add_node(a) \
13 .add_node(b) \
14 .add_node(c) \
15 .add_edge(Edge(a, b, EdgeType.DIRECTED)) \
16 .add_edge(Edge(b, c, EdgeType.DIRECTED))
17
18sampler = LogicSampler(bbn)
19samples = sampler.get_samples(n_samples=10000, seed=37)
Sampling with Rejection¶
This code demonstrates sampling with evidence asserted. During each round of sampling, if the sample value generated does not match with the evidence, the entire sample is discarded.
1from pybbn.graph.dag import Bbn
2from pybbn.graph.edge import Edge, EdgeType
3from pybbn.graph.node import BbnNode
4from pybbn.graph.variable import Variable
5from pybbn.sampling.sampling import LogicSampler
6
7a = BbnNode(Variable(0, 'a', ['on', 'off']), [0.5, 0.5])
8b = BbnNode(Variable(1, 'b', ['on', 'off']), [0.5, 0.5, 0.4, 0.6])
9c = BbnNode(Variable(2, 'c', ['on', 'off']), [0.7, 0.3, 0.2, 0.8])
10
11bbn = Bbn() \
12 .add_node(a) \
13 .add_node(b) \
14 .add_node(c) \
15 .add_edge(Edge(a, b, EdgeType.DIRECTED)) \
16 .add_edge(Edge(b, c, EdgeType.DIRECTED))
17
18sampler = LogicSampler(bbn)
19samples = sampler.get_samples(evidence={0: 'on'}, n_samples=10000, seed=37)