Generate random draws from the `probs` distribution over integers in [0, N). Parameters ---------- n_samples: int The number of samples to generate. Default is 1. Returns ------- sample : :py:class:`ndarray <numpy.ndarray
(self, n_samples=1)
| 439 | return self.sample(n_samples) |
| 440 | |
| 441 | def sample(self, n_samples=1): |
| 442 | """ |
| 443 | Generate random draws from the `probs` distribution over integers in |
| 444 | [0, N). |
| 445 | |
| 446 | Parameters |
| 447 | ---------- |
| 448 | n_samples: int |
| 449 | The number of samples to generate. Default is 1. |
| 450 | |
| 451 | Returns |
| 452 | ------- |
| 453 | sample : :py:class:`ndarray <numpy.ndarray>` of shape `(n_samples,)` |
| 454 | A collection of draws from the distribution defined by `probs`. |
| 455 | Each sample is an int in the range `[0, N)`. |
| 456 | """ |
| 457 | ixs = np.random.randint(0, self.N, n_samples) |
| 458 | p = np.exp(self.prob_table[ixs]) if self.log else self.prob_table[ixs] |
| 459 | flips = np.random.binomial(1, p) |
| 460 | samples = [ix if f else self.alias_table[ix] for ix, f in zip(ixs, flips)] |
| 461 | |
| 462 | # do recursive rejection sampling to sample without replacement |
| 463 | if not self.with_replacement: |
| 464 | unique = list(set(samples)) |
| 465 | while len(samples) != len(unique): |
| 466 | n_new = len(samples) - len(unique) |
| 467 | samples = unique + self.sample(n_new).tolist() |
| 468 | unique = list(set(samples)) |
| 469 | |
| 470 | return np.array(samples, dtype=int) |
| 471 | |
| 472 | |
| 473 | ####################################################################### |