Wednesday, 5 December 2018

testDNN analysis 11

% GetOnInd: get indexes which are used (not dropped) nodes
%
% OnInd = GetOnInd( dbn, DropOutRate, strbm )
%
%
%Output parameters:
% OnInd: indexes which are used (not dropped) nodes
%
%
%Input parameters:
% dbn: the Original Deep Belief Nets (DBN) model
% DropOutRate: 0 < DropOutRate < 1
% strbm (optional): started rbm layer to dropout (Default: 1)
%
%
%Reference:
%for details of the dropout
% Hinton et al, Improving neural networks by preventing co-adaptation of feature detectors, 2012.
%
%
%Version: 20130821

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function OnInd = GetOnInd( dbn, DropOutRate, strbm ) % ... , 3 x 1, 1

if( ~exist('strbm', 'var') || isempty(strbm) )
strbm = 1;
end

OnInd = cell(numel(dbn.rbm),1); % 3, 1

for n=1:numel(dbn.rbm) % 1:3
    dimV = size(dbn.rbm{n}.W,1); % 32->16->8
    if( n >= strbm )
        OnNum = round(dimV*DropOutRate(n)); % 16->8->4 DropOutRate 0.7 would cause OnNum=22 -->22 x 32 as OnInd{1}
        OnInd{n} = sort(randperm(dimV, OnNum)); % OnNum integers btw 1 and dimV -->randperm(32 x 16, 16 x 8, 8 x 4) = 16 x 32, 8 x 16, 4 x 8
    else
        OnInd{n} = 1:dimV; %1 2 3 4 5 6 7 8
    end
end

%{
randperm (n)
randperm (n, m)
Return a row vector containing a random permutation of 1:n.
If m is supplied, return m permutations, one in each row of an MxN matrix

octave:1> randperm(8,4)
ans =

   1   6   2   8   4   5   3   7
   3   1   6   2   5   4   7   8
   4   6   8   7   5   1   2   3
   2   8   5   7   1   6   4   3

octave:2> sort(randperm(8,4))
ans =

   1   3   2   4   1   6   1   2
   2   3   5   5   2   6   1   4
   5   3   8   6   3   7   4   4
   8   6   8   7   7   7   8   5

%}
%{
debug> aa=[1,2,3,4;5,6,7,8;9,10,11,12]
debug> aa
aa =

    1    2    3    4
    5    6    7    8
    9   10   11   12

debug> bb
bb =

   1   1
   2   2
   3   3
   4   4

debug> cc
cc =

   1
   1

debug> aa(cc,bb)
ans =

   1   2   3   4   1   2   3   4
   1   2   3   4   1   2   3   4

debug> aa
aa = 3 x 4

    1    2    3    4
    5    6    7    8
    9   10   11   12

debug> aa(bb)
ans =

   1   1
   5   5
   9   9
   2   2
debug> bb
bb =  2 x 4

   1   1
   2   2
   3   3
   4   4

debug> dd
dd = 1 x 2

   1
   2

debug> aa(dd,bb) 2 x 8
ans =

   1   2   3   4   1   2   3   4
   5   6   7   8   5   6   7   8

%}

testDNN analysis 10

% v2hall: to transform from visible (input) variables to all hidden (output) variables
%
% Hall = h2val(dnn, V)
%
%
%Output parameters:
% Hall: all hidden (output) variables, where # of row is number of data and # of col is # of hidden (output) nodes
%
%
%Input parameters:
% dnn: the Deep Neural Network model (dbn, rbm)
% V: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes
%
%
%Version: 20130727

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Hall = v2hall(dnn, V) %  dnn.rbm{i}(512 x 128, 128 x 132, 32 x 4), V(250 x 512)

if( isequal(dnn.type(3:5), 'RBM') ) % BBRBM
    Hall = cell(1,1);
    Hall{1} = sigmoid( bsxfun(@plus, V * dnn.W, dnn.b ) );

elseif( isequal(dnn.type(3:5), 'DBN') ) % BBDBN
    nrbm = numel( dnn.rbm ); % 3
    Hall = cell(nrbm,1); % 3 x 1
    H0 = V; % 1000 x 32  , 250 x 512

    for i=1:nrbm % 1:3
        H1 = v2h( dnn.rbm{i}, H0 ); % dnn.rbm{i}.type = BBRBM
        H0 = H1;
        Hall{i} = H1; % 1000 x 4(i=3) <- 1000="" 128="" 16="" 250="" 32="" 4="" 8="" i="1) " nbsp="" p="" x="">
    end
end


testDNN analysis 9

