Numpy generating array from repeated function

Question:

I’m trying to generate an numpy array with randomly generated elements (it’s similar like bernouilli distribution. The thing is I want to achieve it without using numpy.random.binomial function). Only function that fits after searching documentation and some forums is numpy.fromfunction. But I encountered a problem that this function doesn’t generate n elements, but one.

I expect output something like:

[0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1]

This function generates 1 element only, no matter what shape is in tuple:

np.fromfunction(lambda i : np.random.choice([0, 1], p=[0.1, 0.9]), (20, ))

#returns 1 or 0

np.fromfunction(lambda i ,j : np.random.choice([0, 1], p=[0.1, 0.9]), (20, 1))

#still returns 1 or 0

Though I tried implementing "i" into the output stupidest way possible but.. it changed something, but still didn’t help:

np.fromfunction(lambda i : i*0 + np.random.choice([0, 1], p=[0.1, 0.9]), (20, ))

#returns

array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

It’s closer to the shape I want, but this ones or zeros are just repeated on all the array, so nothing’s changed really.

To sum up: I have a function f() that generates randomly with some probability 0 and 1, and is there any other function in numpy that can repeat function f() on array, or maybe some way to repair the example above?

Asked By: newone

||

Answers:

Sure, np.random.choice([0, 1], p=[0.1, 0.9], size=(20,)) or also there is np.random.randint(low=0, high=2, size=(20,)).

Answered By: HansQ

As @paime said in the comments, np.fromfunction is called once with the argument passed to it being an array. You can just use np.random.choice and specify size in it

In [1]: np.random.choice([0, 1], p=[0.1, 0.9], size=(20,))
Out[1]: array([1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1])
Answered By: zaki98