-
Notifications
You must be signed in to change notification settings - Fork 0
/
alexnet_example.m
54 lines (54 loc) · 1.98 KB
/
alexnet_example.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
%% Load alexnet and modify it
net = alexnet;
lgraph = layerGraph(net);
lgraph = removeLayers(lgraph,lgraph.Layers(end).Name);
dlnet = dlnetwork(lgraph);
%% Get layer shape for all layers
layerShapes = get_layer_shape(dlnet);
disp(layerShapes)
%% Get layer shape for all layers
img = rand(256,256,3,1)*255.0;
dlImgs = dlarray(single(img),'SSCB');
[layerShapes,layerShapeMap] = get_layer_shape(dlnet,{dlnet.Layers.Name},dlImgs);
disp(layerShapes)
%%
img = rand(256,256,3,100)*255.0;
dlImg = dlarray(gpuArray(single(img)),'SSCB'); % use gpu input
dydI = dlfeval(@gradientMap_batch,dlnet,dlImg,'fc6',355);
gradmap = extractdata(mean(abs(dydI),[3,4]));
figure;imagesc(gradmap);axis image
%%
img = rand(256,256,3,100)*255.0;
dlImg = dlarray(single(img),'SSCB'); % use cpu input
dydI = dlfeval(@gradientMap_batch,dlnet,dlImg,'conv2',1:256,15,15);
gradmap = extractdata(mean(abs(dydI),[3,4]));
figure;imagesc(gradmap);axis image
%%
% another way of computing the map grad * image
gradimgmap = extractdata(mean(abs(dydI .* dlImg),[3,4]));
figure;imagesc(gradimgmap);axis image
%% find rf for all layers in alexnet (mapReceptiveField.m)
figure;
tiledlayout("flow",'pad','tight','TileSp','tight');
repN = 100;
for rowi = 1:size(layerShapes,1)
layerShape = layerShapes.Size{rowi};
layerName = layerShapes.LayerName{rowi};
disp(layerName)
img = rand(256,256,3,repN)*255.0;
dlImg = dlarray(single(img),'SSCB');
if length(layerShape)==4
% If it's a 4D layer (conv), calculate the gradient map for all channels
% at the center pixel
cent_i = floor(layerShape(1)/2);
cent_j = floor(layerShape(2)/2);
chan_id = 1:layerShape(3);
dydI = dlfeval(@gradientMap_batch,dlnet,dlImg,layerName,chan_id,cent_i,cent_j);
elseif length(layerShape)==2
% If it's a 2D layer, calculate the gradient map for all channel
chan_id = 1:layerShape(1);
dydI = dlfeval(@gradientMap_batch,dlnet,dlImg,layerName,chan_id);
end
gradmap = extractdata(mean(abs(dydI),[3,4]));
ax = nexttile;imagesc(gradmap);title(layerName);axis image;
end