import numpy as np
def nonlin(x, deriv=False):
if(deriv==True):
return(x*(1-x))
return 1/(1+np.exp (-x))
x = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
#seed
np.random.seed(1)
#weights/synapses
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
#training
for j in range(60000):
#layers (input, hidden, output)
#not a class, just thinking of neurons this way
#np.dot is mattrix multiplication
L0 = x
L1 = nonlin(np.dot(L0, syn0))
L2 = nonlin(np.dot(L1, syn1))
#backpropagation
l2_error = y - L2
if (j % 10000) == 0:
print ("Error:" + str(np.mean(np.abs(L2_error))))
#calculate deltas
L2_delta = L2_error*nonlin(L2, deriv=True)
L1_error = L2_delta.dot(syn1.T)
L1_delta = L1_error * nonlin(L1, deriv=True)
#update our synapses
syn1 += L1.T.dot(L2_delta)
syn0 += L0.T.dot(L1_delta)
print ("output after training")
print (L2)
错误说:" L2 = nonlin(np.dot(L1,syn1)) TypeError:*:' NoneType'不支持的操作数类型并且'浮动'"
这是一个非常基本的神经网络。出现错误的部分涉及添加Layer1和syn1作为矩阵。我不确定是否需要将L2更改为浮点数。这是我第一次在python上使用matrixes。
答案 0 :(得分:0)
很高兴看到人们仍在使用Siraj Raval教程在神经网络上练习。
无论如何,当函数 nonlin 没有返回任何内容时会引发错误,因此L1变为无,这是 deriv = False时的情况由于代码中的拼写错误。
我解释说: 当 deriv == False 时, nonlin 函数应该充当sigmoid函数。 对于这个问题,如果 deriv == True ,我们返回 x(1-x)其他 sigmoid ,但是你的拼写错误会阻止函数看到第二种可能性。
因此,定义 nonlin 的正确方法是:
def nonlin(x, deriv=False):
if(deriv==True):
return(x*(1-x))
return 1/(1+np.exp (-x))
或者(您也可以删除 == True 部分)
def nonlin(x, deriv=False):
if deriv:
return(x*(1-x))
else:
return 1/(1+np.exp (-x))
希望这很清楚。
<强>加成强>
即使这不是你要求的,我邀请你查看这个repository的第5周,它可以很好地解释神经网络,以防你想要更深入的概述。
答案 1 :(得分:0)
我们走了,因为怀疑你的函数'nonlin'因为意图错误而返回None。 编辑您的功能,如下所示,
test/
|-- __init__.py
|-- windows/
|-- __init__.py
|-- types.py
|-- window.py
|-- elements.py
|-- test.py
我发现了一个法术错误,
def nonlin(x, deriv=False):
if(deriv==True):
return(x*(1-x))
return 1/(1+np.exp (-x)) # CHECK THE INDENT HERE
到
#backpropagation
l2_error = y - L2
您的代码应该运行。