-
Notifications
You must be signed in to change notification settings - Fork 6
/
cnn_resnet_finetune.m
262 lines (224 loc) · 8.59 KB
/
cnn_resnet_finetune.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
function cnn_resnet_finetune(varargin)
if ~isempty(gcp('nocreate')),
delete(gcp)
end
addpath('resnet');
opts = cnn_setup_environment();
opts.train.gpus = [1] ;
% opts.train.gpus = [ 1 : 3 ]
opts.dataSet = 'Remat';
% opts.dataSet = 'hmdb51';
opts.aug = 'stretch';
opts.border = 0;
opts.pad = 0;
opts.train.memoryMapFile = fullfile(tempdir, 'ramdisk', ['matconvnet' num2str(feature('getpid')) '.bin']) ;
addpath('network_surgery');
opts.dataDir = fullfile(opts.dataPath, opts.dataSet) ;
opts.splitDir = [opts.dataSet '_splits'];
opts.nSplit = 1 ;
opts.dropOutRatio = 0.5 ;
opts.train.cheapResize = 0 ;
opts.inputdim = [ 224, 224, 3] ;
opts.train.batchSize = 196 ;
opts.train.numSubBatches = ceil(8 / max(numel(opts.train.gpus),1));
opts.train.epochFactor = 10 ;
opts.train.augmentation = 'borders25';
opts.train.backpropDepth = cell(1, 2);
opts.train.backpropDepth(:) = {'pool5'};
opts.train.learningRate = [1e-2*ones(1, 2) 1e-2*ones(1, 3) 1e-3*ones(1, 3) 1e-4*ones(1, 3)] ;
if strcmp(opts.dataSet, 'hmdb51')
opts.train.learningRate = [1e-2*ones(1, 2) 1e-2*ones(1, 1) 1e-3*ones(1, 1) 1e-4*ones(1, 1)] ;
end
model = ['img-res50-' opts.train.augmentation '-bs=' num2str(opts.train.batchSize) ...
'-split' num2str(opts.nSplit) '-dr' num2str(opts.dropOutRatio)];
if strfind(model, 'vgg16');
baseModel = 'imagenet-vgg-verydeep-16.mat' ;
opts.train.learningRate = [1e-3*ones(1, 3) 5e-4*ones(1, 5) 5e-5*ones(1,2) 5e-6*ones(1,2)] ;
opts.train.backpropDepth = cell(1, 3);
opts.train.backpropDepth(:) = {'layer37'};
opts.train.batchSize = 128 ;
opts.train.numSubBatches = ceil(16 / max(numel(opts.train.gpus),1));
elseif strfind(model, 'vgg-m');
baseModel = 'imagenet-vgg-m-2048.mat' ;
elseif strfind(model, 'res152');
baseModel = 'imagenet-resnet-152-dag.mat' ;
elseif strfind(model, 'res101');
baseModel = 'imagenet-resnet-101-dag.mat' ;
elseif strfind(model, 'res50');
baseModel = 'imagenet-resnet-50-dag.mat' ;
opts.train.numSubBatches = ceil(32 / max(numel(opts.train.gpus),1));
else
error('Unknown model %s', model) ;
end
opts.model = fullfile(opts.modelPath,baseModel) ;
opts.expDir = fullfile(opts.dataDir, [opts.dataSet '-' model]) ;
opts.imdbPath = fullfile(opts.dataDir, [opts.dataSet '_resnet_split' num2str(opts.nSplit) 'imdb.mat']);
opts.train.plotDiagnostics = 0 ;
opts.train.continue = 1 ;
opts.train.prefetch = 1 ;
opts.train.expDir = opts.expDir ;
opts.train.numAugments = 1;
opts.train.frameSample = 'random';
opts.train.nFramesPerVid = 1;
opts.train.uniformAugments = false;
[opts, varargin] = vl_argparse(opts, varargin) ;
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
else
imdb = cnn_Remat_resnet_setup_data('dataPath', opts.dataPath, 'flowDir',opts.flowDir, ...
'dataSet', opts.dataSet, 'nSplit', opts.nSplit) ;
save(opts.imdbPath, '-struct', 'imdb', '-v6') ;
end
nClasses = length(imdb.classes.name);
if ~exist(opts.model)
fprintf('Downloading base model file: %s ...\n', baseModel);
mkdir(fileparts(opts.model)) ;
urlwrite(...
['http://www.vlfeat.org/matconvnet/models/' baseModel], ...
opts.model) ;
end
net = load(opts.model);
if isfield(net, 'net'), net=net.net;end
if isstruct(net.layers)
% replace 1000-way imagenet classifiers
for p = 1 : numel(net.params)
sz = size(net.params(p).value);
if any(sz == 1000)
sz(sz == 1000) = nClasses;
fprintf('replace classifier layer of %s\n', net.params(p).name);
if numel(sz) > 2
net.params(p).value = 0.01 * randn(sz, class(net.params(p).value));
else
net.params(p).value = zeros(sz, class(net.params(p).value));
end
end
end
net.meta.normalization.border = [256 256] - net.meta.normalization.imageSize(1:2);
net = dagnn.DagNN.loadobj(net);
if strfind(model, 'bnorm')
net = insert_bnorm_layers(net) ;
end
else
% net=vl_simplenn_tidy(net);
if isfield(net, 'meta'),
netNorm = net.meta.normalization;
else
netNorm = net.normalization;
end
if(netNorm.imageSize(3) == 3) && ~isempty(strfind(opts.model, 'imagenet'))
netNorm.border = [240 240] - netNorm.imageSize(1:2);
net = replace_last_layer(net, [1 2], [1 2], nClasses, opts.dropOutRatio);
end
if strfind(model, 'bnorm')
net = insert_bnorm_layers(net) ;
end
net = dagnn.DagNN.fromSimpleNN(net) ;
end
net = dagnn.DagNN.setLrWd(net);
net.renameVar(net.vars(1).name, 'input');
if ~isnan(opts.dropOutRatio)
dr_layers = find(arrayfun(@(x) isa(x.block,'dagnn.DropOut'), net.layers)) ;
if ~isempty(dr_layers)
if opts.dropOutRatio > 0
for i=dr_layers, net.layers(i).block.rate = opts.dropOutRatio; end
else
net.removeLayer({net.layers(dr_layers).name});
end
else
if opts.dropOutRatio > 0
pool5_layer = find(arrayfun(@(x) isa(x.block,'dagnn.Pooling'), net.layers)) ;
conv_layers = pool5_layer(end);
for i=conv_layers
block = dagnn.DropOut() ; block.rate = opts.dropOutRatio ;
newName = ['drop_' net.layers(i).name];
net.addLayer(newName, ...
block, ...
net.layers(i).outputs, ...
{newName}) ;
for l = 1:numel(net.layers)-1
for f = net.layers(i).outputs
sel = find(strcmp(f, net.layers(l).inputs )) ;
if ~isempty(sel)
[net.layers(l).inputs{sel}] = deal(newName) ;
end
end
end
end
end
end
end
net.layers(~cellfun('isempty', strfind({net.layers(:).name}, 'err'))) = [] ;
opts.train.derOutputs = {} ;
for l=numel(net.layers):-1:1
if isa(net.layers(l).block, 'dagnn.Loss') && isempty(strfind(net.layers(l).name, 'err'))
opts.train.derOutputs = {opts.train.derOutputs{:}, net.layers(l).outputs{:}, 1} ;
end
if isa(net.layers(l).block, 'dagnn.SoftMax')
net.removeLayer(net.layers(l).name)
l = l - 1;
end
end
if isempty(opts.train.derOutputs)
net = dagnn.DagNN.insertLossLayers(net, 'numClasses', nClasses) ;
fprintf('setting derivative for layer %s \n', net.layers(end).name);
opts.train.derOutputs = {opts.train.derOutputs{:}, net.layers(end).outputs{:}, 1} ;
end
lossLayers = find(arrayfun(@(x) isa(x.block,'dagnn.Loss') && strcmp(x.block.loss,'softmaxlog'),net.layers));
net.addLayer('top1error', ...
dagnn.Loss('loss', 'classerror'), ...
net.layers(lossLayers(end)).inputs, ...
'top1error') ;
net.addLayer('top5error', ...
dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
net.layers(lossLayers(end)).inputs, ...
'top5error') ;
net.print() ;
net.rebuild() ;
net.meta.normalization.rgbVariance = [];
net.meta.normalization.averageImage = mean(mean(net.meta.normalization.averageImage, 1), 2);
opts.train.train = find(ismember(imdb.images.set, [1])) ;
opts.train.train = repmat(opts.train.train,1,opts.train.epochFactor);
% opts.train.valmode = '250samples';
opts.train.valmode = '30samples'
opts.train.denseEval = 1;
net.conserveMemory = 1 ;
fn = getBatchFn(opts, net.meta);
%fn = getBatchWrapper_ucf101_rgbflow(net.meta.normalization, opts.numFetchThreads, opts.train) ;
[info] = cnn_resnet_train_dag(net, imdb, fn, opts.train) ;
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
bopts.numThreads = opts.numFetchThreads ;
bopts.pad = opts.pad ;
bopts.border = opts.border ;
bopts.transformation = opts.aug ;
bopts.imageSize = meta.normalization.imageSize ;
bopts.averageImage = meta.normalization.averageImage ;
bopts.rgbVariance = meta.normalization.rgbVariance ;
% bopts.transformation = meta.augmentation.transformation ;
fn = @(x,y) getSimpleNNBatch(bopts,x,y) ;
end
% -------------------------------------------------------------------------
function [im,labels] = getSimpleNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
isVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ;
if ~isVal
% training
im = cnn_resnet_get_batch(images, opts, ...
'prefetch', nargout == 0) ;
else
% validation: disable data augmentation
% opts.border=0;
im = cnn_resnet_get_batch(images, opts, ...
'prefetch', nargout == 0, ...
'transformation', 'none') ;
end
if nargout > 0
labels = imdb.images.class(batch) ;
end
end