Produce *n* random samples from the Bayesian network, subject to *evidence*, and return them in a list. This function takes the following arguments: 1. *n* -- The number of random samples to produce. 2. *evidence* -- (Optional) A dict containin
(self, n, evidence=None)
| 138 | return fn.specificquery(query, evidence) |
| 139 | |
| 140 | def randomsample(self, n, evidence=None): |
| 141 | ''' |
| 142 | Produce *n* random samples from the Bayesian network, subject to *evidence*, and return them in a list. |
| 143 | |
| 144 | This function takes the following arguments: |
| 145 | |
| 146 | 1. *n* -- The number of random samples to produce. |
| 147 | 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. |
| 148 | |
| 149 | And returns: |
| 150 | A list of *n* independent random samples, each element of which is a dict containing (vertex: value) pairs. |
| 151 | |
| 152 | Usage example: this would generate a sequence of 10 random samples:: |
| 153 | |
| 154 | import json |
| 155 | |
| 156 | from libpgm.nodedata import NodeData |
| 157 | from libpgm.graphskeleton import GraphSkeleton |
| 158 | from libpgm.discretebayesiannetwork import DiscreteBayesianNetwork |
| 159 | |
| 160 | # load nodedata and graphskeleton |
| 161 | nd = NodeData() |
| 162 | skel = GraphSkeleton() |
| 163 | nd.load("../tests/unittestdict.txt") # any input file |
| 164 | skel.load("../tests/unittestdict.txt") |
| 165 | |
| 166 | # topologically order graphskeleton |
| 167 | skel.toporder() |
| 168 | |
| 169 | # load bayesian network |
| 170 | bn = DiscreteBayesianNetwork(skel, nd) |
| 171 | |
| 172 | # sample |
| 173 | result = bn.randomsample(10) |
| 174 | |
| 175 | # output |
| 176 | print json.dumps(result, indent=2) |
| 177 | |
| 178 | |
| 179 | ''' |
| 180 | assert (isinstance(n, int) and n > 0), "Argument must be a positive integer." |
| 181 | |
| 182 | random.seed() |
| 183 | seq = [] |
| 184 | for _ in range(n): |
| 185 | outcome = dict() |
| 186 | for vertex in self.V: |
| 187 | outcome[vertex] = "default" |
| 188 | |
| 189 | def assignnode(s): |
| 190 | |
| 191 | if (evidence != None): |
| 192 | if s in evidence.keys(): |
| 193 | return evidence[s] |
| 194 | |
| 195 | # find entry in dictionary and store |
| 196 | Vdataentry = self.Vdata[s] |
| 197 |