Python 第二层参数的神经网络导数错误

Python 第二层参数的神经网络导数错误,python,machine-learning,neural-network,minimization,Python,Machine Learning,Neural Network,Minimization,我正在建立我的第一个神经网络。尽管看到我获得了95-98%的准确率令人鼓舞。我通过梯度检查发现,第二层θ(参数)的导数与我通过数值梯度检查得到的结果相差很远(最大差值为0.9…)。我的输入是sklearn load_数字的8X8数字图像 输入维度(1797,65),带有偏差 输出维度(1797,10) 神经网络结构:3层。第1-65层节点、第2-101层节点、第3-10层节点 下面是python代码片段 #forward propagation a1 = x #(1797, 64) a1 =

我正在建立我的第一个神经网络。尽管看到我获得了95-98%的准确率令人鼓舞。我通过梯度检查发现,第二层θ(参数)的导数与我通过数值梯度检查得到的结果相差很远(最大差值为0.9…)。我的输入是sklearn load_数字的8X8数字图像

  • 输入维度(1797,65),带有偏差
  • 输出维度(1797,10)
  • 神经网络结构:3层。第1-65层节点、第2-101层节点、第3-10层节点
下面是python代码片段

#forward propagation
a1 = x #(1797, 64)
a1 = np.column_stack((np.ones(m,),a1)) #(1797,65)
a2 = expit(a1.dot(theta1)) #(1797,100)
a2 = np.column_stack((np.ones(m,),a2)) #(1797,101)
a3 = expit(a2.dot(theta2)) #(1797,10)
a3[a3==1] = 0.999999 #to avoid log(1)
res1 = np.multiply(outputs,np.log(a3)) #(1797,10) .* (1797,10) 
res2 = np.multiply(1-outputs,np.log(1-a3))
lamda = 0.5
cost = (-1/m)*(res1+res2).sum(axis=1).sum() + lamda/(2*m)*(np.square(theta1[1:,:]).sum(axis=1).sum() + np.square(theta2[1:,:]).sum(axis=1).sum())
反向传播代码:

#Back propagation
delta3 = a3 - outputs
delta2 = np.multiply(delta3.dot(theta2.T),np.multiply(a2,1-a2)) #(1797,10) * (10,101) = (1797,101)
D1 = (a1.T.dot(delta2[:,1:])) #(65, 1797) * (1797,100) = (65,100)
D1[0,:] = 1/m * D1[0,:]
D1[1:,:] = 1/m * (D1[1:,:] + lamda*theta1[1:,:])
D2 = (a2.T.dot(delta3)) #(101,1797) * (1797, 10) = (101,10)
D2[0,:] = 1/m * D2[0,:]
D2[1:,:] = 1/m * (D2[1:,:] + lamda*theta2[1:,:]) #something wrong in D2 calculation steps...
#print(theta1.shape,theta2.shape,D1.shape,D2.shape)
#this is what is returned by cost function
return cost,np.concatenate((np.asarray(D1).flatten(),np.asarray(D2).flatten())) #last 1010 wrong values
如你所见,渐变变平了。当我使用数值梯度检查时,我发现前6500个数字非常接近“D1”,最大差值=1.0814544260334766e-07。但与D2相对应的最后1010项的最大值为0.9。下面是渐变检查代码:

print("Checking gradient:")
c,grad = cost(np.concatenate((np.asarray(theta1).flatten(),np.asarray(theta2).flatten())),x_tr,y_tr,theta1.shape,theta2.shape)
grad_approx = checkGrad(x_tr,y_tr,theta1,theta2)
print("Non zero in grad",np.count_nonzero(grad),np.count_nonzero(grad_approx))
tup_grad = np.nonzero(grad)
print("Original\n",grad[tup_grad[0][0:20]])
print("Numerical\n",grad_approx[tup_grad[0][0:20]])
wrong_grads = np.abs(grad-grad_approx)>0.1
print("Max diff:",np.abs(grad-grad_approx).max(),np.count_nonzero(wrong_grads),np.abs(grad-grad_approx)[0:6500].max())
print(np.squeeze(np.asarray(grad[wrong_grads]))[0:20])
print(np.squeeze(np.asarray(grad_approx[wrong_grads]))[0:20])
where_tup = np.where(wrong_grads)
print(where_tup[0][0:5],where_tup[0][-5:])
检查梯度功能:

def checkGrad(x,y,theta1,theta2):
eps = 0.0000001 #0.00001    
theta = np.concatenate((np.asarray(theta1).flatten(),np.asarray(theta2).flatten()))
gradApprox = np.zeros((len(theta,)))
thetaPlus = np.copy(theta)
thetaMinus = np.copy(theta)
print("Total iterations to be made",len(theta))
for i in range(len(theta)):
    if(i % 100 == 0):
        print("iteration",i)
    if(i != 0):
        thetaPlus[i-1] = thetaPlus[i-1]-eps
        thetaMinus[i-1] = thetaMinus[i-1]+eps
    thetaPlus[i] = theta[i]+eps
    thetaMinus[i] = theta[i]-eps
    cost1,grad1 = cost(thetaPlus,x,y,theta1.shape,theta2.shape)
    cost2,grad2 = cost(thetaMinus,x,y,theta1.shape,theta2.shape)
    gradApprox[i] = (cost1 - cost2)/(2*eps)

return gradApprox
我相信我犯了一些新手错误。我意识到这可能需要很多代码。但对于在这一领域有经验的人来说,我可能会有一些建议,指出我犯的错误

  • 错在哪里
  • 为什么我使用相同的算法(TNC)得到了非常不同的scipy最小化结果。BFGS的结果很糟糕
  • 编辑:进一步澄清:我使用checkGrad函数验证我使用backprop为参数θ1和θ2计算的导数(D1和D2)是否正确。“lamda”(打字错误)是正则化常数0.5。Expit是numpy的sigmoid函数


    完整代码:

    通用方法

    如果这是您的第一个NN,那么我建议您使用网络本身计算梯度:

    from copy import deepcopy as dc
    
    
    def gradient(net, weights, dx=0.01):
        der = []
        # compute partial derivatives
        for i in range(len(weights)):
            w = dc(weights)     # dc is needed
            w[i] += dx
            der.append((net(w) - net(weights)) / dx)    # dy/dx
        return der
    
    这里有一个简单的例子

    def net(weights):
        """ this is your net """
        # example with just a simple cost function for clarity purposes
        return sum([i**2 for i in weights])
    
    print('cost', net([1, 1]))
    print('gradient =', gradient(net, [1, 1]))
    

    额外提示:让舒尔在需要时始终使用deepcopy,这花了我很多时间才弄明白

    您能否指定您的
    checkGrad
    函数的功能?expit与
    相同
    ?(还有,字母“lambda”写得不一样;-):-D.对不起,混淆了。我已经添加了对您的查询的响应。我实际上想看看您在内部调用什么。是这个吗?另外,你最初在哪里设置你的
    theta
    值?@dennlinger因为在这里发布完整代码会很笨拙,所以我添加了一个指向完整代码的链接。θ被设置为0到3之间的随机值。我已经在计算数值导数(就像你写的)来验证我的模型。我不明白你到底建议什么作为解决办法。你是说,用这种方法训练我的整个数据集?这种方法简单得多,不需要任何第n层导数公式。对于您的第一个NN,我推荐它,无论如何它不应该花费太多;)