Created
August 28, 2015 23:43
-
-
Save pierrelux/d2e725c3dca92d0487d7 to your computer and use it in GitHub Desktop.
Inverse transform sampling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InverseTransform: | |
def __init__(self, probs, rng=None): | |
if np.sum(probs) < 1.: | |
raise ValueError('Must sum up to 1') | |
self.rng = rng | |
if rng is None: | |
self.rng = np.random.RandomState() | |
self.cdf = np.cumsum(probs) | |
def __call__(self, size=None): | |
return np.argmax(np.greater(self.cdf, self.rng.rand(size)[:, np.newaxis]), axis=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should use searchsorted rather than argmax in line 12! It works because cdfs are sorted. That will give you a runtime of
size * log |probs|
rather thansize * |probs|
!