Lukasz
Lukasz

Reputation: 2606

Numpy Uniform Distribution With Decay

I'm trying to construct a matrix of uniform distributions decaying to 0 at the same rate in each row. The distributions should be between -1 and 1. What I'm looking at is to construct something that resembles:

[[0.454/exp(0) -0.032/exp(1) 0.641/exp(2)...]
 [-0.234/exp(0) 0.921/exp(1) 0.049/exp(2)...]
 ...
 [0.910/exp(0) 0.003/exp(1) -0.908/exp(2)...]]

I can build a matrix of uniform distributions using:

w = np.array([np.random.uniform(-1, 1, 10) for i in range(10)])

and can achieve the desired result using a for loop with:

for k in range(len(w)):
    for l in range(len(w[0])):
        w[k][l] = w[k][l]/np.exp(l)

but wanted to know if there was a better way of accomplishing this.

Upvotes: 2

Views: 242

Answers (2)

benten
benten

Reputation: 1991

Alok Singhal's answer is best, but as another way to do this (perhaps more explicit) you can duplicate the vector [exp(0), ...,exp(9)] and stack them all into matrix by doing an outer product with a vector of ones. Then divide the 'w' matrix by the new 'decay' matrix.

n=10
w = np.array([np.random.uniform(-1, 1, n) for i in range(n)])
decay = np.outer( np.ones((n,1)), np.exp(np.arange(10)) )
result = w/decay

You could also use np.tile for creating a matrix out of several copies of a vector. It accomplishes the same thing as the outer product trick.

Upvotes: 1

Alok Singhal
Alok Singhal

Reputation: 96091

You can use numpy's broadcasting feature to do this:

w = np.random.uniform(-1, 1, size=(10, 10))
weights = np.exp(np.arange(10))
w /= weights

Upvotes: 6

Related Questions