% v2h: to transform from visible (input) variables to hidden (output) variables
%
% H = h2v(dnn, V)
%
%
%Output parameters:
% H: hidden (output) variables, where # of row is number of data and # of col is # of hidden (output) nodes
%
%
%Input parameters:
% dnn: the Deep Neural Network model (dbn, rbm)
% V: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes
%
%
%Example:
% datanum = 1024;
% outputnum = 16;
% inputnum = 4;
%
% inputdata = rand(datanum, outputnum);
%
% dnn = randRBM( inputnum, outputnum );
% outputdata = v2h( dnn, input );
%
%
%Version: 20130727


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function H = v2h(dnn, V) % V(1000 x 32, 250 x 32)   dnn.rbm{i}.W(32 x 16)(16 x 8) (8 x 4)

if( isequal(dnn.type, 'BBRBM') ) % BBDBN    Bernoulli-Bernoulli Restricted Bolztmann Machine
    H = sigmoid( bsxfun(@plus, V * dnn.W, dnn.b ) ); % H(250 x 16) * (32 x 16) = 250 x 16
% 250 x 512 * 512 x 128 = 250 x 128

elseif( isequal(dnn.type, 'GBRBM') ) % BBDBN Gaussian-Bernoulli Restricted Bolztmann Machine
    v = bsxfun(@rdivide, V, dnn.sig );
    H = sigmoid( bsxfun(@plus, v * dnn.W, dnn.b ) ); 

elseif( isequal(dnn.type(3:5), 'DBN') ) % BBDBN
    nrbm = numel( dnn.rbm ); % 3
    H0 = V; % 1000 x 32, 250 x 32, 250 x 512
    for i=1:nrbm
        H1 = v2h( dnn.rbm{i}, H0 ); % 1000 x 32, 250 x 32    dnn.rbm{i}.type = BBRBM dnn.rbm{i}.W(32 x 16)(16 x 8) (8 x 4)
        H0 = H1; % 1000 x 4 <- 1000x16="" 1000x8="" 250="" 250x16="" 250x8="" 4="" p="" x="">    end
    H = H1; % 1000 x 4
end

testDNN analysis 8

% trainDBN: training the Deep Belief Nets (DBN) model by back projection algorithm
%
% [dbn rmse] = trainDBN( dbn, IN, OUT, opts)
%
%
%Output parameters:
% dbn: the trained Deep Belief Nets (DBN) model
% rmse: the rmse between the teaching data and the estimates
%
%
%Input parameters:
% dbn: the initial Deep Belief Nets (DBN) model
% IN: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes % 1000 x 32
% OUT: teaching hidden (output) variables, where # of row is number of data and # of col is # of hidden (output) nodes % 1000 x 4
% opts (optional): options
%
% options (defualt value):
%  opts.LayerNum: # of tarining RBMs counted from output layer (all layer)
%  opts.MaxIter: Maxium iteration number (100)
%  opts.InitialMomentum: Initial momentum until InitialMomentumIter (0.5)
%  opts.InitialMomentumIter: Iteration number for initial momentum (5)
%  opts.FinalMomentum: Final momentum after InitialMomentumIter (0.9)
%  opts.WeightCost: Weight cost (0.0002)
%  opts.DropOutRate: List of Dropout rates for each layer (0)
%  opts.StepRatio: Learning step size (0.01)
%  opts.BatchSize: # of mini-batch data (# of all data)
%  opts.Object: specify the object function ('Square')
%              'Square'
%              'CrossEntorpy'
%  opts.Verbose: verbose or not (false)
%
%
%Example:
% datanum = 1024;
% outputnum = 16;
% hiddennum = 8;
% inputnum = 4;
%
% inputdata = rand(datanum, inputnum);
% outputdata = rand(datanum, outputnum);
%
% dbn = randDBN([inputnum, hiddennum, outputnum]);
% dbn = pretrainDBN( dbn, inputdata );
% dbn = SetLinearMapping( dbn, inputdata, outputdata );
% dbn = trainDBN( dbn, inputdata, outputdata );
%
% estimate = v2h( dbn, inputdata );
%
%
%Reference:
%for details of the dropout
% Hinton et al, Improving neural networks by preventing co-adaptation of feature detectors, 2012.
%
%
%Version: 20131204

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dbn rmse] = trainDBN( dbn, IN, OUT, opts)

% Important parameters
InitialMomentum = 0.5;     % momentum for first five iterations
FinalMomentum = 0.9;       % momentum for remaining iterations
WeightCost = 0.0002;       % costs of weight update
InitialMomentumIter = 5;

MaxIter = 100;
StepRatio = 0.01;
BatchSize = 0;
Verbose = false;

Layer = 0;
strbm = 1;

nrbm = numel( dbn.rbm ); % 3
DropOutRate = zeros(nrbm,1); % 3 x 1

OBJECTSQUARE = 1;
OBJECTCROSSENTROPY = 2;
Object = OBJECTSQUARE; % 1

