Python 名称错误:名称';自我';未在神经网络示例中定义
我直接从塔里克·拉希德的《创建你自己的神经网络》中运行以下代码。它表示“名称错误:未定义名称‘self’”。但它是有定义的。代码直接来自于书中Python 名称错误:名称';自我';未在神经网络示例中定义,python,neural-network,Python,Neural Network,我直接从塔里克·拉希德的《创建你自己的神经网络》中运行以下代码。它表示“名称错误:未定义名称‘self’”。但它是有定义的。代码直接来自于书中 import numpy #neural network class definition class neuralNetwork: #initialize the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate)
import numpy
#neural network class definition
class neuralNetwork:
#initialize the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# set number of nodes in each input, hidden, output layer
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
#learning rate
self.lr = learningrate
pass
#train the neural network
def train():
pass
#query the neural network
def query():
pass
#number of input, hidden and output nodes
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
#learning rate is 0.3
learning_rate = 0.3
#create instance of neural network
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
numpy.random.rand(3, 3)-0.5
#link weight matrices, wih and who
#weights inside the arrays are w_i_j, where link is from node i to node j in
the next layer
#w11 w21
#w12 w22 etc
self.wih = (numpy.random.rand(self.hnodes, self.inodes) - 0.5)
self.who = (numpy.random.rand(self.onodes, self.hnodes) - 0.5)
self
仅在此处的\uuuu init\uuu()函数中定义。顶层代码没有定义它,因此出现错误
代码是否应该位于neuralNetwork
类中的方法内部-那些空的train()
和query()
方法看起来可疑
请注意,您需要将self
作为方法的参数。(例如:def序列(自身):
看起来你遗漏了书中要求你做的事情。我假设你正在尝试,而且代码确实在方法中。替换self.wih=(numpy.random.rand(self.hnodes,self.inodes)-0.5)self.who=(numpy.random.rand(self.onodes,self.hnodes)-0.5)
withwih=(numpy.random.rand(n.hnodes,n.inodes)-0.5)who=(numpy.random.rand(n.onodes,n.hnodes)-0.5)打印出来,who
会给你正确的答案,没有任何语法错误空火车()和查询()方法尚未填写。这是一个逐步的说明。我一直在python笔记本中构建它,这是我收到错误的阶段。@Ken确实如此,但您在底部添加的代码需要在这些方法中。请参阅链接版本。如果您引用的是self
,则必须在方法中执行,否则erwiseself
是什么意思?self
指的是当前实例-如果你不在实例中,那就没有意义了。好的,我明白你的意思。我需要确保其余的代码都在类中。谢谢。@Ken Yeah。在这种情况下,这不太明显,因为你只有一个类实例,但是如果y你做了另一个,使用self
outside没有意义,因为它可能意味着任何一个。值得注意的是,你可以在外部上下文中使用n
来处理实例(因为这恰好是你在这里给它的名称),但一般来说,将代码作为类上的方法编写并调用这些方法更有意义,否则将变得难以阅读和使用。