Sandy.Arv
Sandy.Arv

Reputation: 605

Neural Networks Python

I am trying to build a simple neural network which takes 8 inputs and 2 outputs, from an xls file which has 500 rows of data, with 2 hidden weights in a matrix (8, 2). Currently, the neuron has not started to learn anything. Its jus a sample code to make it run for random weights. Here is my code

def sigmoid(x,deriv=False):
    if(deriv==True):
        return sigmoid(x,False)*(1-sigmoid(x,False))
    return 1/(1+np.exp(-x))

def neuron(inputs, weights):                
    weighted_input = np.dot(inputs, weights)
    return sigmoid(weighted_input, False)

weights = 2 * np.random.random((8,2)) - 1
W = np.array([weights])

error1 = []
for i in range(500):
    for k in range (2):
        X = X_T[i] #list of 8 Inputs from xls 
        T = T_T[i] #list of 2 outputs from xls
        Y = neuron(X, W)[k]
        error1.append(np.sqrt((Y[k] - T) ** 2))    

print W
print np.average(error1)
pl.plot(error1)

I want this code to run for the two hidden weights which are random at the moment. that is why i have set the range of k as 2. But when i try to run this, i get the following error.

IndexError                                Traceback (most recent call last)
<ipython-input-36-b300ce507da8> in <module>()
     20         X = X_T[i]
     21         T = T_T[i]
---> 22         Y = neuron(X, W)[k]
     23         error1.append(np.sqrt((Y[k] - T) ** 2))
     24 

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

I get that i have messed up the loop. but i do not know how to work this out.

Upvotes: 0

Views: 1186

Answers (2)

alex
alex

Reputation: 254

Doing it in loops is rather inefficient. This code benefits from optimized matrix manipulations and should be doing approximately what you want if I understood it correctly.

import numpy as np

def sigmoid(x,deriv=False):
    if(deriv==True):
        s = sigmoid(x,False)
        return s*(1-s)
    return 1/(1+np.exp(-x))

n_in = 8
n_out = 2
n_data = 500

X = np.random.randn( n_data, n_in )
T = np.random.randn( n_data, n_out )

W = np.random.randn( n_out, n_in )
b = np.random.randn( n_out, )

err = ( sigmoid( np.dot(X, W.T) + b ) - T ) ** 2

Upvotes: 1

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

In Y = neuron(X, W)[k]:

neuron(X, W) is return a float value. So you get error.

If neuron(X, W) is return a list/tuple...so on, you can get value by index.

Example:

>>> L = [1,2][0]
>>> L
1
>>> 

Upvotes: 0

Related Questions