if( exist('opts' ) )
 if( isfield(opts,'MaxIter') )
  MaxIter = opts.MaxIter;
 end
 if( isfield(opts,'InitialMomentum') )
  InitialMomentum = opts.InitialMomentum;
 end
 if( isfield(opts,'InitialMomentumIter') )
  InitialMomentumIter = opts.InitialMomentumIter;
 end
 if( isfield(opts,'FinalMomentum') )
  FinalMomentum = opts.FinalMomentum;
 end
 if( isfield(opts,'WeightCost') )
  WeightCost = opts.WeightCost;
 end
 if( isfield(opts,'DropOutRate') )
  DropOutRate = opts.DropOutRate;
  if( numel(DropOutRate) == 1 )
      DropOutRate = ones(nrbm,1) * DropOutRate;
  end
 end
 if( isfield(opts,'StepRatio') )
  StepRatio = opts.StepRatio;
 end
 if( isfield(opts,'BatchSize') )
  BatchSize = opts.BatchSize;
 end
 if( isfield(opts,'Verbose') )
  Verbose = opts.Verbose;
 end
 if( isfield(opts,'Layer') )
  Layer = opts.Layer;
 end
 if( isfield(opts,'Object') )
  if( strcmpi( opts.object, 'Square' ) )
   Object = OBJECTSQUARE;
  elseif( strcmpi( opts.object, 'CrossEntropy' ) )
   Object = OBJECTCROSSENTROPY;
  end
 end
end

num = size(IN,1); % 1000
if( BatchSize <= 0 ) % 250
  BatchSize = num;
end

if( Layer > 0 ) % 0  <- strbm="1</p">    strbm = nrbm - Layer + 1;
end

deltaDbn = dbn;
for n=strbm:nrbm % 1:3
    deltaDbn.rbm{n}.W = zeros(size(dbn.rbm{n}.W)); % 32 x 16, 16 x 8, 8 x 4
    deltaDbn.rbm{n}.b = zeros(size(dbn.rbm{n}.b)); % 1x16, 1 x 8, 1 x 4
end

if( Layer > 0 ) % 0
    strbm = nrbm - Layer + 1;
end

if( sum(DropOutRate > 0) ) % 1 x 1
    OnInd = GetOnInd( dbn, DropOutRate, strbm ); % 3 x 1 {16 x 32, 8 x 16, 4 x 8}
    for n=max([2,strbm]):nrbm % 2:3
        dbn.rbm{n}.W = dbn.rbm{n}.W / numel(OnInd{n-1}) * size(dbn.rbm{n-1}.W,2);
% 16 x 8                    / 512(=16*32) * 16(32 x 16)
% 8 x 4 = (dbn.rbm{n}.W(8 x 4) / 128(=8*16)) * 8(16 x 8)
    end
end

for iter=1:MaxIter % 1:20
     
    % Set momentum
if( iter <= InitialMomentumIter )
momentum = InitialMomentum; % 0.5
else
momentum = FinalMomentum; % 0.9
    end
   
ind = randperm(num); % 1 x 1000 num=1000 random numbers with values upto 1000
for batch=1:BatchSize:num % 1:250:1000   1 251 501 751
bind = ind(batch:min([batch + BatchSize - 1, num])); % 1 x 250 <-- -="" ind="" min="">ind(1:250)   batch==1
% extract num of Batchsize items or if less upto the upper limit num
        % bind(1:10)= 166 919 119 895 754 24 500 318 249 659
        trainDBN = dbn;
        if( DropOutRate > 0 )
    % 1 x 1 ->  trainDBN.rbm{i}(16 x 32, 8 x 16, 4 x 8)
            [trainDBN OnInd] = GetDroppedDBN( trainDBN, DropOutRate, strbm );
% trainDBN.rbm{i}(512 x 128(n=1), 128 x 32(n=2), 32 x 4(n=3))

            Hall = v2hall( trainDBN, IN(bind,OnInd{1}) );
% IN(1000 x 32) bind(1 x 250) OnInd(16 x 32)
% size(IN(bind,OnInd{1}))-> 250 x 512
% Hall(1->250 x 128, 2->250 x 32, 3->250 x 4)
%  size(IN(bind,OnInd{1}))->(250 x 512)  * trainDBN(512 x 128) * = Hall->250 x 128, 250 x 32, 250 x 4(n=3)
else
             Hall = v2hall( trainDBN, IN(bind,:) ); % IN(1000 x 32) bind(1 x 250)
        end
   
        for n=nrbm:-1:strbm % 3 : -1 : 1
            derSgm = Hall{n} .* ( 1 - Hall{n} ); %derivative sigmoid 250 x 4(n=3), 250 x 32(n=2), 250 x 1288(n=1)
            if( n+1 > nrbm )
                der = ( Hall{nrbm} - OUT(bind,:) );  %der(250 x 4) Hall{nrbm}(250 x 4) 250 x 4 = OUT(1000 x 4) (bind(1 x 250),:)
                if( Object == OBJECTSQUARE )
                    der = derSgm .* der; % 250 x 4(n=3)
                end
            else
                der = derSgm .* ( der * trainDBN.rbm{n+1}.W' );  % (n=1)(250 x 128 * 32 x 128'), 250 x 32( 250 x 4 * 4 x 32 )(n=2)
            end
           
            if( n-1 > 0 )
                in = Hall{n-1}; % (n=3)250 x 32, (n=2)250 x 128, (n=1)250 x 512, 
            else
                if( DropOutRate > 0 )
                    in = IN(bind,OnInd{1}); %  IN(1000 x 32) bind(1 x 250) OnInd{1}(16 x 32) = 250 x 512(n=3,n=2,n=1)
                else
                    in = IN(bind,:); % 250 x 32(n=3), 250 x 128(n=2), 250 x 512(n=1)
                end
            end
           
            in = cat(2, ones(numel(bind),1), in); %(n=3)250 x 33,(n=2)250 x 129, ones(numel(bind),1)(250 x 1)(250 x 512) = 250 x 513
            deltaWb = in' * der / numel(bind);
