转 神经网络

神经网络在解决一些复杂的非线性分类问题时,相对于线性回归、逻辑回归,都被证明是一个更好的算法。其实神经网络也可以看做的逻辑回归的组合(叠加,级联等)。

        一个典型神经网络的模型如下图所示:

                 

        上述模型由3个部分组成:输入层、隐藏层、输出层。其中输入层输入特征值,输出层的输出作为我们分类的依据。例如一个20*20大小的手写数字图片的识别举例,那么输入层的输入便可以是20*20=400个像素点的像素值,即模型中的a1;输出层的输出便可以看做是该幅图片是0到9其中某个数字的概率。而隐藏层、输出层中的每个节点其实都可以看做是逻辑回归得到的。逻辑回归的模型可以看做这样(如下图所示):

                        

        有了神经网络的模型,我们的目的就是求解模型里边的参数theta,为此我们还需知道该模型的代价函数以及每一个节点的“梯度值”。

        代价函数的定义如下:

                                               

      代价函数关于每一个节点处theta的梯度可以用反向传播算法计算出来。反向传播算法的思想是由于我们无法直观的得到隐藏层的输出,但我们已知输出层的输出,通过反向传播,倒退其参数。

我们以以下模型举例,来说明反向传播的思路、过程:

                      

该模型与给出的第一个模型不同的是,它具有两个隐藏层。

        为了熟悉这个模型,我们需要先了解前向传播的过程,对于此模型,前向传播的过程如下:

                  

其中,a1,z2等参数的意义可以参照本文给出的第一个神经网络模型,类比得出。

然后我们定义误差delta符号具有如下含义(之后推导梯度要用):

               

误差delta的计算过程如下:

             

然后我们通过反向传播算法求得节点的梯度,反向传播算法的过程如下:

      

有了代价函数与梯度函数,我们可以先用数值的方法检测我们的梯度结果。之后我们就可以像之前那样调用matlab的fminunc函数求得最优的theta参数。

需要注意的是,在初始化theta参数时,需要赋予theta随机值,而不能是固定为0或是什么,这就避免了训练之后,每个节点的参数都是一样的。

下面给出计算代价与梯度的代码:

 

