【发布时间】:2018-05-04 21:42:42
【问题描述】:
我正在 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
【问题讨论】:
-
这一行的错误
if (deriv == True)令人痛苦,因为比较deriv==True返回一个布尔数组。if不明白如何处理它,因为它需要一个标量,您是否正在寻找所有布尔值、1 个或更多...等等。您可以通过执行if (deriv == True).any()或if (deriv == True).all()来修复警告,但什么是你的意图是什么?
标签: python-2.7 numpy neural-network