MCPcopy Create free account
hub / github.com/CyberPoint/libpgm / randomsample

Method randomsample

libpgm/hybayesiannetwork.py:75–152  ·  view source on GitHub ↗

Produce *n* random samples from the Bayesian networki, subject to *evidence*, and return them in a list. This function requires the *nodes* attribute to be instantiated. This function takes the following arguments: 1. *n* -- The number of random samples to prod

(self, n, evidence=None)

Source from the content-addressed store, hash-verified

73 assert sorted(self.V) == sorted(self.Vdata.keys()), "Node data did not match graph skeleton nodes."
74
75 def randomsample(self, n, evidence=None):
76 '''
77 Produce *n* random samples from the Bayesian networki, subject to *evidence*, and return them in a list. This function requires the *nodes* attribute to be instantiated.
78
79 This function takes the following arguments:
80
81 1. *n* -- The number of random samples to produce.
82 2. *evidence* -- (Optional) A dict containing (vertex: value) pairs that describe the evidence. To be used carefully because it does manually overrides the nodes with evidence instead of affecting the joint probability distribution of the entire graph.
83
84 And returns:
85 A list of *n* independent random samples, each element of which is a dict containing (vertex: value) pairs.
86
87 Usage example: this would generate a sequence of 10 random samples::
88
89 import json
90
91 from libpgm.nodedata import NodeData
92 from libpgm.graphskeleton import GraphSkeleton
93 from libpgm.hybayesiannetwork import HyBayesianNetwork
94
95 # load nodedata and graphskeleton
96 nd = NodeData()
97 skel = GraphSkeleton()
98 nd.load("../tests/unittesthdict.txt") # an input file
99 skel.load("../tests/unittestdict.txt")
100
101 # topologically order graphskeleton
102 skel.toporder()
103
104 # convert nodes to class instances
105 nd.entriestoinstances()
106
107 # load bayesian network
108 hybn = HyBayesianNetwork(skel, nd)
109
110 # sample
111 result = hybn.randomsample(10)
112
113 # output
114 print json.dumps(result, indent=2)
115
116
117
118 '''
119 assert (isinstance(n, int) and n > 0), "Argument must be a positive integer."
120
121 random.seed()
122 seq = []
123 for _ in range(n):
124 outcome = dict()
125 for vertex in self.V:
126 outcome[vertex] = "default"
127
128 def assignnode(name, node):
129
130 # check if node is already observed
131 if (evidence != None):
132 if name in evidence.keys():

Callers 9

gibbssampleMethod · 0.45
test_randomsampleMethod · 0.45
test_randomsampleMethod · 0.45
setUpMethod · 0.45
test_randomsampleMethod · 0.45
test_randomsampleMethod · 0.45
setUpMethod · 0.45
examples.pyFile · 0.45

Calls

no outgoing calls

Tested by 7

test_randomsampleMethod · 0.36
test_randomsampleMethod · 0.36
setUpMethod · 0.36
test_randomsampleMethod · 0.36
test_randomsampleMethod · 0.36
setUpMethod · 0.36