TypeError:不支持*的操作数类型:“NoneType”和“nonlin”的“float”帮助美国运输部"

2024-06-16 14:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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(美国运输部(L1,合成1) TypeError:不支持*:“NoneType”和“float”的操作数类型

这是一个非常基本的神经网络。出现错误的部分包括添加Layer1和syn1作为矩阵。我不确定是否需要将L2更改为float。这是我第一次在python上使用矩阵。在


Tags: truel1ifnprandomerrordotdelta
2条回答

我们开始吧,因为怀疑您的函数'nonlin'由于意图错误而返回None。 编辑你的功能如下

def nonlin(x, deriv=False):
    if(deriv==True):
        return(x*(1-x))
    return 1/(1+np.exp (-x))  # CHECK THE INDENT HERE

我又发现一个拼写错误

变化

^{pr2}$

进入

#backpropagation
L2_error = y  - L2

你的代码应该运行。在

很高兴看到人们仍在使用Siraj Raval教程来练习神经网络。在

不管怎样,当函数nonlin不返回任何内容时,就会引发错误,因此L1变成None,这就是由于代码中的错误而导致deriv=False的情况。在

我解释说: 当deriv==Falseelse作为其导数时,nonlin函数被认为是sigmoid函数。 对于这个问题,如果deriv==True我们返回x(1-x)elsesigmoid,但是您的输入错误阻止了函数看到第二种可能性。在

因此,定义nonlin的正确方法是:

def nonlin(x, deriv=False):
    if(deriv==True):
        return(x*(1-x))

    return 1/(1+np.exp (-x))

或者(也可以删除==True部分)

^{pr2}$

希望这已经足够清楚了。在

奖金

尽管这不是你所要求的,但我请你看看本书的第5周,它对神经网络的解释足够好,以防你想有更深入的了解。在

相关问题 更多 >