我已经实现了一个带有1个隐藏层的神经网络进行分类。它使用sigmoid activation
函数和cross entropy
丢失。但是在观看cs231n讲座时,我遇到了relu activation
函数,它收敛得更快。因此,我使用relu激活隐藏图层,但准确度从30-40%
大幅减少到90%
。之前我因为cost function
始终倾向于infinity
而挣扎,因为relu的输出可以是0.我通过在log
中添加一个小值来修复它。
以下是我之前使用sigmoid激活的版本中修改过的最重要的代码片段。我无法突出显示我已更改的部分,因此我添加了#changed
评论。如果有人想仔细看看,我会把整个代码。
片段:
激活功能:
def relu(arg): #I have tried both relu and leaky relu
return 1*(arg<0)*0.0001*arg + (arg>=0)*arg
def reluGrad(arg):
for i in range(arg.shape[0]):
for j in range(arg.shape[1]):
if arg[i][j]>0:
arg[i][j]=1
else:
arg[i][j]=0
return arg
def softmax(x):
x = x.transpose()
e_x = np.exp(x - np.max(x))
return (e_x / e_x.sum(axis=0)).transpose()
前进道具
a1 = np.insert(data,0,np.ones(len(data)),1).astype(np.float64)
z2 = a1.dot(theta1)
a2 = relu(z2) #changed
a2 = np.insert(a2,0,np.ones(len(a2)),1)
z3 = a2.dot(theta2)
a3 = softmax(z3) #changed
计算费用:
cost = -(output*(np.log(a3))+(1-output)*(np.log(1-a3))).sum()
cost = (1/len(data))*cost + (lamb/(2*len(data)))*((np.delete(theta1,0,0)**2).sum() + (np.delete(theta2,0,0)**2).sum())
backProp:
sigma3 = a3-output
sigma2 = (sigma3.dot(np.transpose(theta2)))* reluGrad(np.insert(z2,0,np.ones(len(z2)),1)) #changed
sigma2 = np.delete(sigma2,0,1)
delta2 = (np.transpose(a2)).dot(sigma3)
delta1 = (np.transpose(a1)).dot(sigma2)
grad1 = delta1/len(data) + (lamb/len(data))*np.insert(np.delete(theta1,0,0),0,np.zeros(len(theta1[0])),0)
grad2 = delta2/len(data) + (lamb/len(data))*np.insert(np.delete(theta2,0,0),0,np.zeros(len(theta2[0])),0)
#update theta
theta1 = theta1 - alpha*grad1
theta2 = theta2 - alpha*grad2
为什么准确度会降低?使用relu函数实现此错误的原因是什么?