![](/img/trans.png)
[英]Python: Getting an undefine variable error when trying to call a function?
[英]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))
我正在制作一個神經網絡(我當然省略了很多代碼,因為有很多代碼)並且在函數“前饋”中我有變量“a”,它返回激活函數。 培訓結束后,我想打印出該變量。 訓練是這樣開始的:
net=Network([784,30,10])
net.SGD(training_data, 5, 30, 3.0, test_data=test_data)
和我試圖打印出的代碼:
print(net.feedforward(a))
但我收到以下錯誤:
`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`
a
變量僅feedforward
函數的局部范圍內可用。 行print(net.feedforward(a))
嘗試使用預期在全局范圍內定義的變量再次調用該函數。 一種可能性是使其成為實例變量:
def feedforward(self, a):
for b, w in zip(self.biases, self.weights):
self.a = sigmoid(np.dot(w, a)+b)
return self.a
因此,您可以稍后打印出分配給它的最后一個值。
print(net.a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.