【RBM】代码学习--DeepLearningToolBox

下载地址:DeepLearningToolBox

     学习RBM代码之前,需要一些基本的RBM的知识。

     网上有很多参考资料,我借鉴一篇写的很好的系列文章,看下来也差不多能看懂了,博客地址:http://blog.csdn.net/itplus/article/details/19168937


 目录如下

(一)预备知识

(二)网络结构

(三)能量函数和概率分布

(四)对数似然函数

(五)梯度计算公式

(六)对比散度算法

(七)RBM 训练算法

(八)RBM 的评估


通过学习上面的系列文章,基本上理解了RBM的原理,接下来动手学习toolbox中对应的代码部分。本文参考诸多博客,感谢原文作者。


1.ministdeepauto

   这个code对应的原文是 Hition大牛science文章reducing the dimensionality of data with neural networks。
 用MNIST数据库来进行深度的autoencoder压缩,用的是无监督学习,评价标准是重构误差值MSE。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. % Version 1.000  
  2. %  
  3. % Code provided by Ruslan Salakhutdinov and Geoff Hinton    
  4. %  
  5. % Permission is granted for anyone to copy, use, modify, or distribute this  
  6. % program and accompanying programs and documents for any purpose, provided  
  7. this copyright notice is retained and prominently displayed, along with  
  8. % a note saying that the original programs are available from our   
  9. % web page.   
  10. % The programs and documents are distributed without any warranty, express or  
  11. % implied.  As the programs were written for research purposes only, they have  
  12. % not been tested to the degree that would be advisable in any important  
  13. % application.  All use of these programs is entirely at the user's own risk.  
  14.   
  15.   
  16. % This program pretrains a deep autoencoder for MNIST dataset  
  17. % You can set the maximum number of epochs for pretraining each layer  
  18. % and you can set the architecture of the multilayer net.  
  19.   
  20. clc  
  21. clear all  
  22. close all  
  23.   
  24. maxepoch=10; %In the Science paper we use maxepoch=50, but it works just fine.   
  25. numhid=1000; numpen=500; numpen2=250; numopen=30;  
  26.   
  27. fprintf(1,'Converting Raw files into Matlab format \n');  
  28. converter; % 转换数据为matlab的格式  
  29.   
  30. fprintf(1,'Pretraining a deep autoencoder. \n');  
  31. fprintf(1,'The Science paper used 50 epochs. This uses %3i \n', maxepoch);  
  32.   
  33. makebatches;  
  34. [numcases numdims numbatches]=size(batchdata);  
  35.   
  36. fprintf(1,'Pretraining Layer 1 with RBM: %d-%d \n',numdims,numhid);  
  37. restart=1;  
  38. rbm;  
  39. hidrecbiases=hidbiases; %hidbiases为隐含层的偏置值  
  40. save mnistvh vishid hidrecbiases visbiases;  
  41. %保存每层的变量,分别为权值,隐含层偏置值,可视层偏置值  
  42.   
  43. fprintf(1,'\nPretraining Layer 2 with RBM: %d-%d \n',numhid,numpen);  
  44. batchdata=batchposhidprobs; %batchposhidprobs为第一个rbm的输出概率值  
  45. numhid=numpen;  
  46. restart=1;  
  47. rbm;  
  48. hidpen=vishid; penrecbiases=hidbiases; hidgenbiases=visbiases;  
  49. save mnisthp hidpen penrecbiases hidgenbiases;  
  50. %mnisthp为所保存的文件名  
  51.   
  52. fprintf(1,'\nPretraining Layer 3 with RBM: %d-%d \n',numpen,numpen2);  
  53. batchdata=batchposhidprobs;  
  54. numhid=numpen2;  
  55. restart=1;  
  56. rbm;  
  57. hidpen2=vishid; penrecbiases2=hidbiases; hidgenbiases2=visbiases;  
  58. save mnisthp2 hidpen2 penrecbiases2 hidgenbiases2;  
  59.   
  60. fprintf(1,'\nPretraining Layer 4 with RBM: %d-%d \n',numpen2,numopen);  
  61. batchdata=batchposhidprobs;  
  62. numhid=numopen;   
  63. restart=1;  
  64. rbmhidlinear;  
  65. hidtop=vishid; toprecbiases=hidbiases; topgenbiases=visbiases;  
  66. save mnistpo hidtop toprecbiases topgenbiases;  
  67.   
  68. backprop; %Finetune  

 

