I was listening to an introductory talk about MCMC (link). I'll have more to say about the talk another time (hint: I think it's terrific). The speaker described a method for sampling from a probability distribution. The idea is to generate random samples from U[0,1], and then find the value of x at which the

*cumulative*density function first exceeds the random number. The resulting samples of x are plotted as a histogram.

The Python script has three parts. In the first section we set up a weighted mixture of three normal distributions of different mean and sd, and plot that in red using x increments of 0.01. In the second section the same values are used to generate a discrete cdf for the same points. This is plotted in blue (after normalizing by the interval size).

Then we implement the algorithm for sampling. Binning for the histogram used the

`collections.Counter`

class that will be in Python 2.7. I don't have that, so I grabbed the class from here.You might notice that the labels on the y-axis also cover the histogram. It would be better to have two separate plots, but I'm not quite sure how to handle that yet.

[UPDATE: more here]

## 2 comments:

One small (potential) improvement to "find_first" would be to make it a binary

search, taking it from O(categories) to O(log categories).

Hi. I found this code very useful. Another improvement could be to use the numpy.where() function instead of creating an ennumerate and find the first value greater than certain value. For example, to find the values in a function that are greater than a low boundary:

---------------

t=np.arange(0,4*np.pi,pi/16)

cosineFunc=np.cos(t)

c=np.argwhere(cosineFunc>0.8)

plot(t,cosineFunc)

plot(t[c],cosineFunc[c],'ro')

---------------

Using built in function could bring a faster performance.

Post a Comment