mardi 26 février 2019

Vectorizing np.random.binomial for accepting a multidimensional array

I have an array, let us say a three-dimensional of size (3,3,3):

M = np.arange(27).reshape((3,3,3))

What I would like to achieve, is to apply the numpy.random.binomial function, like:

X[i,j,k] = (n=M[i,j,k], p=0.5 , size=1)

This should be easy with for loops, but for large arrays, not the best idea.

A possible solution would be:

def binom(x):
   fis = int(np.random.binomial(x,p=0.5,size=1))
   return fis

X = np.vectorize(binom)(M)

It works fine, but np.vectorizeis basically a well-disguised for equivalent, so not much of an improvement for larger arrays. I am sure that there are way cheaper and faster solutions.




Aucun commentaire:

Enregistrer un commentaire