jeudi 24 août 2017

Weighted Random Sampling from 2d numpy array

I have a 2d numpy array Z and I want to randomly choose an index of Z where the chance of an index being chosen is proportional to the value of Z at that index.

Right now, I'm doing the following:

yar = list(np.ndenumerate(Z))
x,y = yar[np.random.choice(len(yar), p=Z.ravel()/Z.sum())][0]

Which does the job but feels hideous (and is extremely slow besides). Is there a better way?




Aucun commentaire:

Enregistrer un commentaire