简体   繁体   中英

Getting error in python when trying to print a variable from a class' function

 class Network(object):

        def __init__(self, sizes):

        def feedforward(self, a):
            for b, w in zip(self.biases, self.weights):
                a = sigmoid(np.dot(w, a)+b)
            return a

        def SGD(self, training_data, epochs, mini_batch_size, eta,
                test_data=None):

        def evaluate(self, test_data):
            test_results = [(np.argmax(self.feedforward(x)), y)
                            for (x, y) in test_data]
            return sum(int(x == y) for (x, y) in test_results)

    def sigmoid(z):
        return 1.0/(1.0+np.exp(-z))

I'm making a neural network (I've left out a lot of code of course because there is a lot of it) and in the function "feedforward" I have the variable "a" which return the activation functions. Once the training is over I would like to print out that variable. The training is started by this:

net=Network([784,30,10])
net.SGD(training_data, 5, 30, 3.0, test_data=test_data)

and the code I tried to print out a:

print(net.feedforward(a))

But I get the following error:

`Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/MyName/DeepLearningPython35/network.py", line 158, in <module>
    print(net.feedforward(a))
NameError: name 'a' is not defined`

The a variable is only available in the local scope of the feedforward function. The line print(net.feedforward(a)) is trying to call the function again with a variable expected to be defined in the global scope. One possibility is to make it an instance variable:

def feedforward(self, a):
    for b, w in zip(self.biases, self.weights):
        self.a = sigmoid(np.dot(w, a)+b)
    return self.a

So you can later print out the last value assigned to it.

print(net.a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM