深度学习 8. MatConvNet 相关函数解释说明,MatConvNet 代码理解(四)cnn_train.m 的注释

深度学习 8. MatConvNet 相关函数解释说明,MatConvNet 代码理解(四)cnn_train.m 的注释

本文为原创文章转载必须注明本文出处以及附上 本文地址超链接  以及 博主博客地址:http://blog.csdn.net/qq_20259459  和 作者邮箱( jinweizhi93@gmai.com )。

(如果喜欢本文,欢迎大家关注我的博客或者动手点个赞,有需要可以邮件联系我)

 

 

接上一篇文章(阅读上一篇文章:http://blog.csdn.net/qq_20259459/article/details/54600368 )

 

 

(四)cnn_train.m 

 

 

[plain] view plain copy
 
  1. %调用cnn_train:  
  2. % [ net, info ] = cnn_train(net, imdb, @getBatch, opts.train, 'val', find(imdb.images.set == 3)) ;  
  3.   
  4. function [net, stats] = cnn_train(net, imdb, getBatch, varargin)  
  5. %% --------------------------------------------------------------  
  6. %   函数名:cnn_train  
  7. %   功能:  1.用于训练过程  
  8. %           2.使用随机梯度下降法(SGD)  
  9. % ------------------------------------------------------------------------  
  10. %CNN_TRAIN  An example implementation of SGD for training CNNs  
  11. %    CNN_TRAIN() is an example learner implementing stochastic  
  12. %    gradient descent with momentum to train a CNN. It can be used  
  13. %    with different datasets and tasks by providing a suitable  
  14. %    getBatch function.  
  15. %  
  16. %    The function automatically restarts after each training epoch by  
  17. %    checkpointing.  
  18. %  
  19. %    The function supports training on CPU or on one or more GPUs  
  20. %    (specify the list of GPU IDs in the `gpus` option).  
  21.   
  22. % Copyright (C) 2014-16 Andrea Vedaldi.  
  23. % All rights reserved.  
  24. %  
  25. % This file is part of the VLFeat library and is made available under  
  26. % the terms of the BSD license (see the COPYING file).  
  27. % ------------------------------------------------------------------------  
  28. %翻译:  
  29. %cnn_train是一个学习器的示例,基于SGD算法对CNN进行训练。  
  30. %通过适当的getBatch函数,cnn_train可以被用在训练不同的数据集,以实现不同目的的训练。  
  31. %cnn_train提供了自动检查上次训练状态并且继续接着训练的能力。  
  32. %cnn_train支持使用GPU并且同时支持多个GPU的并行运算  
  33. % ------------------------------------------------------------------------  
  34.   
  35. opts.subsetSize = 1e4;  
  36.   
  37. opts.expDir = fullfile('data','exp') ;      %选择保存路径  
  38. opts.continue = true ;                      %选择每次重启都是接着上次训练状态开始  
  39. opts.batchSize = 256 ;                      %选择初始化批的大小为256  
  40. opts.numSubBatches = 1 ;                    %选择子批的个数为1(不划分子批)  
  41. opts.train = [] ;                           %初始化训练集索引为空  
  42. opts.val = [] ;                             %初始化验证集索引为空  
  43. opts.gpus = [] ;                            %选择GPU  
  44. opts.prefetch = false ;                     %选择是否预读取下一批次的样本(初始化为否)  
  45. opts.numEpochs = 300 ;                      %选择epoch为300  
  46. opts.learningRate = 0.001 ;                 %选择学习率为0.001  
  47. opts.weightDecay = 0.0005 ;                 %选择权重延迟为0.0005  
  48. opts.momentum = 0.9 ;                       %选择动量为0.9  
  49. opts.saveMomentum = true ;                  %选择存储动量  
  50. opts.nesterovUpdate = false ;               %选择nesterovUpdate为假  
  51. opts.randomSeed = 0 ;                       %选择随机种子为0  
  52. opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;      %选择内存映射文件  
  53. opts.profile = false ;                      %选择profile为假  
  54. opts.parameterServer.method = 'mmap' ;      %选择参数server的途径为mmap  
  55. opts.parameterServer.prefix = 'mcn' ;       %选择参数server的词头为mcn  
  56.   
  57. opts.conserveMemory = true ;                %选择是否保存内存(是)  
  58. opts.backPropDepth = +inf ;                 %选择BP的深度(传到底)  
  59. opts.sync = false ;                         %选择是否同步(是)  
  60. opts.cudnn = true ;                         %选择是否使用cudnn(是)  
  61. opts.errorFunction = 'multiclass' ;         %选择误差函数为多类误差  
  62. opts.errorLabels = {} ;                     %初始化错误标签为空  
  63. opts.plotDiagnostics = false ;              %选择是否绘制诊断信息(否)  
  64. opts.plotStatistics = true;                 %选择是否绘制过程统计信息(是)  
  65. opts = vl_argparse(opts, varargin) ;        %调用vl_argparse函数,修改默认参数配置  
  66.   
  67. % ------------------------------------------------------------------------  
  68. %                                                            初始化准备工作  
  69. % ------------------------------------------------------------------------  
  70. if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end                     %如果不存在保存路径就创建该路径  
  71. if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end         %如果imdb.images.set==1就得到训练样本索引集  
  72. if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end             %如果imdb.images.set==2就得到验证样本索引集  
  73. if isnan(opts.train), opts.train = [] ; end                                 %如果opts.train中有非数字元素存在就返回true并且清空训练集  
  74. if isnan(opts.val), opts.val = [] ; end                                     %如果opts.val中有非数字元素存在就返回true并且清空val集  
  75.   
  76. % -------------------------------------------------------------------------  
  77. %                                                            Initialization  
  78. %                                                                    初始化  
  79. % -------------------------------------------------------------------------  
  80.   
  81. net = vl_simplenn_tidy(net); % fill in some eventually missing values|||为网络添加最终缺失值  
  82. net.layers{end-1}.precious = 1; % do not remove predictions, used for error|||不要移除predictions,用于误差计算  
  83. vl_simplenn_display(net, 'batchSize', opts.batchSize) ;             %在控制台输出batchSize信息  
  84.   
  85. evaluateMode = isempty(opts.train) ;                %如果训练集为空就进入评估模式  
  86. if ~evaluateMode                                    %如果训练集不为空就进入训练模式:  
  87.   for i=1:numel(net.layers)                           
  88.     J = numel(net.layers{i}.weights) ;  
  89.     if ~isfield(net.layers{i}, 'learningRate')  
  90.       net.layers{i}.learningRate = ones(1, J) ;  
  91.     end  
  92.     if ~isfield(net.layers{i}, 'weightDecay')  
  93.       net.layers{i}.weightDecay = ones(1, J) ;  
  94.     end  
  95.   end  
  96. end  
  97.   
  98. % setup error calculation function  
  99. %设置误差计算函数  
  100. hasError = true ;  
  101. if isstr(opts.errorFunction)  
  102.   switch opts.errorFunction         %选择误差类型  
  103.     case 'none'                     %没有误差的case  
  104.       opts.errorFunction = @error_none ;                      
  105.       hasError = false ;  
  106.     case 'multiclass'               %多类误差的case  
  107.       opts.errorFunction = @error_multiclass ;  
  108.       if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end  
  109.     case 'binary'                   %二值误差的case  
  110.       opts.errorFunction = @error_binary ;  
  111.       if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end  
  112.       otherwise                     %其他  
  113.       error('Unknown error function ''%s''.', opts.errorFunction) ;  
  114.   end  
  115. end  
  116.   
  117. state.getBatch = getBatch ;  
  118. stats = [] ;  
  119.   
  120. % -------------------------------------------------------------------------  
  121. %                                                        Train and validate  
  122. %                                                                 训练和验证  
  123. % -------------------------------------------------------------------------  
  124.   
  125. modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));   %保存训练好的模型已经误差曲线  
  126. modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;                     %训练结果统计图  
  127.   
  128. start = opts.continue * findLastCheckpoint(opts.expDir) ;                   %选择训练开始的位置  
  129. if start >= 1                                                               %从上次停下的状态继续训练  
  130.   fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;           
  131.   [net, state, stats] = loadState(modelPath(start)) ;  
  132. else  
  133.   state = [] ;  
  134. end  
  135.   
  136. for epoch=start+1:opts.numEpochs  
  137.   
  138.   % Set the random seed based on the epoch and opts.randomSeed.  
  139.   % This is important for reproducibility, including when training  
  140.   % is restarted from a checkpoint.  
  141.   
  142.   rng(epoch + opts.randomSeed) ;  
  143.   prepareGPUs(opts, epoch == start+1) ;  
  144.   
  145.   % Train for one epoch.  
  146.   % 一次epoch的训练过程  
  147.   params = opts ;  
  148.   params.epoch = epoch ;  
  149.   params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;  
  150.   params.train = opts.train(randperm(numel(opts.train))) ; % shuffle  
  151.   params.val = opts.val(randperm(numel(opts.val))) ;  
  152.   params.imdb = imdb ;  
  153.   params.getBatch = getBatch ;  
  154.   
  155.   if numel(params.gpus) <= 1  
  156.     [net, state] = processEpoch(net, state, params, 'train') ;  
  157.     [net, state] = processEpoch(net, state, params, 'val') ;  
  158.     if ~evaluateMode  
  159.       saveState(modelPath(epoch), net, state) ;  
  160.     end  
  161.     lastStats = state.stats ;  
  162.   else  
  163.     spmd  
  164.       [net, state] = processEpoch(net, state, params, 'train') ;  
  165.       [net, state] = processEpoch(net, state, params, 'val') ;  
  166.       if labindex == 1 && ~evaluateMode  
  167.         saveState(modelPath(epoch), net, state) ;  
  168.       end  
  169.       lastStats = state.stats ;  
  170.     end  
  171.     lastStats = accumulateStats(lastStats) ;  
  172.   end  
  173.   
  174.   stats.train(epoch) = lastStats.train ;  
  175.   stats.val(epoch) = lastStats.val ;  
  176.   clear lastStats ;  
  177.   saveStats(modelPath(epoch), stats) ;  
  178.   
  179.   if params.plotStatistics  
  180.     switchFigure(1) ; clf ;  
  181.     plots = setdiff(...  
  182.       cat(2,...  
  183.       fieldnames(stats.train)', ...  
  184.       fieldnames(stats.val)'), {'num', 'time'}) ;  
  185.     for p = plots  
  186.       p = char(p) ;  
  187.       values = zeros(0, epoch) ;  
  188.       leg = {} ;  
  189.       for f = {'train', 'val'}  
  190.         f = char(f) ;  
  191.         if isfield(stats.(f), p)  
  192.           tmp = [stats.(f).(p)] ;  
  193.           values(end+1,:) = tmp(1,:)' ;  
  194.           leg{end+1} = f ;  
  195.         end  
  196.       end  
  197.       subplot(1,numel(plots),find(strcmp(p,plots))) ;  
  198.       plot(1:epoch, values','o-') ;  
  199.       xlabel('epoch') ;  
  200.       title(p) ;  
  201.       legend(leg{:}) ;  
  202.       grid on ;  
  203.     end  
  204.     drawnow ;  
  205.     print(1, modelFigPath, '-dpdf') ;  
  206.   end  
  207. end  
  208.   
  209. % With multiple GPUs, return one copy  
  210. if isa(net, 'Composite'), net = net{1} ; end  
  211.   
  212. % -------------------------------------------------------------------------  
  213. function err = error_multiclass(params, labels, res)  
  214. % -------------------------------------------------------------------------  
  215. % 多类误差  
  216. % -------------------------------------------------------------------------  
  217. predictions = gather(res(end-1).x) ;  
  218. [~,predictions] = sort(predictions, 3, 'descend') ;  
  219.   
  220. % be resilient to badly formatted labels  
  221. if numel(labels) == size(predictions, 4)  
  222.   labels = reshape(labels,1,1,1,[]) ;  
  223. end  
  224.   
  225. % skip null labels  
  226. mass = single(labels(:,:,1,:) > 0) ;  
  227. if size(labels,3) == 2  
  228.   % if there is a second channel in labels, used it as weights  
  229.   mass = mass .* labels(:,:,2,:) ;  
  230.   labels(:,:,2,:) = [] ;  
  231. end  
  232.   
  233. m = min(5, size(predictions,3)) ;  
  234.   
  235. error = ~bsxfun(@eq, predictions, labels) ;  
  236. err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;  
  237. err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;  
  238.   
  239. % -------------------------------------------------------------------------  
  240. function err = error_binary(params, labels, res)  
  241. % -------------------------------------------------------------------------  
  242. % 二值误差  
  243. % -------------------------------------------------------------------------  
  244. predictions = gather(res(end-1).x) ;  
  245. error = bsxfun(@times, predictions, labels) < 0 ;  
  246. err = sum(error(:)) ;  
  247.   
  248. % -------------------------------------------------------------------------  
  249. function err = error_none(params, labels, res)  
  250. % -------------------------------------------------------------------------  
  251. % 空误差  
  252. % -------------------------------------------------------------------------  
  253. err = zeros(0,1) ;  
  254.   
  255. % -------------------------------------------------------------------------  
  256. function [net, state] = processEpoch(net, state, params, mode)  
  257. % -------------------------------------------------------------------------  
  258. %   
  259. % Note that net is not strictly needed as an output argument as net  
  260. % is a handle class. However, this fixes some aliasing issue in the  
  261. % spmd caller.  
  262. % 处理一个回合的训练  
  263. % -------------------------------------------------------------------------  
  264.   
  265. % initialize with momentum 0  
  266. if isempty(state) || isempty(state.momentum)  
  267.   for i = 1:numel(net.layers)  
  268.     for j = 1:numel(net.layers{i}.weights)  
  269.       state.momentum{i}{j} = 0 ;  
  270.     end  
  271.   end  
  272. end  
  273.   
  274. % move CNN  to GPU as needed  
  275. numGpus = numel(params.gpus) ;  
  276. if numGpus >= 1  
  277.   net = vl_simplenn_move(net, 'gpu') ;  
  278.   for i = 1:numel(state.momentum)  
  279.     for j = 1:numel(state.momentum{i})  
  280.       state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;  
  281.     end  
  282.   end  
  283. end  
  284. if numGpus > 1  
  285.   parserv = ParameterServer(params.parameterServer) ;  
  286.   vl_simplenn_start_parserv(net, parserv) ;  
  287. else  
  288.   parserv = [] ;  
  289. end  
  290.   
  291. % profile  
  292. if params.profile  
  293.   if numGpus <= 1  
  294.     profile clear ;  
  295.     profile on ;  
  296.   else  
  297.     mpiprofile reset ;  
  298.     mpiprofile on ;  
  299.   end  
  300. end  
  301.   
  302. subset = params.(mode) ;  
  303. num = 0 ;  
  304. stats.num = 0 ; % return something even if subset = []  
  305. stats.time = 0 ;  
  306. adjustTime = 0 ;  
  307. res = [] ;  
  308. error = [] ;  
  309.   
  310. start = tic ;  
  311. for t=1:params.batchSize:numel(subset)  
  312.   fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...  
  313.           fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;  
  314.   batchSize = min(params.batchSize, numel(subset) - t + 1) ;  
  315.   
  316.   for s=1:params.numSubBatches  
  317.     % get this image batch and prefetch the next  
  318.     batchStart = t + (labindex-1) + (s-1) * numlabs ;  
  319.     batchEnd = min(t+params.batchSize-1, numel(subset)) ;  
  320.     batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;  
  321.     num = num + numel(batch) ;  
  322.     if numel(batch) == 0, continue ; end  
  323.   
  324.     [im, labels] = params.getBatch(params.imdb, batch) ;  
  325.   
  326.     if params.prefetch  
  327.       if s == params.numSubBatches  
  328.         batchStart = t + (labindex-1) + params.batchSize ;  
  329.         batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;  
  330.       else  
  331.         batchStart = batchStart + numlabs ;  
  332.       end  
  333.       nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;  
  334.       params.getBatch(params.imdb, nextBatch) ;  
  335.     end  
  336.   
  337.     if numGpus >= 1  
  338.       im = gpuArray(im) ;  
  339.     end  
  340.   
  341.     if strcmp(mode, 'train')  
  342.       dzdy = 1 ;  
  343.       evalMode = 'normal' ;  
  344.     else  
  345.       dzdy = [] ;  
  346.       evalMode = 'test' ;  
  347.     end  
  348.     net.layers{end}.class = labels ;  
  349.     res = vl_simplenn(net, im, dzdy, res, ...  
  350.                       'accumulate', s ~= 1, ...  
  351.                       'mode', evalMode, ...  
  352.                       'conserveMemory', params.conserveMemory, ...  
  353.                       'backPropDepth', params.backPropDepth, ...  
  354.                       'sync', params.sync, ...  
  355.                       'cudnn', params.cudnn, ...  
  356.                       'parameterServer', parserv, ...  
  357.                       'holdOn', s < params.numSubBatches) ;  
  358.   
  359.     % accumulate errors  
  360.     error = sum([error, [...  
  361.       sum(double(gather(res(end).x))) ;  
  362.       reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;  
  363.   end  
  364.   
  365.   % accumulate gradient  
  366.   if strcmp(mode, 'train')  
  367.     if ~isempty(parserv), parserv.sync() ; end  
  368.     [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;  
  369.   end  
  370.   
  371.   % get statistics  
  372.   time = toc(start) + adjustTime ;  
  373.   batchTime = time - stats.time ;  
  374.   stats = extractStats(net, params, error / num) ;  
  375.   stats.num = num ;  
  376.   stats.time = time ;  
  377.   currentSpeed = batchSize / batchTime ;  
  378.   averageSpeed = (t + batchSize - 1) / time ;  
  379.   if t == 3*params.batchSize + 1  
  380.     % compensate for the first three iterations, which are outliers  
  381.     adjustTime = 4*batchTime - time ;  
  382.     stats.time = time + adjustTime ;  
  383.   end  
  384.   
  385.   fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;  
  386.   for f = setdiff(fieldnames(stats)', {'num', 'time'})  
  387.     f = char(f) ;  
  388.     fprintf(' %s: %.3f', f, stats.(f)) ;  
  389.   end  
  390.   fprintf('\n') ;  
  391.   
  392.   % collect diagnostic statistics  
  393.   if strcmp(mode, 'train') && params.plotDiagnostics  
  394.     switchFigure(2) ; clf ;  
  395.     diagn = [res.stats] ;  
  396.     diagnvar = horzcat(diagn.variation) ;  
  397.     diagnpow = horzcat(diagn.power) ;  
  398.     subplot(2,2,1) ; barh(diagnvar) ;  
  399.     set(gca,'TickLabelInterpreter', 'none', ...  
  400.       'YTick', 1:numel(diagnvar), ...  
  401.       'YTickLabel',horzcat(diagn.label), ...  
  402.       'YDir', 'reverse', ...  
  403.       'XScale', 'log', ...  
  404.       'XLim', [1e-5 1], ...  
  405.       'XTick', 10.^(-5:1)) ;  
  406.     grid on ;  
  407.     subplot(2,2,2) ; barh(sqrt(diagnpow)) ;  
  408.     set(gca,'TickLabelInterpreter', 'none', ...  
  409.       'YTick', 1:numel(diagnpow), ...  
  410.       'YTickLabel',{diagn.powerLabel}, ...  
  411.       'YDir', 'reverse', ...  
  412.       'XScale', 'log', ...  
  413.       'XLim', [1e-5 1e5], ...  
  414.       'XTick', 10.^(-5:5)) ;  
  415.     grid on ;  
  416.     subplot(2,2,3); plot(squeeze(res(end-1).x)) ;  
  417.     drawnow ;  
  418.   end  
  419. end  
  420.   
  421. % Save back to state.  
  422. state.stats.(mode) = stats ;  
  423. if params.profile  
  424.   if numGpus <= 1  
  425.     state.prof.(mode) = profile('info') ;  
  426.     profile off ;  
  427.   else  
  428.     state.prof.(mode) = mpiprofile('info');  
  429.     mpiprofile off ;  
  430.   end  
  431. end  
  432. if ~params.saveMomentum  
  433.   state.momentum = [] ;  
  434. else  
  435.   for i = 1:numel(state.momentum)  
  436.     for j = 1:numel(state.momentum{i})  
  437.       state.momentum{i}{j} = gather(state.momentum{i}{j}) ;  
  438.     end  
  439.   end  
  440. end  
  441.   
  442. net = vl_simplenn_move(net, 'cpu') ;  
  443.   
  444. % -------------------------------------------------------------------------  
  445. function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)  
  446. % -------------------------------------------------------------------------  
  447. % 梯度下降累计函数  
  448. % -------------------------------------------------------------------------  
  449. numGpus = numel(params.gpus) ;  
  450. otherGpus = setdiff(1:numGpus, labindex) ;  
  451.   
  452. for l=numel(net.layers):-1:1  
  453.   for j=numel(res(l).dzdw):-1:1  
  454.   
  455.     if ~isempty(parserv)  
  456.       tag = sprintf('l%d_%d',l,j) ;  
  457.       parDer = parserv.pull(tag) ;  
  458.     else  
  459.       parDer = res(l).dzdw{j}  ;  
  460.     end  
  461.   
  462.     if j == 3 && strcmp(net.layers{l}.type, 'bnorm')  
  463.       % special case for learning bnorm moments  
  464.       thisLR = net.layers{l}.learningRate(j) ;  
  465.       net.layers{l}.weights{j} = vl_taccum(...  
  466.         1 - thisLR, ...  
  467.         net.layers{l}.weights{j}, ...  
  468.         thisLR / batchSize, ...  
  469.         parDer) ;  
  470.     else  
  471.       % Standard gradient training.  
  472.       thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;  
  473.       thisLR = params.learningRate * net.layers{l}.learningRate(j) ;  
  474.   
  475.       if thisLR>0 || thisDecay>0  
  476.         % Normalize gradient and incorporate weight decay.  
  477.         parDer = vl_taccum(1/batchSize, parDer, ...  
  478.                            thisDecay, net.layers{l}.weights{j}) ;  
  479.   
  480.         % Update momentum.  
  481.         state.momentum{l}{j} = vl_taccum(...  
  482.           params.momentum, state.momentum{l}{j}, ...  
  483.           -1, parDer) ;  
  484.   
  485.         % Nesterov update (aka one step ahead).  
  486.         if params.nesterovUpdate  
  487.           delta = vl_taccum(...  
  488.             params.momentum, state.momentum{l}{j}, ...  
  489.             -1, parDer) ;  
  490.         else  
  491.           delta = state.momentum{l}{j} ;  
  492.         end  
  493.   
  494.         % Update parameters.  
  495.         net.layers{l}.weights{j} = vl_taccum(...  
  496.           1, net.layers{l}.weights{j}, ...  
  497.           thisLR, delta) ;  
  498.       end  
  499.     end  
  500.   
  501.     % if requested, collect some useful stats for debugging  
  502.     if params.plotDiagnostics  
  503.       variation = [] ;  
  504.       label = '' ;  
  505.       switch net.layers{l}.type  
  506.         case {'conv','convt'}  
  507.           variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;  
  508.           power = mean(res(l+1).x(:).^2) ;  
  509.           if j == 1 % fiters  
  510.             base = mean(net.layers{l}.weights{j}(:).^2) ;  
  511.             label = 'filters' ;  
  512.           else % biases  
  513.             base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;  
  514.             label = 'biases' ;  
  515.           end  
  516.           variation = variation / base ;  
  517.           label = sprintf('%s_%s', net.layers{l}.name, label) ;  
  518.       end  
  519.       res(l).stats.variation(j) = variation ;  
  520.       res(l).stats.power = power ;  
  521.       res(l).stats.powerLabel = net.layers{l}.name ;  
  522.       res(l).stats.label{j} = label ;  
  523.     end  
  524.   end  
  525. end  
  526.   
  527. % -------------------------------------------------------------------------  
  528. function stats = accumulateStats(stats_)  
  529. % -------------------------------------------------------------------------  
  530.   
  531. for s = {'train', 'val'}  
  532.   s = char(s) ;  
  533.   total = 0 ;  
  534.   
  535.   % initialize stats stucture with same fields and same order as  
  536.   % stats_{1}  
  537.   stats__ = stats_{1} ;  
  538.   names = fieldnames(stats__.(s))' ;  
  539.   values = zeros(1, numel(names)) ;  
  540.   fields = cat(1, names, num2cell(values)) ;  
  541.   stats.(s) = struct(fields{:}) ;  
  542.   
  543.   for g = 1:numel(stats_)  
  544.     stats__ = stats_{g} ;  
  545.     num__ = stats__.(s).num ;  
  546.     total = total + num__ ;  
  547.   
  548.     for f = setdiff(fieldnames(stats__.(s))', 'num')  
  549.       f = char(f) ;  
  550.       stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;  
  551.   
  552.       if g == numel(stats_)  
  553.         stats.(s).(f) = stats.(s).(f) / total ;  
  554.       end  
  555.     end  
  556.   end  
  557.   stats.(s).num = total ;  
  558. end  
  559.   
  560. % -------------------------------------------------------------------------  
  561. function stats = extractStats(net, params, errors)  
  562. % -------------------------------------------------------------------------  
  563. stats.objective = errors(1) ;  
  564. for i = 1:numel(params.errorLabels)  
  565.   stats.(params.errorLabels{i}) = errors(i+1) ;  
  566. end  
  567.   
  568. % -------------------------------------------------------------------------  
  569. function saveState(fileName, net, state)  
  570. % -------------------------------------------------------------------------  
  571. save(fileName, 'net', 'state') ;  
  572.   
  573. % -------------------------------------------------------------------------  
  574. function saveStats(fileName, stats)  
  575. % -------------------------------------------------------------------------  
  576. if exist(fileName)  
  577.   save(fileName, 'stats', '-append') ;  
  578. else  
  579.   save(fileName, 'stats') ;  
  580. end  
  581.   
  582. % -------------------------------------------------------------------------  
  583. function [net, state, stats] = loadState(fileName)  
  584. % -------------------------------------------------------------------------  
  585. load(fileName, 'net', 'state', 'stats') ;  
  586. net = vl_simplenn_tidy(net) ;  
  587. if isempty(whos('stats'))  
  588.   error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...  
  589.         fileName) ;  
  590. end  
  591.   
  592. % -------------------------------------------------------------------------  
  593. function epoch = findLastCheckpoint(modelDir)  
  594. % -------------------------------------------------------------------------  
  595. list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;  
  596. tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;  
  597. epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;  
  598. epoch = max([epoch 0]) ;  
  599.   
  600. % -------------------------------------------------------------------------  
  601. function switchFigure(n)  
  602. % -------------------------------------------------------------------------  
  603. if get(0,'CurrentFigure') ~= n  
  604.   try  
  605.     set(0,'CurrentFigure',n) ;  
  606.   catch  
  607.     figure(n) ;  
  608.   end  
  609. end  
  610.   
  611. % -------------------------------------------------------------------------  
  612. function clearMex()  
  613. % -------------------------------------------------------------------------  
  614. %clear vl_tmove vl_imreadjpeg ;  
  615. disp('Clearing mex files') ;  
  616. clear mex ;  
  617. clear vl_tmove vl_imreadjpeg ;  
  618.   
  619. % -------------------------------------------------------------------------  
  620. function prepareGPUs(params, cold)  
  621. % -------------------------------------------------------------------------  
  622. numGpus = numel(params.gpus) ;  
  623. if numGpus > 1  
  624.   % check parallel pool integrity as it could have timed out  
  625.   pool = gcp('nocreate') ;  
  626.   if ~isempty(pool) && pool.NumWorkers ~= numGpus  
  627.     delete(pool) ;  
  628.   end  
  629.   pool = gcp('nocreate') ;  
  630.   if isempty(pool)  
  631.     parpool('local', numGpus) ;  
  632.     cold = true ;  
  633.   end  
  634. end  
  635. if numGpus >= 1 && cold  
  636.   fprintf('%s: resetting GPU\n', mfilename) ;  
  637.   clearMex() ;  
  638.   if numGpus == 1  
  639.     disp(gpuDevice(params.gpus)) ;  
  640.   else  
  641.     spmd  
  642.       clearMex() ;  
  643.       disp(gpuDevice(params.gpus(labindex))) ;  
  644.     end  
  645.   end  
  646. end  



 

 

本文为原创文章转载必须注明本文出处以及附上 本文地址超链接  以及 博主博客地址:http://blog.csdn.net/qq_20259459  和 作者邮箱( jinweizhi93@gmai.com )。

(如果喜欢本文,欢迎大家关注我的博客或者动手点个赞,有需要可以邮件联系我)

 

posted @ 2018-04-01 22:00  菜鸡一枚  阅读(1460)  评论(0)    收藏  举报