% (n=3)33 x 4=250 x 33' * 250 x 4 ,
% 129 x 32 = 250 x 129' * 250 x 32,
% 513 x 128 =250 x 513' * 250 x 128  / 250
            deltab = deltaWb(1,:); % 1 x 4(n=3), 1 x 32, 1 x 128
            deltaW = deltaWb(2:end,:); % 32 x 4(n=3), 128 x 32(n=2), 512 x 128(n=1)
           
            if( strcmpi( dbn.rbm{n}.type, 'GBRBM' ) ) % BBRBM   Gaussian-Binary Restricted Bolztmann
deltaW = bsxfun( @rdivide, deltaW, trainDBN.rbm{n}.sig' );
            end
           
            deltaDbn.rbm{n}.W = momentum * deltaDbn.rbm{n}.W; % 0.5 * 32 x 16(n=1), 16 x 8(n=2), 8 x 4(n=3)
            deltaDbn.rbm{n}.b = momentum * deltaDbn.rbm{n}.b; % 0.5 * 1x16(n=1), 1 x 8(n=2), 1 x 4(n=3)
             
            if( DropOutRate > 0 ) %(0.5, 0.5, 0.5)'
                if( n == nrbm )
                    deltaDbn.rbm{n}.W(OnInd{n},:) = deltaDbn.rbm{n}.W(OnInd{n},:) - StepRatio * deltaW;
% 32 x 4                        32 x 4                           32 x 4
                    deltaDbn.rbm{n}.b = deltaDbn.rbm{n}.b - StepRatio * deltab; % 1 x 4
                else
                    deltaDbn.rbm{n}.W(OnInd{n},OnInd{n+1}) = deltaDbn.rbm{n}.W(OnInd{n},OnInd{n+1}) - StepRatio * deltaW;
% (n=2)128 x 32=(8 x 16,4 x 8) (n=1)512 x 128=(32x16(16x32,8x16))      (n=2)128 x 32 (n=1)512 x 128
                    deltaDbn.rbm{n}.b(1,OnInd{n+1}) = deltaDbn.rbm{n}.b(1,OnInd{n+1}) - StepRatio * deltab;
% 1 x 32(n=2) (n=1)1 x 128(onInd{n+1}=8 x 16)
                end
            else
                deltaDbn.rbm{n}.W = deltaDbn.rbm{n}.W - StepRatio * deltaW;
                deltaDbn.rbm{n}.b = deltaDbn.rbm{n}.b - StepRatio * deltab;
            end
keyboard()
        end
           
        for n=strbm:nrbm           
            dbn.rbm{n}.W = dbn.rbm{n}.W + deltaDbn.rbm{n}.W;
            dbn.rbm{n}.b = dbn.rbm{n}.b + deltaDbn.rbm{n}.b; 
        end
    end
   
    if( Verbose )
        tdbn = dbn;
        if( sum(DropOutRate > 0) )
            OnInd = GetOnInd( tdbn, DropOutRate, strbm );
            for n=max([2,strbm]):nrbm
                tdbn.rbm{n}.W = tdbn.rbm{n}.W * numel(OnInd{n-1}) / size(tdbn.rbm{n-1}.W,2);
            end
        end
        out = v2h( tdbn, IN );
        err = power( OUT - out, 2 );
        rmse = sqrt( sum(err(:)) / numel(err) );
        fprintf( '%3d : %9.4f\n', iter, rmse );
    end
end

if( sum(DropOutRate > 0) )
    OnInd = GetOnInd( dbn, DropOutRate, strbm );
    for n=max([2,strbm]):nrbm
        dbn.rbm{n}.W = dbn.rbm{n}.W * numel(OnInd{n-1}) / size(dbn.rbm{n-1}.W,2);
    end
end

testDNN analysis 7

% linearMaping: calculate the linear mapping matrix between the input data and the output data
%
% M = linearMapping( IN, OUT )
%
%
%Output parameters:
% M: The linear mapping matrix
%
%
%Input parameters:
% IN: input data, where # of row is # of data and # of col is # of input features
% 1 input1 1-4
% 2 input2 1-4
% ...
% 1024 inputn 1-4
% OUT: output data, where # of row is # of data and # of col is # of output labels
% 1 output1 1-16
% 2 output2 1-16
% ...
% 1024 outputn 1-16
%
%Example:
% datanum = 1024;
% outputnum = 16;
% inputnum = 4;
%
% inputdata = rand(datanum, inputnum);                rand(1024,4)
% outputdata = rand(datanum, outputnum);              rand(1024,16)
%
% M = linearMapping(inputdata, outputdata);         1024 x 4, 1024 x 16
%
%
%Version: 20130727

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = linearMapping( IN, OUT ) % IN 1000 x 8 OUT 1000 x 4
M = pinv(IN) * OUT; % 8 x 1000 * 1000 x 4 = 8 x 4

%OUT = IN * M;

testDNN analysis 6

% SetLinearMapping: set the RBM associated to the linear mapping to the last layer
%
% dbn = SetLinearMapping( dbn, IN, OUT )
%
%
%Input parameters:
% dbn: the Deep Belief Nets (DBN) model
% IN: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes
% OUT: teaching data, where # of row is number of data and # of col is # of hidden (output) nodes
%
%
%Output parameters:
% dbn: the set Deep Belief Nets (DBN) model
%
%
%Example:
% datanum = 1024;
% outputnum = 16;
% hiddennum = 8;
% inputnum = 4;
%
% inputdata = rand(datanum, inputnum);
% outputdata = rand(datanum, outputnum);
%
% dbn = randDBN([inputnum, hiddennum, outputnum]);
% dbn = pretrainDBN( dbn, inputdata );
% dbn = SetLinearMapping( dbn, inputdata, outputdata );
% dbn = trainDBN( dbn, inputdata, outputdata );
%
% estimate = v2h( dbn, inputdata );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dbn = SetLinearMapping( dbn, IN, OUT ) % 1000 x 32 , 1000 x 4
nrbm = numel(dbn.rbm);
if( nrbm > 1 ) % 3
    Hall = v2hall( dbn, IN ); % 3 x 1 Hall{1}->1000 x 16, 1000 x 8, 1000 x 4
    dbn.rbm{nrbm}.W = linearMapping( Hall{nrbm-1}, OUT ); % 1000 x 8, 1000 x 4 = 8 x 4
    dbn.rbm{nrbm}.b = -0.5 * ones(size(dbn.rbm{nrbm}.b)); % 1 x 4
else
    dbn.rbm{nrbm}.W = linearMapping( IN, OUT );
    dbn.rbm{nrbm}.b = -0.5 * ones(size(dbn.rbm{nrbm}.b));
end

testDNN analysis 5

% pretrainRBM: pre-training the restricted boltzmann machine (RBM) model by Contrastive Divergence Learning
%
% rbm = pretrainRBM(rbm, V, opts)
%
%
%Output parameters:
% rbm: the restricted boltzmann machine (RBM) model
%
%
%Input parameters:
% rbm: the initial boltzmann machine (RBM) model
% V: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes
% opts (optional): options
%
% options (defualt value):
%  opts.MaxIter: Maxium iteration number (100)
%  opts.InitialMomentum: Initial momentum until InitialMomentumIter (0.5)
%  opts.InitialMomentumIter: Iteration number for initial momentum (5)
%  opts.FinalMomentum: Final momentum after InitialMomentumIter (0.9)
%  opts.WeightCost: Weight cost (0.0002)
%  opts.DropOutRate: Dropour rate (0)
%  opts.StepRatio: Learning step size (0.01)
%  opts.BatchSize: # of mini-batch data (# of all data)
%  opts.Verbose: verbose or not (false)
%  opts.SparseQ: q parameter of sparse learning (0)
%  opts.SparseLambda: lambda parameter (weight) of sparse learning (0)
%
%
%Example:
% datanum = 1024;
% outputnum = 16;
% inputnum = 4;
%
% inputdata = rand(datanum, inputnum);
% outputdata = rand(datanum, outputnum);
%
% rbm = randRBM(inputnum, outputnum);
% rbm = pretrainRBM( rbm, inputdata );
%
%
%Reference:
%for details of the dropout
% Hinton et al, Improving neural networks by preventing co-adaptation of feature detectors, 2012.
%for details of the sparse learning
% Lee et al, Sparse deep belief net model for visual area V2, NIPS 2008.
%for implimentation of contrastive divergence learning
% http://read.pudn.com/downloads103/sourcecode/math/421402/drtoolbox/techniques/train_rbm.m__.htm
%
%
%Version: 20130727


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rbm = pretrainRBM(rbm, V, opts )

% Important parameters
InitialMomentum = 0.5;     % momentum for first five iterations
FinalMomentum = 0.9;       % momentum for remaining iterations
WeightCost = 0.0002;       % costs of weight update
InitialMomentumIter = 5;

MaxIter = 100;
DropOutRate = 0;
StepRatio = 0.01;
BatchSize = 0;
Verbose = false;

SparseQ = 0;
SparseLambda = 0;


if( exist('opts' ) )
 if( isfield(opts,'MaxIter') )
  MaxIter = opts.MaxIter;
 end
 if( isfield(opts,'InitialMomentum') )
  InitialMomentum = opts.InitialMomentum;
 end
 if( isfield(opts,'InitialMomentumIter') )
  InitialMomentumIter = opts.InitialMomentumIter;
 end
 if( isfield(opts,'FinalMomentum') )
  FinalMomentum = opts.FinalMomentum;
 end
 if( isfield(opts,'WeightCost') )
  WeightCost = opts.WeightCost;
 end
 if( isfield(opts,'DropOutRate') )
  DropOutRate = opts.DropOutRate;
 end
 if( isfield(opts,'StepRatio') )
  StepRatio = opts.StepRatio;
 end
 if( isfield(opts,'BatchSize') )
  BatchSize = opts.BatchSize;
 end
 if( isfield(opts,'Verbose') )
  Verbose = opts.Verbose;
 end
 if( isfield(opts,'SparseQ') )
  SparseQ = opts.SparseQ;
 end
 if( isfield(opts,'SparseLambda') )
  SparseLambda = opts.SparseLambda;
 end

else
 opts = [];
end

num = size(V,1); % 1000 x 32
dimH = size(rbm.b, 2); % 16
dimV = size(rbm.c, 2); % 32

if( BatchSize <= 0 ) % 250
  BatchSize = num;
end

if( DropOutRate > 0 )
    DropOutNum = round(dimV * DropOutRate); % 32 * 0.5
    DropOutRate = DropOutNum / num;  % 0.016
end


deltaW = zeros(dimV, dimH); % 32 x 16
deltaB = zeros(1, dimH); % 1 x 16
deltaC = zeros(1, dimV); % 1 x 32

for iter=1:MaxIter % 1:20
         
    % Set momentum
if( iter <= InitialMomentumIter )
momentum = InitialMomentum; % 0.500
else
momentum = FinalMomentum; % 0.9XXX
    end
               
    if( SparseLambda > 0 ) % 0
        dsW = zeros(dimV, dimH); % 32 x 16
        dsB = zeros(1, dimH); % 1 x 16
           
        vis0 = V; % 250 % 32
        hid0 = v2h( rbm, vis0 ); % 250 x 16
           
        dH = hid0 .* ( 1.0 - hid0 ); %derivative hidden  % 250 x 16
        sH = sum( hid0, 1 ); % sum of columns of each row % 1 x 16
    end
                   
    if( SparseLambda > 0 ) %0
        mH = sH / num; % sH/1000 or 250   1 x 16
        sdH = sum( dH, 1 ); % sum of derivative hidden columns of each row 1 x 16
        svdH = dH' * vis0;  % derivative hidden' times vis0 16 x 250 * 250 x 32 = 16 x 32
             
        dsW = dsW + SparseLambda * 2.0 * bsxfun(@times, (SparseQ-mH)', svdH)'; % 32 x 16 + (1 x 16' 1 x 32)'
        dsB = dsB + SparseLambda * 2.0 * (SparseQ-mH) .* sdH; % 1 x 16 + 1 x 16 .* 1 x 16 = 1 x 16
    end
       
       
ind = randperm(num); % randperm(1000)

for batch=1:BatchSize:num % 1 251 501 751
         
bind = ind(batch:min([batch + BatchSize - 1, num])); % 1 x 250 = 1 + 249, 1000 -> 1:250 -> ind( randperm(num))
           
        if( DropOutRate > 0 ) % 0.016
            cMat = zeros(dimV,1); % 32 x 1
            p = randperm(dimV, DropOutNum); % randperm(32 x 16)=16 x 32
            cMat(p) = 1;  % 16 x 32     cmat 32 x 1(16 x 32) = 16 x 32  --> cMat(1 x 32) = 1
            cMat = diag(cMat); %32 x 32  diag(32 x 1)
        end
       
        % Gibbs sampling step 0
        vis0 = double(V(bind,:)); % Set values of visible nodes 250 x 32 = 1000 x 32  1 x 250
        if( DropOutRate > 0 ) % 0.016
            vis0 = vis0 * cMat; % 250 x 32 * 32 x 32 = 250 x 32
        end
        hid0 = v2h( rbm, vis0 );  % Compute hidden nodes 250 x 16
       
        % Gibbs sampling step 1
        bhid0 = double( rand(size(hid0)) < hid0 ); % 250 x 16
        vis1 = h2v( rbm, bhid0 );  % Compute visible nodes % 250 x 32
        if( DropOutRate > 0 )  % 0.016
            vis1 = vis1 * cMat;% 250 x 32 * 32 x 32 = 250 x 32
        end
        hid1 = v2h( rbm, vis1 );  % Compute hidden nodes 250 x 16
       
posprods = hid0' * vis0; % 250 x 16' * 250 x 32 = 16 x 32
negprods = hid1' * vis1; % 250 x 16' * 250 x 32 = 16 x 32
% Compute the weights update by contrastive divergence
       
        dW = (posprods - negprods)'; %16 x 32'
        dB = (sum(hid0, 1) - sum(hid1, 1)); % 1 x 16
        dC = (sum(vis0, 1) - sum(vis1, 1)); % 1 x 32
     
        if( strcmpi( 'GBRBM', rbm.type ) ) % BBRBM   Gaussian-Binary Restricted Bolztmann
        dW = bsxfun(@rdivide, dW, rbm.sig');
        dC = bsxfun(@rdivide, dC, rbm.sig .* rbm.sig);
        end
       
deltaW = momentum * deltaW + (StepRatio / num) * dW; % 0.1/1000    32 x 16
deltaB = momentum * deltaB + (StepRatio / num) * dB; % 0.1/1000    1 x 16
deltaC = momentum * deltaC + (StepRatio / num) * dC; % 0.1/1000    1 x 32
         
        if( SparseLambda > 0 ) % 0
            deltaW = deltaW + numel(bind) / num * dsW;
            deltaB = deltaB + numel(bind) / num * dsB;
        end
       
% Update the network weights
rbm.W = rbm.W + deltaW - WeightCost * rbm.W; % 32 x 16   0.0002
rbm.b = rbm.b + deltaB; % 1 x 16
rbm.c = rbm.c + deltaC; % 1 x 32
     
end
       
if( SparseLambda > 0 && strcmpi( 'GBRBM', rbm.type ) )  % BBRBM  Gaussian-Binary Restricted Bolztmann
dsW = bsxfun(@rdivide, dsW, rbm.sig');  % sim = exp( -1 * sum((x1 - x2).^2) / (2 * (sigma ^ 2))); x1,x2 column vectors
end

if( Verbose )
        H = v2h( rbm, V ); % 1000 x 16 = ... , 1000 x 32
        Vr = h2v( rbm, H ); % 1000 x 32= ..., 1000 x 16
err = power( V - Vr, 2 ); % 1000 x 32
rmse = sqrt( sum(err(:)) / numel(err) ); % 1 x 1
fprintf( '%3d : %9.4f %9.4f\n', iter, rmse, mean(H(:)) );
    end
   
end  %% iter 1 : maxIter

testDNN analysis 4

% pretrainDBN: pre-training the Deep Belief Nets (DBN) model by Contrastive Divergence Learning
%
% dbn = pretrainDBN(dbn, V, opts)
%
%
%Output parameters:
% dbn: the trained Deep Belief Nets (DBN) model
%
%
%Input parameters:
% dbn: the initial Deep Belief Nets (DBN) model
% V: visible (input) variables, where # of row is number of data and # of col is # of visible (input) nodes
% opts (optional): options
%
% options (defualt value):
%  opts.LayerNum: # of tarining RBMs counted from input layer (all layer)
%  opts.MaxIter: Maxium iteration number (100)
%  opts.InitialMomentum: Initial momentum until InitialMomentumIter (0.5)
%  opts.InitialMomentumIter: Iteration number for initial momentum (5)
%  opts.FinalMomentum: Final momentum after InitialMomentumIter (0.9)
%  opts.WeightCost: Weight cost (0.0002)
%  opts.DropOutRate: List of Dropout rates for each layer (0)
%  opts.StepRatio: Learning step size (0.01)
%  opts.BatchSize: # of mini-batch data (# of all data)
%  opts.Verbose: verbose or not (false)
%  opts.SparseQ: q parameter of sparse learning (0)
%  opts.SparseLambda: lambda parameter (weight) of sparse learning (0)
%
%
%Example:
% datanum = 1024;
% outputnum = 16;
% hiddennum = 8;
% inputnum = 4;
%
% inputdata = rand(datanum, inputnum);
% outputdata = rand(datanum, outputnum);
%
% dbn = randDBN([inputnum, hiddennum, outputnum]);
% dbn = pretrainDBN( dbn, inputdata );
% dbn = SetLinearMapping( dbn, inputdata, outputdata );
% dbn = trainDBN( dbn, inputdata, outputdata );
%
% estimate = v2h( dbn, inputdata );
%
%
%Reference:
%for details of the dropout
% Hinton et al, Improving neural networks by preventing co-adaptation of feature detectors, 2012.
%for details of the sparse learning
% Lee et al, Sparse deep belief net model for visual area V2, NIPS 2008.
%
%
%Version: 20130821


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dbn = pretrainDBN(dbn, V, opts)

LayerNum = numel( dbn.rbm );  % 3
DropOutRate = zeros(LayerNum,1); % 3 x 1

X = V;  % 1000 x 32

if( exist('opts' ) )
 if( isfield(opts,'LayerNum') ) % false
  LayerNum = opts.LayerNum;
 end
 if( isfield(opts,'DropOutRate') ) % true
  DropOutRate = opts.DropOutRate; % 0.5
  if( numel( DropOutRate ) == 1 )
   DropOutRate = ones(LayerNum,1) * DropOutRate; % 3 x 1   [0.5 0.5 0.5]'
  end
 end

else
 opts = [];
end

for i=1:LayerNum % 1:3
opts.DropOutRate = DropOutRate(i);
    dbn.rbm{i} = pretrainRBM(dbn.rbm{i}, X, opts); % i=1 X=1000 x 32 
    X0 = X; % 1000 x 32, 1000 x 16, 1000 x 8
    X = v2h( dbn.rbm{i}, X0 ); %      V * dnn.W-> X0 * dbn.rbm{i} <----h bsxfun="" dnn.b="" dnn.w="" p="" plus="" sigmoid="" v=""> % i(1) X(1000 x 16) dbn.rbm{i}(32 x 16) X0(1000 x 32)
% i(2) X(1000 x 8) dbn.rbm{i}(16 x 8) X0(1000 x 16)
% i(3) X(1000 x 4) dbn.rbm{i}(8 x 4) X0(1000 x 8)
end

testDNN analysis 3

% randRBM: get randomized restricted boltzmann machine (RBM) model
%
% rbm = randRBM( dimV, dimH, type )
%
%
%Output parameters:
% dbn: the randomized restricted boltzmann machine (RBM) model
%
%
%Input parameters:
% dimV: number of visible (input) nodes
% dimH: number of hidden (output) nodes
% type (optional): (default: 'BBRBM' )
%                 'BBRBM': the Bernoulli-Bernoulli RBM
%                 'GBRBM': the Gaussian-Bernoulli RBM
%
%
%Version: 20130727


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rbm = randRBM( dimV, dimH, type )  % 32V 16H - 16V 8H - 8V 4H

if( ~exist('type', 'var') || isempty(type) )
type = 'BBRBM';
end

if( strcmpi( 'GB', type(1:2) ) )
    rbm.type = 'GBRBM';
    rbm.W = randn(dimV, dimH) * 0.1;
    rbm.b = zeros(1, dimH);
    rbm.c = zeros(1, dimV);
    rbm.sig = ones(1, dimV);  % variance= sigma^2 mean=mu <-normal distribution="" nbsp="" p="">   % Gaussian function is the probability density function of the normal distribution
else
    rbm.type = 'BBRBM';
    rbm.W = randn(dimV, dimH) * 0.1;
    rbm.b = zeros(1, dimH);
    rbm.c = zeros(1, dimV);
end

testDNN analysis2

% randDBN: get randomized Deep Belief Nets (DBN) model
%
% dbn = randDBN( dims, type )
%
%
%Output parameters:
% dbn: the randomized Deep Belief Nets (DBN) model
%
%
%Input parameters:
% dims: number of nodes
% type (optional): (default: 'BBDBN' )
%                 'BBDBN': all RBMs are the Bernoulli-Bernoulli RBMs
%                 'GBDBN': the input RBM is the Gaussian-Bernoulli RBM, other RBMs are the Bernoulli-Bernoulli RBMs
%
%
%Version: 20130727


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deep Neural Network:                                     %
%                                                          %
% Copyright (C) 2013 Masayuki Tanaka. All rights reserved. %
%                    mtanaka@ctrl.titech.ac.jp             %
%                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dbn = randDBN( dims, type )

if( ~exist('type', 'var') || isempty(type) )
type = 'BBDBN';
end


if( strcmpi( 'GB', type(1:2) ) ) %Gaussian-Binary
 dbn.type = 'GBDBN';
else
 dbn.type = 'BBDBN';
end

dbn.rbm = cell( numel(dims)-1, 1 );

i = 1;
if( strcmpi( 'GB', type(1:2) ) )
 dbn.rbm{i} = randRBM( dims(i), dims(i+1), 'GBRBM' ); % Gaussian-Binary Restricted Bolztmann Machine
else
 dbn.rbm{i} = randRBM( dims(i), dims(i+1), 'BBRBM' ); % Bernoulli-Bernoulli Restricted Bolztmann Machine
end

for i=2:numel(dbn.rbm) - 1
 dbn.rbm{i} = randRBM( dims(i), dims(i+1), 'BBRBM' );
end

i = numel(dbn.rbm);
dbn.rbm{i} = randRBM( dims(i), dims(i+1), 'BBRBM' );