Generator based on Kullback-Leibler divergence For example, given users A, B with weights 5 and 1 respectively, this algorithm will yield AAABAAAAABAA.
(users: Iterable[tuple[T, float]])
| 24 | |
| 25 | |
| 26 | def _kl_generator(users: Iterable[tuple[T, float]]) -> Generator[T | None]: |
| 27 | """Generator based on Kullback-Leibler divergence |
| 28 | |
| 29 | For example, given users A, B with weights 5 and 1 respectively, |
| 30 | this algorithm will yield AAABAAAAABAA. |
| 31 | """ |
| 32 | heap = [(x * log2(x / (x + 1.0)), x + 1.0, x, name) for name, x in users if x > 0] |
| 33 | if not heap: |
| 34 | while True: |
| 35 | yield None |
| 36 | |
| 37 | heapify(heap) |
| 38 | while True: |
| 39 | _, x, weight, name = heap[0] |
| 40 | # (divergence diff, number of generated elements + initial weight, initial weight, name) = heap[0] |
| 41 | yield name |
| 42 | kl_diff = weight * log2(x / (x + 1.0)) |
| 43 | # calculate how much choosing element i for (x + 1)th time decreases divergence |
| 44 | heapreplace(heap, (kl_diff, x + 1.0, weight, name)) |
| 45 | |
| 46 | |
| 47 | class UsersDispatcher(Iterator): |
no outgoing calls
no test coverage detected
searching dependent graphs…