|
| 1 | +import collections |
| 2 | + |
1 | 3 | import numpy as np
|
2 | 4 |
|
3 | 5 | __all__ = [
|
4 | 6 | 'Callback',
|
5 |
| - 'CheckParametersConvergence' |
| 7 | + 'CheckParametersConvergence', |
| 8 | + 'Tracker' |
6 | 9 | ]
|
7 | 10 |
|
8 | 11 |
|
@@ -76,3 +79,65 @@ def __call__(self, approx, _, i):
|
76 | 79 | @staticmethod
|
77 | 80 | def flatten_shared(shared_list):
|
78 | 81 | return np.concatenate([sh.get_value().flatten() for sh in shared_list])
|
| 82 | + |
| 83 | + |
| 84 | +class Tracker(Callback): |
| 85 | + """ |
| 86 | + Helper class to record arbitrary stats during VI |
| 87 | +
|
| 88 | + It is possible to pass a function that takes no arguments |
| 89 | + If call fails then (approx, hist, i) are passed |
| 90 | +
|
| 91 | +
|
| 92 | + Parameters |
| 93 | + ---------- |
| 94 | + kwargs : key word arguments |
| 95 | + keys mapping statname to callable that records the stat |
| 96 | +
|
| 97 | + Examples |
| 98 | + -------- |
| 99 | + Consider we want time on each iteration |
| 100 | + >>> import time |
| 101 | + >>> tracker = Tracker(time=time.time) |
| 102 | + >>> with model: |
| 103 | + ... approx = pm.fit(callbacks=[tracker]) |
| 104 | + |
| 105 | + Time can be accessed via :code:`tracker['time']` now |
| 106 | + For more complex summary one can use callable that takes |
| 107 | + (approx, hist, i) as arguments |
| 108 | + >>> with model: |
| 109 | + ... my_callable = lambda ap, h, i: h[-1] |
| 110 | + ... tracker = Tracker(some_stat=my_callable) |
| 111 | + ... approx = pm.fit(callbacks=[tracker]) |
| 112 | + |
| 113 | + Multiple stats are valid too |
| 114 | + >>> with model: |
| 115 | + ... tracker = Tracker(some_stat=my_callable, time=time.time) |
| 116 | + ... approx = pm.fit(callbacks=[tracker]) |
| 117 | + """ |
| 118 | + def __init__(self, **kwargs): |
| 119 | + self.whatchdict = kwargs |
| 120 | + self.hist = collections.defaultdict(list) |
| 121 | + |
| 122 | + def record(self, approx, hist, i): |
| 123 | + for key, fn in self.whatchdict.items(): |
| 124 | + try: |
| 125 | + res = fn() |
| 126 | + # if `*t` argument is used |
| 127 | + # fail will be somehow detected. |
| 128 | + # We want both calls to be tried. |
| 129 | + # Upper one has more priority as |
| 130 | + # arbitrary functions can have some |
| 131 | + # defaults in positionals. Bad idea |
| 132 | + # to try fn(approx, hist, i) first |
| 133 | + except Exception: |
| 134 | + res = fn(approx, hist, i) |
| 135 | + self.hist[key].append(res) |
| 136 | + |
| 137 | + def clear(self): |
| 138 | + self.hist = collections.defaultdict(list) |
| 139 | + |
| 140 | + def __getitem__(self, item): |
| 141 | + return self.hist[item] |
| 142 | + |
| 143 | + __call__ = record |
0 commit comments