-
Notifications
You must be signed in to change notification settings - Fork 133
/
cnn_shape_init.m
177 lines (155 loc) · 6.26 KB
/
cnn_shape_init.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
function net = cnn_shape_init(classNames, varargin)
opts.base = 'imagenet-matconvnet-vgg-m';
opts.restart = false;
opts.nViews = 12;
opts.viewpoolPos = 'relu5';
opts.viewpoolType = 'max';
opts.weightInitMethod = 'xavierimproved';
opts.scale = 1;
opts.networkType = 'simplenn'; % only simplenn is supported currently
opts = vl_argparse(opts, varargin);
assert(strcmp(opts.networkType,'simplenn'), 'Only simplenn is supported currently');
init_bias = 0.1;
nClass = length(classNames);
% Load model, try to download it if not readily available
if ~ischar(opts.base),
net = opts.base;
else
netFilePath = fullfile('data','models', [opts.base '.mat']);
if ~exist(netFilePath,'file'),
fprintf('Downloading model (%s) ...', opts.base) ;
vl_xmkdir(fullfile('data','models')) ;
urlwrite(fullfile('http://www.vlfeat.org/matconvnet/models/', ...
[opts.base '.mat']), netFilePath) ;
fprintf(' done!\n');
end
net = load(netFilePath);
end
assert(strcmp(net.layers{end}.type, 'softmax'), 'Wrong network format');
dataTyp = class(net.layers{end-1}.weights{1});
% Initiate the last but one layer w/ random weights
widthPrev = size(net.layers{end-1}.weights{1}, 3);
nClass0 = size(net.layers{end-1}.weights{1},4);
if nClass0 ~= nClass || opts.restart,
net.layers{end-1}.weights{1} = init_weight(opts, 1, 1, widthPrev, nClass, dataTyp);
net.layers{end-1}.weights{2} = zeros(nClass, 1, dataTyp);
end
% Initiate other layers w/ random weights if training from scratch is desired
if opts.restart,
w_layers = find(cellfun(@(c) isfield(c,'weights'),net.layers));
for i=w_layers(1:end-1),
sz = size(net.layers{i}.weights{1});
net.layers{i}.weights{1} = init_weight(opts, sz(1), sz(2), sz(3), sz(4), dataTyp);
net.layers{i}.weights{2} = zeros(sz(4), 1, dataTyp);
end
end
% Swap softmax w/ softmaxloss
net.layers{end} = struct('type', 'softmaxloss', 'name', 'loss') ;
% Insert viewpooling
if opts.nViews>1,
viewpoolLayer = struct('name', 'viewpool', ...
'type', 'custom', ...
'vstride', opts.nViews, ...
'method', opts.viewpoolType, ...
'forward', @viewpool_fw, ...
'backward', @viewpool_bw);
net = modify_net(net, viewpoolLayer, ...
'mode','add_layer', ...
'loc',opts.viewpoolPos);
if strcmp(opts.viewpoolType, 'cat'),
loc = find(cellfun(@(c) strcmp(c.name,'viewpool'), net.layers));
assert(numel(loc)==1);
w_layers = find(cellfun(@(c) isfield(c,'weights'), net.layers));
loc = w_layers(find((w_layers-loc)>0,1)); % location of the adjacent weight layer
if ~isempty(loc),
sz = size(net.layers{loc}.weights{1});
if length(sz)<4, sz = [sz ones(1,4-length(sz))]; end
net.layers{loc}.weights{1} = init_weight(opts, sz(1), sz(2), sz(3)*opts.nViews, sz(4), dataTyp);
net.layers{loc}.weights{2} = zeros(sz(4), 1, dataTyp);
% random initialize layers after
w_layers = w_layers(w_layers>loc);
for i=w_layers(1:end-1),
sz = size(net.layers{i}.weights{1});
if length(sz)<4, sz = [sz ones(1,4-length(sz))]; end
net.layers{i}.weights{1} = init_weight(opts, sz(1), sz(2), sz(3), sz(4), dataTyp);
net.layers{i}.weights{2} = zeros(sz(4), 1, dataTyp);
end
end
end
end
% update meta data
net.meta.classes.name = classNames;
net.meta.classes.description = classNames;
% speial case: when no class names specified, remove fc8/prob layers
if nClass==0,
net.layers = net.layers(1:end-2);
end
end
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
end
% -------------------------------------------------------------------------
function res_ip1 = viewpool_fw(layer, res_i, res_ip1)
% -------------------------------------------------------------------------
[sz1, sz2, sz3, sz4] = size(res_i.x);
if mod(sz4,layer.vstride)~=0,
error('all shapes should have same number of views');
end
if strcmp(layer.method, 'avg'),
res_ip1.x = permute(...
mean(reshape(res_i.x,[sz1 sz2 sz3 layer.vstride sz4/layer.vstride]), 4), ...
[1,2,3,5,4]);
elseif strcmp(layer.method, 'max'),
res_ip1.x = permute(...
max(reshape(res_i.x,[sz1 sz2 sz3 layer.vstride sz4/layer.vstride]), [], 4), ...
[1,2,3,5,4]);
elseif strcmp(layer.method, 'cat'),
res_ip1.x = reshape(res_i.x,[sz1 sz2 sz3*layer.vstride sz4/layer.vstride]);
else
error('Unknown viewpool method: %s', layer.method);
end
end
% -------------------------------------------------------------------------
function res_i = viewpool_bw(layer, res_i, res_ip1)
% -------------------------------------------------------------------------
[sz1, sz2, sz3, sz4] = size(res_ip1.dzdx);
if strcmp(layer.method, 'avg'),
res_i.dzdx = ...
reshape(repmat(reshape(res_ip1.dzdx / layer.vstride, ...
[sz1 sz2 sz3 1 sz4]), ...
[1 1 1 layer.vstride 1]),...
[sz1 sz2 sz3 layer.vstride*sz4]);
elseif strcmp(layer.method, 'max'),
[~,I] = max(reshape(permute(res_i.x,[4 1 2 3]), ...
[layer.vstride, sz4*sz1*sz2*sz3]),[],1);
Ind = zeros(layer.vstride,sz4*sz1*sz2*sz3, 'single');
Ind(sub2ind(size(Ind),I,1:length(I))) = 1;
Ind = permute(reshape(Ind,[layer.vstride*sz4,sz1,sz2,sz3]),[2 3 4 1]);
res_i.dzdx = ...
reshape(repmat(reshape(res_ip1.dzdx, ...
[sz1 sz2 sz3 1 sz4]), ...
[1 1 1 layer.vstride 1]),...
[sz1 sz2 sz3 layer.vstride*sz4]) .* Ind;
elseif strcmp(layer.method, 'cat'),
res_i.dzdx = reshape(res_ip1.dzdx, [sz1 sz2 sz3/layer.vstride sz4*layer.vstride]);
else
error('Unknown viewpool method: %s', layer.method);
end
end