iqbalhabibie habibie
iqbalhabibie habibie

Reputation: 19

python IndexError: index 3 is out of bounds for axis 0 with size 3

I am trying neural network feed forward in my anaconda using python3.7 under ipython script.

I'm not familiar and still learning the problem with python and don't know how to debug this.

import numpy as np
w1 = np.array([[11, 11, 9, 11, 7,13, 14, 6, 6, 12], [11, 11, 9, 11, 7,13, 14, 6, 6, 12], [11, 11, 9, 11, 7,13, 14, 6, 6, 12]])
w2 = np.zeros ((1,10))
b1 = np.array([0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8])
b2 = np.array([0.2])
def f(x):
        return 1 / (1 + np.exp(-x))
def simple_looped_nn_calc(n_layers, x,w,b):
  for l in range(n_layers-1):
    if l == 0:
         node_in = x
    else:
         node_in = h
    h = np.zeros((w[l].shape[0],))
    for i in range(w[l].shape[0]):
       f_sum = 0
       for j in range(w[l].shape[l]):
            f_sum += w[l][i][j]* node_in[j]
       f_sum += b[l][i]
       h[i] = f(f_sum)
  return h



w = [w1, w2]
b = [b1, b2]
x = [280, 0, 280, 280, 0, 0, 0, 0, 280, 0, 0, 0, 0, 0, 0, 0, 0, 280, 0]

When I run my code I get the error , simple_looped_nn_calc(3, x, w, b) like this:

IndexError: index 3 is out of bounds for axis 0 with size 3

Upvotes: 1

Views: 8618

Answers (2)

user69659
user69659

Reputation: 199

replace

for j in range(w[l].shape[l])

with

for j in range(w[l].shape[0]) 

because you are assigning node_in = h , h here is h = np.zeros((w[l].shape[0],)) , so if you will do for i in range(w[l].shape[l]) then size of node_in and w[l].shape[l] may not match and will cause index errors.

Upvotes: 0

Sebastian Dengler
Sebastian Dengler

Reputation: 1308

Are you sure you wanted to write:

for j in range(w[l].shape[l]):

and not

for j in range(w[l].shape[1]):

Hope I helped!

Upvotes: 1

Related Questions