我只使用python中的numpy创建一个简单的神经网络。我按照本教程进行操作 https://iamtrask.github.io/2015/07/12/basic-python-network/ 我在上面提到的链接中更改了3层神经网络的代码,如下所示。我需要随时调用单独的方法。但它给了我以下错误。我想知道的是为什么我会收到此错误?由于我是python的初学者,我无法弄清楚为什么我会收到此错误?所以请有人帮助我解决这个问题。
import numpy as np
class NeuralNetwork():
def __init__(self):
self.X = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
self.y = np.array([[0],
[1],
[1],
[0]])
np.random.seed(1)
# randomly initialize our weights with mean 0
self.syn0 = 2 * np.random.random((3, 4)) - 1
self.syn1 = 2 * np.random.random((4, 1)) - 1
def nonlin(x, deriv=False):
if (deriv == True):
return x * (1 - x)
return 1 / (1 + np.exp(-x))
def train(self,steps):
for j in xrange(steps):
# Feed forward through layers 0, 1, and 2
l0 = self.X
print("came 1")
l1 = self.nonlin(np.dot(l0, self.syn0))
print("came 2")
l2 = self.nonlin(np.dot(l1, self.syn1))
# how much did we miss the target value?
l2_error = self.y - l2
if (j % 10000) == 0:
print "Error:" + str(np.mean(np.abs(l2_error)))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
l2_delta = l2_error * self.nonlin(l2, deriv=True)
# how much did each l1 value contribute to the l2 error (according to the weights)?
l1_error = l2_delta.dot(self.syn1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
l1_delta = l1_error * self.nonlin(l1, deriv=True)
self.syn1 += l1.T.dot(l2_delta)
self.syn0 += l0.T.dot(l1_delta)
print("Output after training:")
print(l2)
if __name__ == '__main__':
ann=NeuralNetwork()
ann.train(6000)
我得到的错误如下所示
Traceback (most recent call last):
File "C:/Users/Ssa/Desktop/Neural-Network-using-numpy-master/Neural-Network-using-numpy-master/outbreak_test/outbreak_test4.py", line 63, in <module>
ann.train(6000)
File "C:/Users/Ssa/Desktop/Neural-Network-using-numpy-master/Neural-Network-using-numpy-master/outbreak_test/outbreak_test4.py", line 34, in train
l1 = self.nonlin(np.dot(l0, self.syn0))
File "C:/Users/Ssa/Desktop/Neural-Network-using-numpy-master/Neural-Network-using-numpy-master/outbreak_test/outbreak_test4.py", line 23, in nonlin
if (deriv == True):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Process finished with exit code 1
答案 0 :(得分:2)
问题是,您已将函数nonlin
定义为非类成员函数。这意味着,函数的第一个参数不是self
(对象的引用)。您可以通过两种不同的方式使代码工作:
1)将nonlin
功能更改为:
def nonlin(self, x, deriv=True):
...
2)制作nonlin
函数静态方法:
@staticmethod
def nonlin(x, deriv=True):
...
您可以找到有关第二种方法的更多信息here。这两种方法都是有效的,但在我看来,第一种方法似乎更适合面向对象编程。
答案 1 :(得分:0)
nonlin
需要提出self
参数,否则self
将被视为x
,x
将被视为deriv
。< / p>