-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcnn_cifar.m
206 lines (171 loc) · 6.84 KB
/
cnn_cifar.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
function [net, info] = cnn_cifar(varargin)
%Demonstrates ResNet (with preactivation) on:
%CIFAR-10 and CIFAR-100 (tested for depth 164)
%Tested in: 2015b and 2016a versions of Matlab
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', 'matconvnet','matlab', 'vl_setupnn.m')) ;
%the graph building breaks without it for earlier versions
if verLessThan('matlab','R2015b')
set(0,'RecursionLimit',1000);
end
opts.modelType = 'res' ;
opts.depth=164;
opts.GPU=[];
opts.batchSize=128;
opts.weightDecay=0.0001;
opts.momentum=0.9;
opts.resConn = 1;
opts.Nclass=10;
opts.filterDepths = [];
opts.learningRate = [0.01*ones(1,3) 0.1*ones(1,80) 0.01*ones(1,10) 0.001*ones(1,20)] ;
[opts, varargin] = vl_argparse(opts, varargin) ;
datas='cifar';
opts.expDir = sprintf('data/%s_%d-%s-D%d-R%d',datas, opts.Nclass, opts.modelType,opts.depth,opts.resConn);
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data', datas) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.whitenData = false ;
opts.contrastNormalization = false ;
opts.networkType = 'dagnn' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = [opts.GPU]; end;
% -------------------------------------------------------------------------
% Prepare model and data
% -------------------------------------------------------------------------
switch opts.modelType
case 'res'
net = cnn_resnet_preact('modelType', opts.modelType,'depth',opts.depth, 'resConn', opts.resConn, 'Nclass', opts.Nclass);
otherwise
error('Unknown model type ''%s''.', opts.modelType) ;
end
net.meta.trainOpts.learningRate=opts.learningRate; %update lr
net.meta.trainOpts.batchSize = opts.batchSize; %batch size
net.meta.trainOpts.weightDecay = opts.weightDecay; %weight decay
net.meta.trainOpts.momentum = opts.momentum ;
net.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate); %update num. ep.
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
if opts.Nclass==10 && strcmp(datas,'cifar')
imdb = getCifar10Imdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
else
imdb = getCifar100Imdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
end
net.meta.classes.name = imdb.meta.classes(:)' ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
[net, info] = cnn_train_dag(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% -------------------------------------------------------------------------
function fn = getBatch(opts)
% -------------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
error('The simplenn structure is not supported for the ResNet architecture');
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
images=cropRand(images) ; %random crop for all samples
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% -------------------------------------------------------------------------
function imdb = getCifar10Imdb(opts)
% -------------------------------------------------------------------------
unpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');
files = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...
{'test_batch.mat'}];
files = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);
file_set = uint8([ones(1, 5), 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
%pad the images to crop later
data = padarray(data,[4,4],128,'both');
%remove mean
r = data(:,:,1,set == 1);
g = data(:,:,3,set == 1);
b = data(:,:,3,set == 1);
meanCifar = [mean(r(:)), mean(g(:)), mean(b(:))];
data = bsxfun(@minus, data, reshape(meanCifar,1,1,3));
%divide by std
stdCifar = [std(r(:)), std(g(:)), std(b(:))];
data = bsxfun(@times, data,reshape(1./stdCifar,1,1,3)) ;
clNames = load(fullfile(unpackPath, 'batches.meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.label_names;
% -------------------------------------------------------------------------
function imdb = getCifar100Imdb(opts)
% -------------------------------------------------------------------------
unpackPath = fullfile(opts.dataDir, 'cifar-100-matlab');
files{1} = fullfile(unpackPath, 'train.mat');
files{2} = fullfile(unpackPath, 'test.mat');
%files{3} = fullfile(unpackPath, 'meta.mat');
file_set = uint8([1, 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-100-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.fine_labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
%pad the images to crop later
data = padarray(data,[4,4],128,'both');
% remove mean
r = data(:,:,1,set == 1);
g = data(:,:,2,set == 1);
b = data(:,:,3,set == 1);
meanCifar = [mean(r(:)), mean(g(:)), mean(b(:))];
data = bsxfun(@minus, data, reshape(meanCifar,1,1,3));
%divide by std
stdCifar = [std(r(:)), std(g(:)), std(b(:))];
data = bsxfun(@times, data,reshape(1./stdCifar,1,1,3)) ;
clNames = load(fullfile(unpackPath, 'meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.fine_label_names;