本次是训练4个隐含层的autoencoder深度网络结构,输入层维度为784维,4个隐含层维度分别为1000,500,250,30。整个网络权值的获得流程梳理如下:

  1. 首先训练第一个rbm网络,即输入层784维和第一个隐含层1000维构成的网络。采用的方法是rbm优化,这个过程用的是训练样本,优化完毕后,计算训练样本在隐含层的输出值。
  2. 利用1中的结果作为第2个rbm网络训练的输入值,同样用rbm网络来优化第2个rbm网络,并计算出网络的输出值。并且用同样的方法训练第3个rbm网络和第4个rbm网络。
  3. 将上面4个rbm网络展开连接成新的网络,且分成encoder和decoder部分。并用步骤1和2得到的网络值给这个新网络赋初值。
  4. 由于新网络中最后的输出和最初的输入节点数是相同的,所以可以将最初的输入值作为网络理论的输出标签值,然后采用BP算法计算网络的代价函数和代价函数的偏导数。
  5. 利用步骤3的初始值和步骤4的代价值和偏导值,采用共轭梯度下降法优化整个新网络,得到最终的网络权值。以上整个过程都是无监督的。

2. Rbm

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. % Version 1.000   
  2. %  
  3. % Code provided by Geoff Hinton and Ruslan Salakhutdinov   
  4. %  
  5. % Permission is granted for anyone to copy, use, modify, or distribute this  
  6. % program and accompanying programs and documents for any purpose, provided  
  7. this copyright notice is retained and prominently displayed, along with  
  8. % a note saying that the original programs are available from our  
  9. % web page.  
  10. % The programs and documents are distributed without any warranty, express or  
  11. % implied.  As the programs were written for research purposes only, they have  
  12. % not been tested to the degree that would be advisable in any important  
  13. % application.  All use of these programs is entirely at the user's own risk.  
  14.   
  15. % This program trains Restricted Boltzmann Machine in which  
  16. % visible, binary, stochastic pixels are connected to  
  17. % hidden, binary, stochastic feature detectors using symmetrically  
  18. % weighted connections. Learning is done with 1-step Contrastive Divergence.     
  19. % The program assumes that the following variables are set externally:  
  20. % maxepoch  -- maximum number of epochs  
  21. % numhid    -- number of hidden units   
  22. % batchdata -- the data that is divided into batches (numcases numdims numbatches)  
  23. % restart   -- set to 1 if learning starts from beginning   
  24.   
  25. epsilonw      = 0.1;   % Learning rate for weights   
  26. epsilonvb     = 0.1;   % Learning rate for biases of visible units   
  27. epsilonhb     = 0.1;   % Learning rate for biases of hidden units   
  28. weightcost  = 0.0002;     
  29. initialmomentum  = 0.5;  
  30. finalmomentum    = 0.9;  
  31.  %由此可见这里隐含层和可视层的偏置值不是共用的,当然了,其权值是共用的  
  32.    
  33. [numcases numdims numbatches]=size(batchdata);%[100,784,600]  
  34.   
  35. if restart ==1,  
  36.   restart=0;  
  37.   epoch=1;  
  38.   
  39. % Initializing symmetric weights and biases.   
  40.   vishid     = 0.1*randn(numdims, numhid);%权值初始值随便给,784*1000  
  41.   hidbiases  = zeros(1,numhid);  
  42.   visbiases  = zeros(1,numdims);  
  43.   
  44.   poshidprobs = zeros(numcases,numhid); %100*1000,单个batch正向传播时隐含层的输出概率  
  45.   neghidprobs = zeros(numcases,numhid);  
  46.   posprods    = zeros(numdims,numhid);  
  47.   negprods    = zeros(numdims,numhid);  
  48.   vishidinc  = zeros(numdims,numhid);  
  49.   hidbiasinc = zeros(1,numhid);  
  50.   visbiasinc = zeros(1,numdims);  
  51.   batchposhidprobs=zeros(numcases,numhid,numbatches);  
  52.   % 整个数据正向传播时隐含层的输出概率  
  53. end  
  54.   
  55. for epoch = epoch:maxepoch,  
  56.  fprintf(1,'epoch %d\r',epoch);   
  57.  errsum=0;  
  58.  for batch = 1:numbatches, %每次迭代都有遍历所有的batch  
  59.  fprintf(1,'epoch %d batch %d\r',epoch,batch);   
  60.   
  61. %%%%%%%%% START POSITIVE PHASE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  62.   data = batchdata(:,:,batch);  
  63.   % 每次迭代都需要取出一个batch的数据,每一行代表一个样本值(这里的数据是double的,不是01的,严格的说后面应将其01化)  
  64.   poshidprobs = 1./(1 + exp(-data*vishid - repmat(hidbiases,numcases,1)));   
  65.   % 样本正向传播时隐含层节点的输出概率   
  66.   batchposhidprobs(:,:,batch)=poshidprobs;  
  67.   posprods    = data' * poshidprobs;  
  68.   %784*1000,这个是求系统的能量值用的,矩阵中每个元素表示对应的可视层节点和隐含层节点的乘积(包含此次样本的数据对应值的累加)  
  69.   poshidact   = sum(poshidprobs);%针对样本值进行求和  
  70.   posvisact = sum(data);  
  71.   
  72. %%%%%%%%% END OF POSITIVE PHASE  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  73.   poshidstates = poshidprobs > rand(numcases,numhid);  
  74.   %将隐含层数据01化(此步骤在posprods之后进行),按照概率值大小来判定.  
  75.   
  76. %%%%%%%%% START NEGATIVE PHASE  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  77.   negdata = 1./(1 + exp(-poshidstates*vishid' - repmat(visbiases,numcases,1)));% 反向进行时的可视层数据  
  78.   neghidprobs = 1./(1 + exp(-negdata*vishid - repmat(hidbiases,numcases,1))); % 反向进行后又马上正向传播的隐含层概率值      
  79.   negprods  = negdata'*neghidprobs;% 同理也是计算能量值用的,784*1000  
  80.   neghidact = sum(neghidprobs);  
  81.   negvisact = sum(negdata);   
  82.   
  83. %%%%%%%%% END OF NEGATIVE PHASE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  84.   err= sum(sum( (data-negdata).^2 ));% 重构后的差值  
  85.   errsum = err + errsum;  
  86.   
  87.    if epoch>5,  
  88.      momentum=finalmomentum;  
  89.      %momentum为保持上一次权值更新增量的比例,如果迭代次数越少,则这个比例值可以稍微大一点  
  90.    else  
  91.      momentum=initialmomentum;  
  92.    end;  
  93.   
  94. %%%%%%%%% UPDATE WEIGHTS AND BIASES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   
  95.     vishidinc = momentum*vishidinc + ...  
  96.                 epsilonw*( (posprods-negprods)/numcases - weightcost*vishid);  
  97.     visbiasinc = momentum*visbiasinc + (epsilonvb/numcases)*(posvisact-negvisact);  
  98.     hidbiasinc = momentum*hidbiasinc + (epsilonhb/numcases)*(poshidact-neghidact);  
  99.   
  100.     vishid = vishid + vishidinc;  
  101.     visbiases = visbiases + visbiasinc;  
  102.     hidbiases = hidbiases + hidbiasinc;  
  103.   
  104. %%%%%%%%%%%%%%%% END OF UPDATES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   
  105.   
  106.   end  
  107.   fprintf(1, 'epoch %4i error %6.1f  \n', epoch, errsum);   
  108. end;  

下面来看下在程序中大致实现RBM权值的优化步骤(假设是一个2层的RBM网络,即只有输入层和输出层,且这两层上的变量是二值变量):
  1. 随机给网络初始化一个权值矩阵w和偏置向量b。
  2. 对可视层输入矩阵v正向传播,计算出隐含层的输出矩阵h,并计算出输入v和h对应节点乘积的均值矩阵
  3. 此时2中的输出h为概率值,将它随机01化为二值变量。
  4. 利用3中01化了的h方向传播计算出可视层的矩阵v’.(按照道理,这个v'应该是要01化的)
  5. 对v’进行正向传播计算出隐含层的矩阵h’,并计算出v’和h’对应节点乘积的均值矩阵。
  6. 用2中得到的均值矩阵减掉5中得到的均值矩阵,其结果作为对应权值增量的矩阵。
  7. 结合其对应的学习率,利用权值迭代公式对权值进行迭代。
  8. 重复计算2到7,直至收敛。

  偏置值的优化步骤:

  1. 随机给网络初始化一个权值矩阵w和偏置向量b。
  2. 对可视层输入矩阵v正向传播,计算出隐含层的输出矩阵h,并计算v层样本的均值向量以及h层的均值向量。
  3. 此时2中的输出h为概率值,将它随机01化为二值变量。
  4. 利用3中01化了的h方向传播计算出可视层的矩阵v’.
  5. 对v’进行正向传播计算出隐含层的矩阵h’, 并计算v‘层样本的均值向量以及h’层的均值向量。
  6. 用2中得到的v方均值向量减掉5中得到的v’方的均值向量,其结果作为输入层v对应偏置的增值向量。用2中得到的h方均值向量减掉5中得到的h’方的均值向量,其结果作为输入层h对应偏置的增值向量。
  7. 结合其对应的学习率,利用权值迭代公式对偏置值进行迭代。
  8. 重复计算2到7,直至收敛。

  当然了,权值更新和偏置值更新每次迭代都是同时进行的,所以应该是同时收敛的。并且在权值更新公式也可以稍微作下变形,比如加入momentum变量,即本次权值更新的增量会保留一部分上次更新权值的增量值。


3. converter


实现的功能是将样本集从.ubyte格式转换成.ascii格式,然后继续转换成.mat格式。


4.makebatches

实现的是将原本的2维数据集变成3维的,因为分了多个批次,另外1维表示的是批次。

5. backprop

反向传递误差
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. % Version 1.000  
  2. %  
  3. % Code provided by Ruslan Salakhutdinov and Geoff Hinton  
  4. %  
  5. % Permission is granted for anyone to copy, use, modify, or distribute this  
  6. % program and accompanying programs and documents for any purpose, provided  
  7. this copyright notice is retained and prominently displayed, along with  
  8. % a note saying that the original programs are available from our  
  9. % web page.  
  10. % The programs and documents are distributed without any warranty, express or  
  11. % implied.  As the programs were written for research purposes only, they have  
  12. % not been tested to the degree that would be advisable in any important  
  13. % application.  All use of these programs is entirely at the user's own risk.  
  14.   
  15. % This program fine-tunes an autoencoder with backpropagation.  
  16. % Weights of the autoencoder are going to be saved in mnist_weights.mat  
  17. % and trainig and test reconstruction errors in mnist_error.mat  
  18. % You can also set maxepoch, default value is 200 as in our paper.    
  19.   
  20. maxepoch=200;  
  21. fprintf(1,'\nFine-tuning deep autoencoder by minimizing cross entropy error. \n');%其微调通过最小化交叉熵来实现  
  22. fprintf(1,'60 batches of 1000 cases each. \n');  
  23.   
  24. load mnistvh % 分别load4个rbm的参数  
  25. load mnisthp  
  26. load mnisthp2  
  27. load mnistpo   
  28.   
  29. makebatches;  
  30. [numcases numdims numbatches]=size(batchdata);  
  31. N=numcases;   
  32.   
  33. %%%% PREINITIALIZE WEIGHTS OF THE AUTOENCODER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  34. w1=[vishid; hidrecbiases]; %分别装载每层的权值和偏置值,将它们作为一个整体  
  35. w2=[hidpen; penrecbiases];  
  36. w3=[hidpen2; penrecbiases2];  
  37. w4=[hidtop; toprecbiases];  
  38. w5=[hidtop'; topgenbiases];   
  39. w6=[hidpen2'; hidgenbiases2];   
  40. w7=[hidpen'; hidgenbiases];   
  41. w8=[vishid'; visbiases];  
  42.   
  43. %%%%%%%%%% END OF PREINITIALIZATIO OF WEIGHTS  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  44.   
  45. l1=size(w1,1)-1;%每个网络层中节点的个数  
  46. l2=size(w2,1)-1;  
  47. l3=size(w3,1)-1;  
  48. l4=size(w4,1)-1;  
  49. l5=size(w5,1)-1;  
  50. l6=size(w6,1)-1;  
  51. l7=size(w7,1)-1;  
  52. l8=size(w8,1)-1;  
  53. l9=l1;  %输出层节点和输入层的一样  
  54. test_err=[];  
  55. train_err=[];  
  56.   
  57.   
  58. for epoch = 1:maxepoch  
  59.   
  60. %%%%%%%%%%%%%%%%%%%% COMPUTE TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  61. err=0;   
  62. [numcases numdims numbatches]=size(batchdata);  
  63. N=numcases;  
  64.  for batch = 1:numbatches  
  65.   data = [batchdata(:,:,batch)];  
  66.   data = [data ones(N,1)];  % b补上一维,因为有偏置项  
  67.   w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];;  
  68.   %正向传播,计算每一层的输出,且同时在输出上增加一维(值为常量1)  
  69.   w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];  
  70.   w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];  
  71.   w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];  
  72.   w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];  
  73.   w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];  
  74.   w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];  
  75.   dataout = 1./(1 + exp(-w7probs*w8));  
  76.   err= err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 )); %重构的误差值  
  77.   end  
  78.  train_err(epoch)=err/numbatches; %总的误差值(训练样本上)  
  79.   
  80. %%%%%%%%%%%%%% END OF COMPUTING TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  81.   
  82. %%%% DISPLAY FIGURE TOP ROW REAL DATA BOTTOM ROW RECONSTRUCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%  
  83. fprintf(1,'Displaying in figure 1: Top row - real data, Bottom row -- reconstructions \n');  
  84. output=[];  
  85.  for ii=1:15  
  86.   output = [output data(ii,1:end-1)' dataout(ii,:)']; %output为15(因为是显示15个数字)组,每组2列,分别为理论值和重构值  
  87.  end  
  88.    if epoch==1   
  89.    close all   
  90.    figure('Position',[100,600,1000,200]);  
  91.    else   
  92.    figure(1)  
  93.    end   
  94.    mnistdisp(output);  
  95.    drawnow;  
  96.   
  97. %%%%%%%%%%%%%%%%%%%% COMPUTE TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  98. [testnumcases testnumdims testnumbatches]=size(testbatchdata);  
  99. N=testnumcases;  
  100. err=0;  
  101. for batch = 1:testnumbatches  
  102.   data = [testbatchdata(:,:,batch)];  
  103.   data = [data ones(N,1)];  
  104.   w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];  
  105.   w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];  
  106.   w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];  
  107.   w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];  
  108.   w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];  
  109.   w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];  
  110.   w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];  
  111.   dataout = 1./(1 + exp(-w7probs*w8));  
  112.   err = err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));  
  113.   end  
  114.  test_err(epoch)=err/testnumbatches;  
  115.  fprintf(1,'Before epoch %d Train squared error: %6.3f Test squared error: %6.3f \t \t \n',epoch,train_err(epoch),test_err(epoch));  
  116.   
  117. %%%%%%%%%%%%%% END OF COMPUTING TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  118.   
  119.  tt=0;  
  120.  for batch = 1:numbatches/10 %测试样本numbatches是100  
  121.  fprintf(1,'epoch %d batch %d\r',epoch,batch);  
  122.   
  123. %%%%%%%%%%% COMBINE 10 MINIBATCHES INTO 1 LARGER MINIBATCH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  124.  tt=tt+1;   
  125.  data=[];  
  126.  for kk=1:10  
  127.   data=[data   
  128.         batchdata(:,:,(tt-1)*10+kk)];   
  129.  end   
  130.   
  131. %%%%%%%%%%%%%%% PERFORM CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  132. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%共轭梯度线性搜索  
  133.   max_iter=3;  
  134.   VV = [w1(:)' w2(:)' w3(:)' w4(:)' w5(:)' w6(:)' w7(:)' w8(:)']';;  
  135.   % 把所有权值(已经包括了偏置值)变成一个大的列向量  
  136.   Dim = [l1; l2; l3; l4; l5; l6; l7; l8; l9];  
  137.   %每层网络对应节点的个数(不包括偏置值)  
  138.   [X, fX] = minimize(VV,'CG_MNIST',max_iter,Dim,data);%该函数时使用共轭梯度的方法来对参数X进行优化  
  139.     
  140.   w1 = reshape(X(1:(l1+1)*l2),l1+1,l2);  
  141.   xxx = (l1+1)*l2;  
  142.   w2 = reshape(X(xxx+1:xxx+(l2+1)*l3),l2+1,l3);  
  143.   xxx = xxx+(l2+1)*l3;  
  144.   w3 = reshape(X(xxx+1:xxx+(l3+1)*l4),l3+1,l4);  
  145.   xxx = xxx+(l3+1)*l4;  
  146.   w4 = reshape(X(xxx+1:xxx+(l4+1)*l5),l4+1,l5);  
  147.   xxx = xxx+(l4+1)*l5;  
  148.   w5 = reshape(X(xxx+1:xxx+(l5+1)*l6),l5+1,l6);  
  149.   xxx = xxx+(l5+1)*l6;  
  150.   w6 = reshape(X(xxx+1:xxx+(l6+1)*l7),l6+1,l7);  
  151.   xxx = xxx+(l6+1)*l7;  
  152.   w7 = reshape(X(xxx+1:xxx+(l7+1)*l8),l7+1,l8);  
  153.   xxx = xxx+(l7+1)*l8;  
  154.   w8 = reshape(X(xxx+1:xxx+(l8+1)*l9),l8+1,l9);  
  155. %依次重新赋值为优化后的参数  
  156. %%%%%%%%%%%%%%% END OF CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
  157.   
  158.  end  
  159.   
  160.  save mnist_weights w1 w2 w3 w4 w5 w6 w7 w8 %前面一个是文件名  
  161.  save mnist_error test_err train_err;  
  162.   
  163. end  

