0

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 3x3 matrix and looping usually is inefficient.

2
  • Creating an array with random values is covered quite thoroughly on line, as is adding two arrays. Just where are you stuck? Post the code with a specific problem, not a discussion on things you might try. Please repeat how to ask from the intro tour. Commented Apr 25, 2020 at 20:23
  • I thought I had stated my problem clearly. I now removed my first (inefficient and inelegant) approach to solve this problem, which may have been distracting. I am sorry, but I could not find any advice on how to create an array filled with zeros except for a certain amount of random values, maybe I just don't know the right term to search for though. Commented Apr 25, 2020 at 20:33

2 Answers 2

1

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.        ]])
Sign up to request clarification or add additional context in comments.

Comments

0

You can use np.random.rand(3,3) to create a 3x3 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.