File size: 12,509 Bytes
d4035c1 |
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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
function [conf, jobId] = bk_trainAppModel(conf, varargin)
% BK_TRAINAPPMODEL
%
% modelDirs: one for each class
% roiDir: where to find GT rois
%
% Author:: Andrea Vedaldi
% AUTORIGHTS
% Copyright (C) 2008-09 Andrea Vedaldi
%
% This file is part of the VGG MKL Class and VGG MKL Det code packages,
% available in the terms of the GNU General Public License version 2.
conf_.kerDir = '' ;
conf_.kerDb = struct ;
conf_.trainRoiDbPath = '' ;
conf_.trainHistDir = '' ;
conf_.testRoiDbPath = '' ;
conf_.testHistDir = '' ;
conf_.modelPath = '' ;
conf_.featWeights = [] ;
conf_.learnWeights = 'none' ;
conf_.posWeight = 1 ;
conf_.noClobber = false ;
if nargin == 0, conf = conf_ ; return ; end
conf = override(conf_, conf, 1) ;
[jobId, taskId] = parallelDriver('numNodes', 1, ...
'freeMemMb', 4 * 1024, ...
varargin{:}) ;
if ~isnan(jobId) & isnan(taskId) ; return ; end
% --------------------------------------------------------------------
% Process all classes and aspects
% --------------------------------------------------------------------
if conf.noClobber & checkFile(conf.modelPath)
fprintf('\tSkipping to avoid clobbering ''%s''.\n', conf.modelPath) ;
return ;
end
rand('state', 0) ;
randn('state', 0) ;
ensuredir(fileparts(conf.modelPath)) ;
% ------------------------------------------------------------------
% Load training ROI DB
% ------------------------------------------------------------------
fprintf('\tLoading training ROI DB ''%s''.\n', ...
conf.trainRoiDbPath) ;
trdb = load(conf.trainRoiDbPath) ;
labels = trdb.labels(:)' ;
fprintf('\tWeight learning stragegy: %s\n', conf.learnWeights) ;
fprintf('\tInitial weights: %s\n', sprintf('%g ', conf.featWeights)) ;
% ------------------------------------------------------------------
% Train weights
% ------------------------------------------------------------------
if ~isempty(conf.featWeights)
initWeights = conf.featWeights ;
else
initWeights = ones(1, length(conf.kerDb)) ;
end
% if there is only one kernel, MKL is not needed
if length(conf.kerDb) == 1,
conf.learnWeights = 'none' ;
end
switch conf.learnWeights
case 'none'
weights = initWeights ;
case 'equalMean' % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[base, kernels, labels] = ...
loadBase(conf.kerDir, conf.kerDb, trdb.labels(:)', ...
'weights', initWeights, ...
'maxSize', 5000, ...
'squeeze', false) ;
for i=1:size(base,3)
tmp = base(:,:,i) ;
weights(i) = initWeights(i) ./ mean(tmp(:)) ;
clear tmp ;
end
svm.d = weights ;
fprintf('\tComputed weights: %s\n', sprintf('%g ', weights)) ;
% KERNELS contains the full list of kernels, with gamma for the exp
case 'manik' % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[base, kernels, labels] = ...
loadBase(conf.kerDir, conf.kerDb, trdb.labels(:)', ...
'weights', initWeights, ...
'maxSize', 5000, ...
'squeeze', false) ;
svm = learnGmklSvm(base, labels(:)) ;
svm = svmflip(svm, labels) ;
weights = svm.d' .* initWeights ;
svm.d = weights ;
fprintf('\tComputed weights: %s\n', sprintf('%g ', weights)) ;
% KERNELS contains the full list of kernels, with gamma for the exp
case 'manikPartition' % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
numPartitions = 0 ;
kerTypes = uniqueStrings({conf.kerDb.type}) ;
featNames = uniqueStrings({conf.kerDb.feat}) ;
for kerType = kerTypes
kerType = char(kerType) ;
for featName = featNames
featName = char(featName) ;
fprintf('Partition learning %d: %s %s\n', ...
numPartitions, kerType, featName) ;
selKer = findKernels(conf.kerDb, ...
'type', kerType, ...
'feat', featName) ;
if isempty(selKer), continue ; end
numPartitions = numPartitions + 1 ;
[base, kernels{numPartitions}, labels] = ...
loadBase(conf.kerDir, conf.kerDb(selKer), trdb.labels(:)', ...
'weights', initWeights(selKer), ...
'maxSize', 10000, ...
'squeeze', false) ;
svm = learnGmklSvm(base, labels(:)) ;
svm = svmflip(svm, labels) ;
weights(selKer) = svm.d' .* initWeights(selKer) ;
fprintf('\tRelative weights: %s\n', sprintf('%g ', svm.d)) ;
clear base ;
end
end
fprintf('Partition learning: intra weights\n') ;
base = [] ;
thisPartition = 0 ;
for kerType = kerTypes
kerType = char(kerType) ;
for featName = featNames
featName = char(featName) ;
selKer = findKernels(conf.kerDb, ...
'type', kerType, ...
'feat', featName) ;
if isempty(selKer), continue ; end
thisPartition = thisPartition + 1 ;
[partition, drop, labels] = ...
loadBase(conf.kerDir, conf.kerDb(selKer), ...
trdb.labels(:)', ...
'weights', weights(selKer), ...
'maxSize', 7000, ...
'squeeze', true) ;
if isempty(base)
base = zeros([size(partition) numPartitions]) ;
end
base(:,:,thisPartition) = partition ;
clear partition ;
end
end
svm = learnGmklSvm(base, labels(:)) ;
svm = svmflip(svm, labels) ;
fprintf('\tRelative weights: %s\n', sprintf('%g ', svm.d)) ;
clear base ;
thisPartition = 0 ;
for kerType = kerTypes
kerType = char(kerType) ;
for featName = featNames
featName = char(featName) ;
selKer = findKernels(conf.kerDb, ...
'type', kerType, ...
'feat', featName) ;
if isempty(selKer), continue ; end
thisPartition = thisPartition + 1 ;
weights(selKer) = svm.d(thisPartition) .* weights(selKer) ;
end
end
% kernels contains the full list of kernels, with gamma for the exp
kernels = cat(2, kernels{:}) ;
svm.d = weights ;
otherwise
error('Unknown weight learning method') ;
end
% ------------------------------------------------------------------
% Train SVM
% ------------------------------------------------------------------
if ~exist('svm', 'var') | length(labels) < length(trdb.labels) | ...
conf.posWeight
fprintf('\tFinal SVM learning (pos weight: %f)\n', conf.posWeight) ;
[base,kernels,labels] = ...
loadBase(conf.kerDir, conf.kerDb, trdb.labels(:)', ...
'weights', weights, ...
'squeeze', true) ;
svm = svmkernellearn(base, labels(:)', ...
'type', 'C', ...
'C', 10, ...
'verbosity', 1, ...
'weights', [+1 conf.posWeight ; -1 1]') ;
svm = svmflip(svm, trdb.labels) ;
% test it on train
scores = svm.alphay' * base(svm.svind, :) + svm.b ;
errs = scores .* trdb.labels(:)' < 0 ;
err = mean(errs) ;
selPos = find(trdb.labels(:)' > 0) ;
selNeg = find(trdb.labels(:)' < 0) ;
werr = sum(errs(selPos)) * conf.posWeight + sum(errs(selNeg)) ;
werr = werr / (length(selPos) * conf.posWeight + length(selNeg)) ;
fprintf('\tSVM training error: %.2f%% (weighed: %.2f%%).\n', ...
err*100, werr*100) ;
svm.d = weights ;
end
svm.kernels = kernels ;
clear base ;
% ------------------------------------------------------------------
% Compress linear SVMs
% ------------------------------------------------------------------
isLinear = true ;
for ki=1:length(svm.kernels)
kernel = svm.kernels(ki) ;
if ~strcmp(kernel.type, 'kl2'), isLinear = false ; continue ; end
histPath = fullfile(conf.trainHistDir, ['hist-' kernel.histName '.mat']) ;
fprintf('\tLoading histograms''%s''.\n', histPath) ;
tmp = load(histPath) ;
svm.(kernel.histName) = ...
svm.d(ki) * tmp.hists(:, svm.svind) * svm.alphay ;
clear tmp ;
end
if isLinear
svm.type = 'linear' ;
else
svm.type = 'nonlinear' ;
end
fprintf('\tNumber of support vectors: %d\n', length(svm.svind)) ;
fprintf('\tSVM type: %s\n', svm.type) ;
fprintf('\tSaving model ''%s''.\n', conf.modelPath) ;
ssave(conf.modelPath, '-STRUCT', 'svm') ;
return
% ------------------------------------------------------------------
% Test it
% ------------------------------------------------------------------
if isempty(conf.testRoiDbPath), return ; end
fprintf('\tLoading test ROI DB ''%s''.\n', conf.testRoiDbPath) ;
tsdb = load(conf.testRoiDbPath) ;
scores = zeros(size(tsdb.labels)) + svm.b ;
for ki=1:K
matPath = fullfile(conf.kerDir, ['test-' kernels(ki).name '.mat']) ;
fprintf('\tLoading kernel matrix ''%s''.\n', matPath) ;
kernels_ = load(matPath) ;
scores = scores + svm.d(ki) * ...
(svm.alphay' * kernels_.matrix(svm.svind, :)) ;
clear kernels_ ;
end
figure(100) ; clf ; hold on ;
[recall,precision,info] = pr(tsdb.labels, scores) ;
plot(recall,precision,'b-','linewidth',2) ;
grid on ;
xlim([0 1]) ;
ylim([0 1]) ;
xlabel('recall') ;
ylabel('precision') ;
title(sprintf('PR on test ROI DB - AUC: %.2f %% (%.2f %%)', ...
info.auc, info.auc_pa08)) ;
axis square ;
drawnow ;
[a,b,c] = fileparts(conf.modelPath) ;
figPath = fullfile(a, [b '-pr-test.eps']) ;
printsize(.97 + 0.001*randn) ; % ugly hack for matlab repeat
print('-depsc', figPath) ;
prPath = fullfile(a, [b '-pr-test.mat']) ;
ssave(prPath, 'recall', 'precision', 'info') ;
% ------------------------------------------------------------------
function [base, kernels, labels] = ...
loadBase(kerDir, kernels, labels, varargin)
% ------------------------------------------------------------------
opts.squeeze = false ;
opts.weights = NaN ;
opts.maxSize = +inf ;
opts = vl_argparse(opts,varargin{:}) ;
base = [] ;
sel = NaN ;
K = length(kernels) ;
% calculate subset of kernel to load ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if length(labels) > opts.maxSize
selp = find(labels > 0) ;
seln = find(labels < 0) ;
np = length(selp) ;
nm = length(seln) ;
alpha = opts.maxSize / length(labels) ;
mp = floor(alpha * np) ;
mm = floor(alpha * nm) ;
if (mp + mm < opts.maxSize), mp = mp + 1 ; end
if (mp + mm < opts.maxSize), mm = mm + 1 ; end
randn('state', 0) ;
rand('state', 0) ;
selp = randcol(selp, mp) ;
seln = randcol(seln, mm) ;
sel = [selp seln] ;
labels = labels(sel) ;
fprintf('\tLoading kernels for only %.2f %% of the data (pos: %d neg: %d).\n', ...
alpha * 100, length(selp), length(seln)) ;
end
% load matrices ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
clear kernels_ kernels__ ;
for ki = 1:K
kerPath = fullfile(kerDir, [kernels(ki).name '.mat']) ;
fprintf('\tLoading kernel matrix ''%s''.\n', kerPath) ;
kernels_ = load(kerPath) ;
if ~isfield(kernels_,'mu')
[kernels_.mu] = deal([]) ;
end
if ~isnan(sel)
fprintf('\t\tCutting down data.\n') ;
kernels_.matrix = kernels_.matrix(sel, sel) ;
end
if ~isnan(opts.weights)
fprintf('\t\tWeighing by %g.\n', opts.weights(ki)) ;
kernels_.matrix = kernels_.matrix * opts.weights(ki) ;
end
if opts.squeeze
if isempty(base)
base = zeros(size(kernels_.matrix)) ;
end
base = base + kernels_.matrix ;
else
if isempty(base)
base = zeros([size(kernels_.matrix) K]) ;
end
base(:,:,ki) = kernels_.matrix ;
end
kernels__(ki) = normalizeKernelStructure(kernels_);
clear kernels_ ;
end
kernels = kernels__ ;
clear kernels__ ;
info = whos('base') ;
fprintf('\tKernel matrices size %.2f GB\n', info.bytes / 1024^3) ;
clear info ;
% ------------------------------------------------------------------
function kernel_ = normalizeKernelStructure(kernel)
% ------------------------------------------------------------------
kernel_.type = kernel.type ;
kernel_.feat = kernel.feat ;
kernel_.pyrLevel = kernel.pyrLevel ;
kernel_.histName = kernel.histName ;
kernel_.name = kernel.name ;
|