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

Method gibbssample

libpgm/tablecpdfactorization.py:310–435  ·  view source on GitHub ↗

Return a sequence of *n* samples using the Gibbs sampling method, given evidence specified by *evidence*. Gibbs sampling is a technique wherein for each sample, each variable in turn is erased and calculated conditioned on the outcomes of its neighbors. This method starts by sampling from t

(self, evidence, n)

Source from the content-addressed store, hash-verified

308 return fanswer
309
310 def gibbssample(self, evidence, n):
311 '''
312 Return a sequence of *n* samples using the Gibbs sampling method, given evidence specified by *evidence*. Gibbs sampling is a technique wherein for each sample, each variable in turn is erased and calculated conditioned on the outcomes of its neighbors. This method starts by sampling from the 'prior distribution,' which is the distribution not conditioned on evidence, but the samples provably get closer and closer to the posterior distribution, which is the distribution conditioned on the evidence. It is thus a good way to deal with evidence when generating random samples.
313
314 Arguments:
315 1. *evidence* -- A dict containing (key: value) pairs reflecting (variable: value) that represents what is known about the system.
316 2. *n* -- The number of samples to return.
317
318 Returns:
319
320 A list of *n* random samples, each element of which is a dict containing (vertex: value) pairs.
321
322 For more information, cf. Koller et al. Ch. 12.3.1
323
324 Usage example: This code would generate a sequence of 10 samples::
325
326 import json
327
328 from libpgm.graphskeleton import GraphSkeleton
329 from libpgm.nodedata import NodeData
330 from libpgm.discretebayesiannetwork import DiscreteBayesianNetwork
331 from libpgm.tablecpdfactorization import TableCPDFactorization
332
333 # load nodedata and graphskeleton
334 nd = NodeData()
335 skel = GraphSkeleton()
336 nd.load("../tests/unittestdict.txt")
337 skel.load("../tests/unittestdict.txt")
338
339 # toporder graph skeleton
340 skel.toporder()
341
342 # load evidence
343 evidence = dict(Letter='weak')
344
345 # load bayesian network
346 bn = DiscreteBayesianNetwork(skel, nd)
347
348 # load factorization
349 fn = TableCPDFactorization(bn)
350
351 # sample
352 result = fn.gibbssample(evidence, 10)
353
354 # output
355 print json.dumps(result, indent=2)
356
357 '''
358 self.refresh()
359 random.seed()
360
361 # declare result array
362 seq = []
363
364 # create initial instantiation
365 initial = self.bn.randomsample(1)
366 for key in evidence.keys():
367 initial[0][key] = evidence[key]

Callers 3

test_gibbssampleMethod · 0.80
setUpMethod · 0.80
examples.pyFile · 0.80

Calls 3

refreshMethod · 0.95
reducefactorMethod · 0.80
randomsampleMethod · 0.45

Tested by 2

test_gibbssampleMethod · 0.64
setUpMethod · 0.64