2

I am trying to implement backpropagation by my own. Suppose I have a simple vector with whole numbers like the following:

x=[5,3,6,4]

What I would like to do is create matrices, using the previous vector or any like that one. Foe example:

W1 = np.random.normal(loc=0.0, scale=1.0, size=(5,3)) W2 = np.random.normal(loc=0.0, scale=1.0, size=(3,6)) W3 = np.random.normal(loc=0.0, scale=1.0, size=(6,4))

How can I achieve this? The main problem, I guess, is that I cannot name and declare all of this matrices inside a for loop. What would be the most appropiate way of doing this?

1 Answers1

0

You can create a dictionary of your desired arrays:

x=[5,3,6,4]

weights = {'W'+str(i+1): np.random.normal(loc=0.0, scale=1.0, size=(x[i],x[i+1])) 
             for i in range(len(x)-1)}

Then, to use them, just call them from that dictionary. For instance, if you want to use W1, use:

weights['W1']

which returns your array:

array([[-1.22374486,  0.74080707,  0.00914048],
       [ 0.08813797,  0.6807603 ,  0.87249113],
       [ 0.29799539, -0.78276957,  0.11789963],
       [-0.25467395, -1.27457749,  0.96499082],
       [-2.92436286, -0.8131938 , -2.2352768 ]])

You can see a list of all the variables names created using weights.keys()

See this answer

sacuL
  • 49,704
  • 8
  • 81
  • 106
  • Worked as expected. Thanks a lot for the clarification. One more question though. When calling the arrays, is there any way to do it, again, in a loop? For example say I wanted to print all arrays without having to type each one of them. What would be the appropiate way of doing it? I tried with something like `print['W'+str(i+1)]` inside the loop but an exception is raised – Marcelo Rivas Mar 13 '18 at 15:22
  • Found this, and it worked :D `for key in weights: print(weights[key])` – Marcelo Rivas Mar 13 '18 at 15:30