[plain] view plaincopy
  1. function [J grad] = nnCostFunction(nn_params, ...  
  2.                                    input_layer_size, ...  
  3.                                    hidden_layer_size, ...  
  4.                                    num_labels, ...  
  5.                                    X, y, lambda)  
  6. %NNCOSTFUNCTION Implements the neural network cost function for a two layer  
  7. %neural network which performs classification  
  8. %   [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...  
  9. %   X, y, lambda) computes the cost and gradient of the neural network. The  
  10. %   parameters for the neural network are "unrolled" into the vector  
  11. %   nn_params and need to be converted back into the weight matrices.   
  12. %   
  13. %   The returned parameter grad should be a "unrolled" vector of the  
  14. %   partial derivatives of the neural network.  
  15. %  
  16.   
  17. % Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices  
  18. % for our 2 layer neural network  
  19. Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...  
  20.                  hidden_layer_size, (input_layer_size + 1));  
  21.   
  22. Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...  
  23.                  num_labels, (hidden_layer_size + 1));  
  24.   
  25. % Setup some useful variables  
  26. m = size(X, 1);  
  27.            
  28. % You need to return the following variables correctly   
  29. J = 0;  
  30. Theta1_grad = zeros(size(Theta1));  
  31. Theta2_grad = zeros(size(Theta2));  
  32.   
  33. % ====================== YOUR CODE HERE ======================  
  34. % Instructions: You should complete the code by working through the  
  35. %               following parts.  
  36. %  
  37. % Part 1: Feedforward the neural network and return the cost in the  
  38. %         variable J. After implementing Part 1, you can verify that your  
  39. %         cost function computation is correct by verifying the cost  
  40. %         computed in ex4.m  
  41. %  
  42. % Part 2: Implement the backpropagation algorithm to compute the gradients  
  43. %         Theta1_grad and Theta2_grad. You should return the partial derivatives of  
  44. %         the cost function with respect to Theta1 and Theta2 in Theta1_grad and  
  45. %         Theta2_grad, respectively. After implementing Part 2, you can check  
  46. %         that your implementation is correct by running checkNNGradients  
  47. %  
  48. %         Note: The vector y passed into the function is a vector of labels  
  49. %               containing values from 1..K. You need to map this vector into a   
  50. %               binary vector of 1's and 0's to be used with the neural network  
  51. %               cost function.  
  52. %  
  53. %         Hint: We recommend implementing backpropagation using a for-loop  
  54. %               over the training examples if you are implementing it for the   
  55. %               first time.  
  56. %  
  57. % Part 3: Implement regularization with the cost function and gradients.  
  58. %  
  59. %         Hint: You can implement this around the code for  
  60. %               backpropagation. That is, you can compute the gradients for  
  61. %               the regularization separately and then add them to Theta1_grad  
  62. %               and Theta2_grad from Part 2.  
  63. %  
  64. J_tmp=zeros(m,1);  
  65. for i=1:m  
  66.     y_vec=zeros(num_labels,1);  
  67.     y_vec(y(i))=1;  
  68.     a1 = [ones(1, 1) X(i,:)]';  
  69.     z2=Theta1*a1;  
  70.     a2=sigmoid(z2);  
  71.     a2=[ones(1,size(a2,2)); a2];  
  72.     z3=Theta2*a2;  
  73.     a3=sigmoid(z3);  
  74.     hThetaX=a3;  
  75.     J_tmp(i)=sum(-y_vec.*log(hThetaX)-(1-y_vec).*log(1-hThetaX));  
  76. end  
  77. J=1/m*sum(J_tmp);  
  78. J=J+lambda/(2*m)*(sum(sum(Theta1(:,2:end).^2))+sum(sum(Theta2(:,2:end).^2)));  
  79.   
  80. Delta1 = zeros( hidden_layer_size, (input_layer_size + 1));  
  81. Delta2 = zeros( num_labels, (hidden_layer_size + 1));  
  82. for t=1:m  
  83.     y_vec=zeros(num_labels,1);  
  84.     y_vec(y(t))=1;  
  85.     a1 = [1 X(t,:)]';  
  86.     z2=Theta1*a1;  
  87.     a2=sigmoid(z2);  
  88.     a2=[ones(1,size(a2,2)); a2];  
  89.     z3=Theta2*a2;  
  90.     a3=sigmoid(z3);  
  91.     delta_3=a3-y_vec;  
  92.     gz2=[0;sigmoidGradient(z2)];  
  93.     delta_2=Theta2'*delta_3.*gz2;  
  94.     delta_2=delta_2(2:end);  
  95.     Delta2=Delta2+delta_3*a2';  
  96.     Delta1=Delta1+delta_2*a1';  
  97. end  
  98. Theta1_grad=1/m*Delta1;  
  99. Theta2_grad=1/m*Delta2;  
  100.   
  101. Theta1(:,1)=0;  
  102. Theta1_grad=Theta1_grad+lambda/m*Theta1;  
  103. Theta2(:,1)=0;  
  104. Theta2_grad=Theta2_grad+lambda/m*Theta2;  
  105. % -------------------------------------------------------------  
  106.   
  107. % =========================================================================  
  108.   
  109. % Unroll gradients  
  110. grad = [Theta1_grad(:) ; Theta2_grad(:)];  
  111.   
  112.   
  113. end  

最后总结一下,对于一个典型的神经网络,训练过程如下:

 

     

   

按照这个步骤,我们就可以求得神经网络的参数theta。

转载请注明出处:http://blog.csdn.net/u010278305

原文地址:https://www.cnblogs.com/lixiang-/p/4938950.html