5. CG_MNIST

 函数CG_MNIST形式如下:

  function [f, df] = CG_MNIST(VV,Dim,XX);

  该函数实现的功能是计算网络代价函数值f,以及f对网络中各个参数值的偏导数df,权值和偏置值是同时处理。其中参数VV为网络中所有参数构成的列向量,参数Dim为每层网络的节点数构成的向量,XX为训练样本集合。f和df分别表示网络的代价函数和偏导函数值。 


6.minimize——轭梯度下降的优化函数形式

  [X, fX, i] = minimize(X, f, length, P1, P2, P3, ... )

  该函数时使用共轭梯度的方法来对参数X进行优化,所以X是网络的参数值,为一个列向量。f是一个函数的名称,它主要是用来计算网络中的代价函数以及代价函数对各个参数X的偏导函数,f的参数值分别为X,以及minimize函数后面的P1,P2,P3,…使用共轭梯度法进行优化的最大线性搜索长度为length。返回值X为找到的最优参数,fX为在此最优参数X下的代价函数,i为线性搜索的长度(即迭代的次数)。


深度学习工具包 Deprecation notice. ----- This toolbox is outdated and no longer maintained. There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/) I would suggest you use one of the tools mentioned above rather than use this toolbox. Best, Rasmus. DeepLearnToolbox ================ A Matlab toolbox for Deep Learning. Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data. It is inspired by the human brain's apparent deep (layered, hierarchical) architecture. A good overview of the theory of Deep Learning theory is [Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf) For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng. * [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007) * [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010) * [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011) If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284) ``` @MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012", } ``` Contact: rasmusbergpalm at gmail dot com Directories included in the toolbox ----------------------------------- `NN/` - A library for Feedforward Backpropagation Neural Networks `CNN/` - A library for Convolutional Neural Networks `DBN/` - A library for Deep Belief Networks `SAE/` - A library for Stacked Auto-Encoders `CAE/` - A library for Convolutional Auto-Encoders `util/` - Utility functions used by the libraries `data/` - Data used by the examples `tests/` - unit tests to verify toolbox is working For references on each library check REFS.md Setup ----- 1. Download. 2. addpath(genpath('DeepLearnToolbox')); Example: Deep Belief Network --------------------- ```matlab function test_example_DBN load mnist_uint8; train_x = double(train_x) / 255; test_x = double(test_x) / 255; train_y = double(train_y); test_y = double(test_y); %% ex1 train a 100 hidden unit RBM and visualize its weights rand('state',0) dbn.sizes = [100]; opts.numepochs = 1; opts.batchsize = 100; opts.momentum = 0; opts.alpha = 1; dbn = dbnsetup(dbn, train_x, opts); dbn = dbntrain(dbn, train_x, opts); figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights %% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NN rand('state',0) %train dbn dbn.sizes = [100 100]; opts.numepochs = 1; opts.batchsize = 100; opts.momentum = 0; opts.alpha = 1; dbn = dbnsetup(dbn, train_x, opts); dbn = dbntrain(dbn, train_x, opts); %unfold dbn to nn nn = dbnunfoldtonn(dbn, 10); nn.activation_function = 'sigm'; %train nn opts.numepochs = 1; opts.batchsize = 100; nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.10, 'Too big error'); ``` Example: Stacked Auto-Encoders --------------------- ```matlab function test_example_SAE load mnist_uint8; train_x = double(train_x)/255; test_x = double(test_x)/255; train_y = double(train_y); test_y = double(test_y); %% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN % Setup and train a stacked denoising autoencoder (SDAE) rand('state',0) sae = saesetup([784 100]); sae.ae{1}.activation_function = 'sigm'; sae.ae{1}.learningRate = 1; sae.ae{1}.inputZeroMaskedFraction = 0.5; opts.numepochs = 1; opts.batchsize = 100; sae = saetrain(sae, train_x, opts); visualize(sae.ae{1}.W{1}(:,2:end)') % Use the SDAE to initialize a FFNN nn = nnsetup([784 100 10]); nn.activation_function = 'sigm'; nn.learningRate = 1; nn.W{1} = sae.ae{1}.W{1}; % Train the FFNN opts.numepochs = 1; opts.batchsize = 100; nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.16, 'Too big error'); ``` Example: Convolutional Neural Nets --------------------- ```matlab function test_example_CNN load mnist_uint8; train_x = double(reshape(train_x',28,28,60000))/255; test_x = double(reshape(test_x',28,28,10000))/255; train_y = double(train_y'); test_y = double(test_y'); %% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% error rand('state',0) cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer }; cnn = cnnsetup(cnn, train_x, train_y); opts.alpha = 1; opts.batchsize = 50; opts.numepochs = 1; cnn = cnntrain(cnn, train_x, train_y, opts); [er, bad] = cnntest(cnn, test_x, test_y); %plot mean squared error figure; plot(cnn.rL); assert(er<0.12, 'Too big error'); ``` Example: Neural Networks --------------------- ```matlab function test_example_NN load mnist_uint8; train_x = double(train_x) / 255; test_x = double(test_x) / 255; train_y = double(train_y); test_y = double(test_y); % normalize [train_x, mu, sigma] = zscore(train_x); test_x = normalize(test_x, mu, sigma); %% ex1 vanilla neural net rand('state',0) nn = nnsetup([784 100 10]); opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples [nn, L] = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.08, 'Too big error'); %% ex2 neural net with L2 weight decay rand('state',0) nn = nnsetup([784 100 10]); nn.weightPenaltyL2 = 1e-4; % L2 weight decay opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex3 neural net with dropout rand('state',0) nn = nnsetup([784 100 10]); nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex4 neural net with sigmoid activation function rand('state',0) nn = nnsetup([784 100 10]); nn.activation_function = 'sigm'; % Sigmoid activation function nn.learningRate = 1; % Sigm require a lower learning rate opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex5 plotting functionality rand('state',0) nn = nnsetup([784 20 10]); opts.numepochs = 5; % Number of full sweeps through data nn.output = 'softmax'; % use softmax output opts.batchsize = 1000; % Take a mean gradient step over this many samples opts.plot = 1; % enable plotting nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex6 neural net with sigmoid activation and plotting of validation and training error % split training data into training and validation data vx = train_x(1:10000,:); tx = train_x(10001:end,:); vy = train_y(1:10000,:); ty = train_y(10001:end,:); rand('state',0) nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax output opts.numepochs = 5; % Number of full sweeps through data opts.batchsize = 1000; % Take a mean gradient step over this many samples opts.plot = 1; % enable plotting nn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally) [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); ``` [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
Deep Learning Toolbox™提供了一个框架,用于设计和实现具有算法,预训练模型和应用程序的深度神经网络。您可以使用卷积神经网络(ConvNets,CNN)和长期短期记忆(LSTM)网络对图像,时间序列和文本数据进行分类和回归。应用程序和图表可帮助您可视化激活,编辑网络体系结构以及监控培训进度。 对于小型训练集,您可以使用预训练的深层网络模型(包括SqueezeNet,Inception-v3,ResNet-101,GoogLeNet和VGG-19)以及从TensorFlow™-Keras和Caffe导入的模型执行传输学习。 了解深度学习工具箱的基础知识 深度学习图像 从头开始训练卷积神经网络或使用预训练网络快速学习新任务 使用时间序列,序列和文本进行深度学习 为时间序列分类,回归和预测任务创建和训练网络 深度学习调整和可视化 绘制培训进度,评估准确性,进行预测,调整培训选项以及可视化网络学习的功能 并行和云中的深度学习 通过本地或云中的多个GPU扩展深度学习,并以交互方式或批量作业培训多个网络 深度学习应用 通过计算机视觉,图像处理,自动驾驶,信号和音频扩展深度学习工作流程 深度学习导入,导出和自定义 导入和导出网络,定义自定义深度学习图层以及自定义数据存储 深度学习代码生成 生成MATLAB代码或CUDA ®和C ++代码和部署深学习网络 函数逼近和聚类 使用浅层神经网络执行回归,分类和聚类 时间序列和控制系统 基于浅网络的模型非线性动态系统; 使用顺序数据进行预测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值