DeepLearnToolBox中CNN源碼解析

來源:互聯網
上載者:User

標籤:cnn   源碼解析   

         DeepLearnToolbox是一個簡單理解CNN過程的工具箱,可以在github下載。為了理解卷積神經網路的過程,我特此對CNN部分源碼進行了注釋。公式的計算可以由上一篇blog推導得出。

         注意:代碼中沒有的subsampling進行設定參數,將subsampling層的參數w就設定為了0.25,而偏置參數b設定為0。卷積層計算過程為上一層所有feature map的卷積的結果和,後再加一個偏置,再取sigmoid函數。而subsampling的計算過程為上一層對應的2*2的feature map的像素值求和再取平均,沒有加上偏置和取sigmoid。

 

此外net中一些參數進行說明:

net.fv: 最後一層隱藏層的特徵矩陣,採用的是全串連方式

net.o: 最後輸出的結果,每一列為一個樣本結果

net.od: 最後一層輸出層所對應的殘差

net.fvd: 最後一層隱藏層所對應的誤差(全串連的方式)

 

test_example_CNN.m

 

%function test_example_CNNaddpath D:\DeepLearning\DeepLearnToolbox-master\dataaddpath D:\DeepLearning\DeepLearnToolbox-master\CNNaddpath D:\DeepLearning\DeepLearnToolbox-master\utilload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;   % 訓練集變成60000張28*28的圖片大小 28*28*60000,像素點歸一化到[0,1]test_x = double(reshape(test_x',28,28,10000))/255;      %  測試集   28*28*10000train_y = double(train_y');   %10*6000   每列代表一個標籤  softmax迴歸模型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% errorrand('state',0)cnn.layers = {        %%% 設定各層feature maps個數及卷積模板大小等屬性    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};opts.alpha = 0.01;   %迭代下降的速率opts.batchsize = 50;   %每次選擇50個樣本進行更新  隨機梯度下降,每次只選用50個樣本進行更新opts.numepochs = 50;   %迭代次數cnn = cnnsetup(cnn, train_x, train_y);      %對各層參數進行初始化 包括權重和偏置cnn = cnntrain(cnn, train_x, train_y, opts);  %訓練的過程,包括bp演算法及迭代過程[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);% assert(er<0.12, 'Too big error');

cnnsetup.m

 

function net = cnnsetup(net, x, y)%     assert(~isOctave() || compare_versions(OCTAVE_VERSION, '3.8.0', '>='), ['Octave 3.8.0 or greater is required for CNNs as there is a bug in convolution in previous versions. See http://savannah.gnu.org/bugs/?39314. Your version is ' myOctaveVersion]);    inputmaps = 1;   %輸入圖片數量 輸入feature maps數量    mapsize = size(squeeze(x(:, :, 1)));    % 圖片的大小 squeeze 要不要都行28 28    for l = 1 : numel(net.layers)   %  layer        if strcmp(net.layers{l}.type, 's')            mapsize = mapsize / net.layers{l}.scale;    %% sumsampling的featuremap長寬都是上一層卷積層featuremap的一半            assert(all(floor(mapsize)==mapsize), ['Layer ' num2str(l) ' size must be integer. Actual: ' num2str(mapsize)]);            for j = 1 : inputmaps                net.layers{l}.b{j} = 0;   % 將偏置初始化0, 權重weight,,這段代碼subsampling層將weight設為1/4 而偏置參數設為0,故subsampling階段無需參數            end        end        if strcmp(net.layers{l}.type, 'c')            mapsize = mapsize - net.layers{l}.kernelsize + 1;   % 得到當前層feature map的大小            fan_out = net.layers{l}.outputmaps * net.layers{l}.kernelsize ^ 2;   % fan_out與fan_in都是用來初始化kernel的,不知道why             for j = 1 : net.layers{l}.outputmaps  %  output map  當前層feature maps的個數                fan_in = inputmaps * net.layers{l}.kernelsize ^ 2;                for i = 1 : inputmaps  %  input map          共用權值,故kernel參數個數為inputmaps*outputmaps個數,每一個都是5*5                    net.layers{l}.k{i}{j} = (rand(net.layers{l}.kernelsize) - 0.5) * 2 * sqrt(6 / (fan_in + fan_out));   %% 初始化每個feature map對應的kernel參數 -0.5 再乘2歸一化到[-1,1],最終歸一化到[-sqrt(6 / (fan_in + fan_out)),+sqrt(6 / (fan_in + fan_out))] why??                 end                net.layers{l}.b{j} = 0;  % 初始話feture map對應的偏置參數 初始化為0            end            inputmaps = net.layers{l}.outputmaps;   % 修改輸入feature maps的個數以便下次使用        end    end    % 'onum' is the number of labels, that's why it is calculated using size(y, 1). If you have 20 labels so the output of the network will be 20 neurons.    % 'fvnum' is the number of output neurons at the last layer, the layer just before the output layer.    % 'ffb' is the biases of the output neurons.    % 'ffW' is the weights between the last layer and the output neurons. Note that the last layer is fully connected to the output layer, that's why the size of the weights is (onum * fvnum)    fvnum = prod(mapsize) * inputmaps;             % S4最後結點個數即為特徵的個數 用作全串連 12*4*4=192維特徵    onum = size(y, 1);        %最終分類的個數  10類    net.ffb = zeros(onum, 1);     %softmat迴歸的偏置參數個數    net.ffW = (rand(onum, fvnum) - 0.5) * 2 * sqrt(6 / (onum + fvnum));    %% softmaxt迴歸的權值參數 為10*192個 全串連end

cnntrain.m

 

function net = cnntrain(net, x, y, opts)    m = size(x, 3);   %% 圖片一共的數量 60000    numbatches = m / opts.batchsize;    % 迴圈的次數 共1200次,每次使用50個樣本進行    if rem(numbatches, 1) ~= 0        error('numbatches not integer');    end    net.rL = [];    for i = 1 : opts.numepochs            disp(['epoch ' num2str(i) '/' num2str(opts.numepochs)]);        tic;        kk = randperm(m);  %% 隨機產生m以內的不重複的m個數        for l = 1 : numbatches    %% 迴圈1200次,每次選取50個樣本進行更新            batch_x = x(:, :, kk((l - 1) * opts.batchsize + 1 : l * opts.batchsize));    %50個樣本的訓練資料            batch_y = y(:,    kk((l - 1) * opts.batchsize + 1 : l * opts.batchsize));    %50個樣本所對應的標籤            net = cnnff(net, batch_x);        %計算前向傳播            net = cnnbp(net, batch_y);      %bp演算法更新參數            opts.i = i;            opts.l = l;            net = cnnapplygrads(net, opts);   %% 運用梯度迭代更新參數            if isempty(net.rL)                net.rL(1) = net.L;            end            net.rL(end + 1) = 0.99 * net.rL(end) + 0.01 * net.L;   %為什麼要這樣計算不太明白 net.L為每次迭代時候的cost function        end        toc;    end    end

cnnff.m

function net = cnnff(net, x)    n = numel(net.layers);    %% 所具有的層數    net.layers{1}.a{1} = x;    %第一層的激勵值初始化    inputmaps = 1;    for l = 2 : n   %  for each layer        %針對每一個卷積層        if strcmp(net.layers{l}.type, 'c')            %  !!below can probably be handled by insane matrix operations            for j = 1 : net.layers{l}.outputmaps   %  for each output map %針對該層的每一個feture map                %  create temp output map                z = zeros(size(net.layers{l - 1}.a{1}) - [net.layers{l}.kernelsize - 1 net.layers{l}.kernelsize - 1 0]);   % 該層feture map的大小,最後一位是樣本圖片個數 初始化為0                for i = 1 : inputmaps   %  for each input map  %針對每一個輸入feature map                    %  convolve with corresponding kernel and add to temp output map                    z = z + convn(net.layers{l - 1}.a{i}, net.layers{l}.k{i}{j}, 'valid');  %做卷積操作  k{i}{j} 是5*5的double類型,其中a{i}是輸入圖片的feature map 大小為28*28*50 50為映像數量                end                                                                         %% 卷積操作這裡的k是不是應該旋轉180度                %  add bias, pass through nonlinearity                net.layers{l}.a{j} = sigm(z + net.layers{l}.b{j});   %%擷取sigmoid function的值              end            %  set number of input maps to this layers number of outputmaps            inputmaps = net.layers{l}.outputmaps;   %% 設定新的輸入feature maps的個數            elseif strcmp(net.layers{l}.type, 's')   %%% 下採樣採用的方法是,2*2相加乘以權值1/4,  沒有取偏置和取sigmoid            %  downsample            for j = 1 : inputmaps                z = convn(net.layers{l - 1}.a{j}, ones(net.layers{l}.scale) / (net.layers{l}.scale ^ 2), 'valid');   %  !! replace with variable   %%先卷積後各行各列取結果                net.layers{l}.a{j} = z(1 : net.layers{l}.scale : end, 1 : net.layers{l}.scale : end, :);    %得到的結果是上一層卷積層行列的一半  a=z            end        end    end    %  concatenate all end layer feature maps into vector    net.fv = [];   %%用來儲存最後一個隱藏層所對應的特徵 將feature maps變成全串連的形式    for j = 1 : numel(net.layers{n}.a)      % 最後一層隱層具有的feture map數量        sa = size(net.layers{n}.a{j});        net.fv = [net.fv; reshape(net.layers{n}.a{j}, sa(1) * sa(2), sa(3))];  %% 最後得到192*50的矩陣,每一列對應一個樣本映像的特徵,192=4*4*12 12個feturemap     end    %  feedforward into output perceptrons    net.o = sigm(net.ffW * net.fv + repmat(net.ffb, 1, size(net.fv, 2)));    %% 結果為10*50的矩陣,每一列表示一個樣本映像的標籤結果 取了sigmoid function表明是k個二分類器,各類之間不互斥,當然也可以換成softmax迴歸   % net.o = softmax(net.ffW * net.fv + repmat(net.ffb, 1, size(net.fv, 2))); end
 

cnnbp.m

 

function net = cnnbp(net, y)    n = numel(net.layers);    %layers個數    %   error    net.e = net.o - y;   % 10*50  每一列表示一個樣本映像    %  loss function    net.L = 1/2* sum(net.e(:) .^ 2) / size(net.e, 2);   %% cost function 沒有加入參數構成貝葉斯學派的觀點    %%  backprop deltas    net.od = net.e .* (net.o .* (1 - net.o));   %  output delta 輸出層的誤差 用來求解  10*50    net.fvd = (net.ffW' * net.od);              %  feature vector delta  最後一層隱藏層誤差 如果是下採樣層,由於a=z,所以誤差就是這個結果(導數為1,就是對z求導),如果是卷積層,那麼需要乘以f(z)的導數 192*50    if strcmp(net.layers{n}.type, 'c')         %  only conv layers has sigm function        net.fvd = net.fvd .* (net.fv .* (1 - net.fv));     %% 如果最後一個隱藏層是卷積層,直接用該公式就能得到誤差    end    %  reshape feature vector deltas into output map style    sa = size(net.layers{n}.a{1});    %%layers{n}共有12個a 每個a都是4*4*50  50 為樣本圖片的個數   n表示最後一層隱藏層    fvnum = sa(1) * sa(2);    for j = 1 : numel(net.layers{n}.a)   %%最後一個隱藏層一共有多少個feature maps,每個feature map即表示為d{j}變成4*4*50的形式,50為樣本圖片數量,這樣好用於計算前面層次的誤差**** 轉變        net.layers{n}.d{j} = reshape(net.fvd(((j - 1) * fvnum + 1) : j * fvnum, :), sa(1), sa(2), sa(3));   %將最後一層隱藏層變成feature maps的形式,這樣易求解前一層卷積的結果    end    for l = (n - 1) : -1 : 1      %實際是到2終止了,1是輸入層,沒有誤差要求        if strcmp(net.layers{l}.type, 'c')   %卷積層的計算方式            for j = 1 : numel(net.layers{l}.a)   %第n-1層具有的feature maps的個數,進行遍曆 每個d{j}是8*8*50的形式, 由於下一層為下採樣層,故後一層d{j}擴充為8*8的(每個點複製成2*2的),按照bp求誤差公式就可以得出,這裡權重就為1/4,                net.layers{l}.d{j} = net.layers{l}.a{j} .* (1 - net.layers{l}.a{j}) .* (expand(net.layers{l + 1}.d{j}, [net.layers{l + 1}.scale net.layers{l + 1}.scale 1]) / net.layers{l + 1}.scale ^ 2);            end        elseif strcmp(net.layers{l}.type, 's')   %下採樣層的計算方式            for i = 1 : numel(net.layers{l}.a)   %該層feature maps的個數 每個a都是12*12*50 的大小,其中50為樣本圖片的個數                z = zeros(size(net.layers{l}.a{1}));      %大小等於 當前層feature map的大小                for j = 1 : numel(net.layers{l + 1}.a)     %計算公式來自 Notes on Convolutional Neural Networks的pdf,,將當前層下採樣層與後面的採樣層每個feature map相串連, 故按照bp的公式要進行求和                     z = z + convn(net.layers{l + 1}.d{j}, rot180(net.layers{l + 1}.k{i}{j}), 'full');   %%% 可以舉一個簡單的例子進行講解  所有節點相乘都是相加的(因為該結點是與後一層所有的feature maps都是有串連的),                end                                                                                      %% 卷積 full valid是什麼意思 要弄清楚????                net.layers{l}.d{i} = z;          %% 因為是下採樣層,所以a=z,就f(z)=z,導數就等於1,所以誤差就是所串連結點權值與後一層誤差和            end        end    end    %%  calc gradients    %% 對kij求偏導沒有看懂 為什麼要進行求和    for l = 2 : n        if strcmp(net.layers{l}.type, 'c')            for j = 1 : numel(net.layers{l}.a)                for i = 1 : numel(net.layers{l - 1}.a)                    net.layers{l}.dk{i}{j} = convn(flipall(net.layers{l - 1}.a{i}), net.layers{l}.d{j}, 'valid') / size(net.layers{l}.d{j}, 3);   % 可以看論文中的推導!與論文中先將k rot180,然後再rot整體效果是一樣的。                end                net.layers{l}.db{j} = sum(net.layers{l}.d{j}(:)) / size(net.layers{l}.d{j}, 3);   %% 對偏置參數b的導數            end        end    end    net.dffW = net.od * (net.fv)' / size(net.od, 2);      %softmax迴歸中參數所對應的導數    net.dffb = mean(net.od, 2);                %% softmax迴歸中最後參數b所對應的導數    function X = rot180(X)        X = flipdim(flipdim(X, 1), 2);  % flipdim(X, 1) 行互換  flipdim(X, 2) 列互換    endend

cnnapplygrads.m

function net = cnnapplygrads(net, opts)    for l = 2 : numel(net.layers)        if strcmp(net.layers{l}.type, 'c')            for j = 1 : numel(net.layers{l}.a)                for ii = 1 : numel(net.layers{l - 1}.a)                    net.layers{l}.k{ii}{j} = net.layers{l}.k{ii}{j} - 1/(opts.i+opts.alpha + opts.l) * net.layers{l}.dk{ii}{j};   %% 梯度下降求更新後的參數                end                net.layers{l}.b{j} = net.layers{l}.b{j} - 1/(opts.i+opts.alpha + opts.l) * net.layers{l}.db{j};            end        end    end    net.ffW = net.ffW - 1/(opts.i+opts.alpha + opts.l) * net.dffW;    net.ffb = net.ffb - 1/(opts.i+opts.alpha + opts.l) * net.dffb;end


cnntest.m

 

function [er, bad] = cnntest(net, x, y)    %  feedforward    net = cnnff(net, x);    [~, h] = max(net.o);    [~, a] = max(y);    bad = find(h ~= a);    er = numel(bad) / size(y, 2);end

將代碼中opts.numepochs 迭代次數設為1和10分別獲得了11.13%和2.73%的錯誤率。

將最後一層的分類迴歸改為softmax迴歸得到的錯誤率為16.01%和5.10%。當然這裡修改迭代次數即下降的速率可能會得到更佳的效果!

DeepLearnToolBox中CNN源碼解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.