forked from vedaldi/practical-object-category-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise4.m
88 lines (73 loc) · 2.52 KB
/
exercise4.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
% EXERCISE4
setup ;
% Training cofiguration
%targetClass = 1 ;
%targetClass = 'prohibitory' ;
targetClass = 'mandatory' ;
%targetClass = 'danger' ;
numHardNegativeMiningIterations = 7 ;
schedule = [1 2 5 5 100 100 100] ;
% Scale space configuration
hogCellSize = 8 ;
minScale = -1 ;
maxScale = 3 ;
numOctaveSubdivisions = 3 ;
scales = 2.^linspace(...
minScale,...
maxScale,...
numOctaveSubdivisions*(maxScale-minScale+1)) ;
% Load data
loadData(targetClass) ;
% Compute HOG features of examples (see Step 1.2)
trainBoxHog = {} ;
for i = 1:size(trainBoxPatches,4)
trainBoxHog{i} = vl_hog(trainBoxPatches(:,:,:,i), hogCellSize) ;
end
trainBoxHog = cat(4, trainBoxHog{:}) ;
modelWidth = size(trainBoxHog,2) ;
modelHeight = size(trainBoxHog,1) ;
% -------------------------------------------------------------------------
% Step 4.1: Train with hard negative mining
% -------------------------------------------------------------------------
% Initial positive and negative data
pos = trainBoxHog(:,:,:,ismember(trainBoxLabels,targetClass)) ;
neg = zeros(size(pos,1),size(pos,2),size(pos,3),0) ;
for t=1:numHardNegativeMiningIterations
numPos = size(pos,4) ;
numNeg = size(neg,4) ;
C = 1 ;
lambda = 1 / (C * (numPos + numNeg)) ;
fprintf('Hard negative mining iteration %d: pos %d, neg %d\n', ...
t, numPos, numNeg) ;
% Train an SVM model (see Step 2.2)
x = cat(4, pos, neg) ;
x = reshape(x, [], numPos + numNeg) ;
y = [ones(1, size(pos,4)) -ones(1, size(neg,4))] ;
w = vl_svmtrain(x,y,lambda,'epsilon',0.01,'verbose') ;
w = single(reshape(w, modelHeight, modelWidth, [])) ;
% Plot model
figure(1) ; clf ;
imagesc(vl_hog('render', w)) ;
colormap gray ; axis equal ;
title(sprintf('SVM HOG model (retraining ieration %d)',t)) ;
% Evaluate on training data and mine hard negatives
figure(2) ; set(gcf, 'name', sprintf('Retraining iteration %d',t)) ;
[matches, moreNeg] = ...
evaluateModel(...
vl_colsubset(trainImages', schedule(t), 'beginning'), ...
trainBoxes, trainBoxImages, ...
w, hogCellSize, scales) ;
% Add negatives
neg = cat(4, neg, moreNeg) ;
% Remove negative duplicates
z = reshape(neg, [], size(neg,4)) ;
[~,keep] = unique(z','stable','rows') ;
neg = neg(:,:,:,keep) ;
end
% -------------------------------------------------------------------------
% Step 4.2: Evaluate the model on the test data
% -------------------------------------------------------------------------
figure(3) ; clf ;
evaluateModel(...
testImages, testBoxes, testBoxImages, ...
w, hogCellSize, scales) ;