Gilfoyle
Gilfoyle

Reputation: 3616

Python Pre-Define Function

In my code I use the following structure to avoid conditions in a for loop:

if patch_type == "zeros":
    patch_fct = np.zeros
elif patch_type == "ones":
    patch_fct = np.ones
elif patch_type == "rand":
    patch_fct = np.random.random_sample
else:
    raise "Error"

for k in range(10**9):
    m, n = comp_size()
    bla = patch_fct((m,n))

where patch_fct can be easily used with tupels.

Now I want to use the same approach to create a patch_fct that takes a tupel and returns uniformly distributed random numbers between -1 and 1. How can I do that?

I would like to do something like:

patch_fct = 2. * (np.random.random_sample - 0.5)

The approach from above does not seem to be the right one.

Upvotes: 1

Views: 617

Answers (2)

kabanus
kabanus

Reputation: 25895

numpy provides such a function explicitly:

numpy.random.uniform(low=-1, high=1, size=None)

size is the amount of times to draw - this can be a tuple stating the dimensions of the resulting array. size=(10,10) will yield a 10x10 matrix.

If I understand you correctly then:

def patch_fct(size):
    return numpy.random.uniform(low=-1, high=1, size=size)

and size can be a tuple (or not).

In general searching numpy with some math/probability thing will yield the correct answer on the first hit.

Upvotes: 1

timgeb
timgeb

Reputation: 78680

If you need a function that does not already exist, you can just define it and use its name from now on.

For example:

if foo:
    def patch_fct(tup):
        return 2*(np.random.random_sample(tup) - 0.5)
elif bar:
    def patch_fct(tup):
        # do something else
else:
    patch_fct = another_existing_function

The chain of ifs and elses can be written a bit more smoothly with the help of a dictionary.

For your original code, you could write

patch_functions = {'zeros': np.zeros, 
                   'ones': np.ones, 
                   'rand': np.random.random_sample}

and then use it like this:

>>> patch_functions['zeros'](5)
>>> array([0., 0., 0., 0., 0.])

This will automatically throw a KeyError if you are trying to access a key that does not exist in the dictionary.

You can also put self-defined functions inside a dictionary, either by defining them prior to insertion or using anonymous lambda functions. Demo:

>>> def fun1(tup):
...:    return sum(tup) + 1
>>> 
>>> my_functions = {'my_sum': fun1, 'my_random': lambda tup: 2*(np.random.random_sample(tup) - 0.5)}
>>> my_functions['my_sum']((2, 5))
>>> 8
>>> my_functions['my_random']((2, 5))
>>> 
array([[-0.20203832, -0.23868021,  0.72052191,  0.72931098, -0.57160796],
       [-0.45117601, -0.95461634, -0.52232593, -0.24011216, -0.83875935]])

Upvotes: 2

Related Questions