How to add different random values to n elements of a numpy array?

Question:

I am trying to add random values to a specific amount of values in a numpy array to mutate weights of my neural network. For example, 2 of the values in this array

[ [0 1 2]
  [3 4 5]
  [6 7 8] ]

are supposed to be mutated (i. e. a random value between -1 and 1 is added to them). The result may look something like this then:

[ [0   0.7 2]
  [3   4   5]
  [6.9 7   8]]

I would prefer a solution without looping, as my real problem is a little bigger than a 3×3 matrix and looping usually is inefficient.

Asked By: Poly-nom-nom-noo

||

Answers:

Here’s one way based on np.random.choice

def add_random_n_places(a, n):
    # Generate a float version
    out = a.astype(float)

    # Generate unique flattened indices along the size of a
    idx = np.random.choice(a.size, n, replace=False)

    # Assign into those places ramdom numbers in [-1,1)
    out.flat[idx] += np.random.uniform(low=-1, high=1, size=n)
    return out

Sample runs –

In [89]: a # input array
Out[89]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [90]: add_random_n_places(a, 2)
Out[90]: 
array([[0.        , 1.        , 2.        ],
       [2.51523009, 4.        , 5.        ],
       [6.        , 7.        , 8.36619255]])

In [91]: add_random_n_places(a, 4)
Out[91]: 
array([[0.67792859, 0.84012682, 2.        ],
       [3.        , 3.71209157, 5.        ],
       [6.        , 6.46088001, 8.        ]])
Answered By: Divakar

You can use np.random.rand(3,3) to create a 3×3 matrix with [0,1) random values.
To get (-1,1) values try np.random.rand(3,3) - np.random.rand(3,3) and add this to a matrix you want to mutate.

Answered By: lotrus28
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.