def sample_from_histogram(p, n_samples=1):
"""
returns the indice of bin according to the histogram p
@param p: histogram
@type p: numpy.array
@param n_samples: number of samples to generate
@type n_samples: integer
"""
from numpy import add, less, argsort, take, arange
from numpy.random import random
indices = argsort(p)
indices = take(indices, arange(len(p) - 1, -1, -1))
c = add.accumulate(take(p, indices)) / add.reduce(p)
return indices[add.reduce(less.outer(c, random(n_samples)), 0)]
评论列表
文章目录