kamazibel
kamazibel

Reputation: 1

Error in python while programming neural Network (fairly easy... I am new with python)

class neuralNetwork:
    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        self.inodes = input_nodes
        self.hnodes = hidden_nodes
        self.onodes = output_nodes
        self.lr = learning_rate
        pass

    def train():
        pass

    def query():
        pass

input_nodes = 3
hidden_nodes = 3
output_nodes = 3

learning_rate = 0.3
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)

import numpy


self.wih = (numpy.random.rand(self.hnodes, self.inodes) - 0.5)
self.who = (numpy.random.rand(self.onodes, self.hnodes) - 0.5)



---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-8474973d8450> in <module>()
----> 1 self.wih = (numpy.random.rand(self.hnodes, self.inodes) - 0.5)
  2 self.who = (numpy.random.rand(self.onodes, self.hnodes) - 0.5)
NameError: name 'self' is not defined

Why is self not defined?

so how can I fix this error... I overlooked it several times, but still can't find any Solutions to it. Even though it is explained like this in a tutorial. Help would be appreciated.

Upvotes: 0

Views: 146

Answers (1)

Josh K
Josh K

Reputation: 28883

self is passed into the call to an instance method. You're looking to address the instance itself.

nnet = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
nnet.wih = (numpy.random.rand(nnet.hnodes, nnet.inodes) - 0.5)
nnet.who = (numpy.random.rand(nnet.onodes, nnet.hnodes) - 0.5)

Briefly talking about how self works, it's not magical. Taking an example class:

class Foo(object):
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Hello {}".format(self.name)

self is passed into speak when it's invoked as a bound function. One could call it this instead, but self is the Python convention.

Upvotes: 2

Related Questions