Generate a sequence of samples using *samplerstatement* and return the average of its results. Arguments: 1. *samplerstatement* -- The statement of a function (with inputs) that would output a sequence of samples. For example: ``bn.randomsample(50)`` where ``bn
(self, samplerstatement)
| 41 | |
| 42 | |
| 43 | def aggregate(self, samplerstatement): |
| 44 | ''' |
| 45 | Generate a sequence of samples using *samplerstatement* and return the average of its results. |
| 46 | |
| 47 | Arguments: |
| 48 | 1. *samplerstatement* -- The statement of a function (with inputs) that would output a sequence of samples. For example: ``bn.randomsample(50)`` where ``bn`` is an instance of the :doc:`DiscreteBayesianNetwork <discretebayesiannetwork>` class. |
| 49 | |
| 50 | This function stores the output of *samplerstatement* in the attribute *seq*, and then averages *seq* and stores the approximate distribution found in the attribute *avg*. It then returns *avg*. |
| 51 | |
| 52 | Usage example: this would print the average of 10 data points:: |
| 53 | |
| 54 | import json |
| 55 | |
| 56 | from libpgm.nodedata import NodeData |
| 57 | from libpgm.graphskeleton import GraphSkeleton |
| 58 | from libpgm.discretebayesiannetwork import DiscreteBayesianNetwork |
| 59 | from libpgm.sampleaggregator import SampleAggregator |
| 60 | |
| 61 | # load nodedata and graphskeleton |
| 62 | nd = NodeData() |
| 63 | skel = GraphSkeleton() |
| 64 | nd.load("../tests/unittestdict.txt") |
| 65 | skel.load("../tests/unittestdict.txt") |
| 66 | |
| 67 | # topologically order graphskeleton |
| 68 | skel.toporder() |
| 69 | |
| 70 | # load bayesian network |
| 71 | bn = DiscreteBayesianNetwork(skel, nd) |
| 72 | |
| 73 | # build aggregator |
| 74 | agg = SampleAggregator() |
| 75 | |
| 76 | # average samples |
| 77 | result = agg.aggregate(bn.randomsample(10)) |
| 78 | |
| 79 | # output |
| 80 | print json.dumps(result, indent=2) |
| 81 | |
| 82 | ''' |
| 83 | |
| 84 | # get sequence |
| 85 | seq = samplerstatement |
| 86 | |
| 87 | # denominator |
| 88 | denom = len(seq) |
| 89 | |
| 90 | output = dict() |
| 91 | for key in seq[0].keys(): |
| 92 | output[key] = dict() |
| 93 | for trial in seq: |
| 94 | keyss = output[key].keys() |
| 95 | vall = trial[key] |
| 96 | if (keyss.count(vall) > 0): |
| 97 | output[key][trial[key]] += 1 |
| 98 | else: |
| 99 | output[key][trial[key]] = 1 |
| 100 |
no outgoing calls