plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
cssjcai/hihca-master
getInitFCParams.m
.m
hihca-master/codes/layers/getInitFCParams.m
4,544
utf_8
deec7a8250b9e09b81982324fef3484d
function fc_params_init = getInitFCParams(net, imdb, opts) switch opts.pretrainFC case 'lr' if exist(fullfile(opts.modelTrainDir, 'fc_lr_init.mat')) load(fullfile(opts.modelTrainDir, 'fc_lr_init.mat')) ; else train = find(ismember(imdb.images.set, [1 2])); if ~exist(opts.initPolyfeatDir) mkdir(opts.initPolyfeatDir) end initPolyfeatList = dir(fullfile(opts.initPolyfeatDir, '/*.mat')); if numel(initPolyfeatList) == 0 meta = net.meta; meta.augmentation.transformation = 'none'; meta.augmentation.rgbVariance = []; meta.augmentation.numAugments = 1; batchSizeFC = floor(opts.batchSizeFC/meta.augmentation.numAugments); fn_trainFC = getBatchFn(opts, meta); for t=1:opts.batchSizeFC:numel(train) fprintf('Initialization: extracting polynomial features of batch %d/%d\n', ceil(t/batchSizeFC), ceil(numel(train)/batchSizeFC)); batch = train(t:min(numel(train), t+batchSizeFC-1)); inputs = fn_trainFC(imdb, batch); if opts.prefetch nextBatch = train(t+batchSizeFC:min(t+2*batchSizeFC-1, numel(train))); fn_trainFC(imdb, nextBatch); end if opts.gpus net.move('gpu'); end net.mode = 'test'; % net.conserveMemory = false; net.eval(inputs(1:2)); fIdx = net.getVarIndex('l2norm'); polyFea = net.vars(fIdx).value; polyFea = squeeze(gather(polyFea)); for i=1:numel(batch) fea_p = polyFea(:,i); savefast(fullfile(opts.initPolyfeatDir, ['init_polyfeats_', num2str(batch(i), '%05d')]), 'fea_p'); end end if opts.gpus net.move('cpu'); end end % lr learning polydb = imdb; tempStr = sprintf('%05d\t', train); tempStr = textscan(tempStr, '%s', 'delimiter', '\t'); polydb.images.name = strcat('init_polyfeats_', tempStr{1}'); polydb.images.id = polydb.images.id(train); polydb.images.label = polydb.images.label(train); polydb.images.set = polydb.images.set(train); polydb.imageDir = opts.initPolyfeatDir; [trainFV, trainY, valFV, valY] = load_polyfea_fromdisk(polydb); [w, b, acc, map, scores]= train_test_vlfeat('LR', trainFV, trainY, valFV, valY); % reshape the parameters to the input format fc_params_init{1} = reshape(single(w), 1, 1, size(w, 1), size(w, 2)); fc_params_init{2} = single(squeeze(b)); save(fullfile(opts.modelTrainDir, 'fc_lr_init.mat'), 'fc_params_init', '-v7.3'); end case 'random' if exist(fullfile(opts.modelTrainDir, 'fc_ram_init.mat')) load(fullfile(opts.modelTrainDir, 'fc_ram_init.mat')); else numClass = length(unique(imdb.images.label)); scal = 1.0; init_bias = 0.1; fc_params_init{1} = single(0.001/scal *randn(1, 1, opts.fdim, numClass)); fc_params_init{2} = single(init_bias.*ones(1, numClass)); save(fullfile(opts.modelTrainDir, 'fc_ram_init.mat'), 'fc_params_init', '-v7.3'); end end function [trainFV, trainY, valFV, valY] = load_polyfea_fromdisk(polydb) % ------------------------------------------------------------------------- train = find(polydb.images.set==1); trainFV = cell(1, numel(train)); for i = 1:numel(train) load(fullfile(polydb.imageDir, polydb.images.name{train(i)})); trainFV{i} = fea_p; end trainFV = cat(2,trainFV{:}); trainY = polydb.images.label(train)'; val = find(polydb.images.set==2); valFV = cell(1, numel(val)); for i = 1:numel(val) load(fullfile(polydb.imageDir, polydb.images.name{val(i)})); valFV{i} = fea_p; end valFV = cat(2,valFV{:}); valY = polydb.images.label(val)';
github
cssjcai/hihca-master
vl_compile.m
.m
hihca-master/codes/vlfeat/toolbox/vl_compile.m
5,060
utf_8
978f5189bb9b2a16db3368891f79aaa6
function vl_compile(compiler) % VL_COMPILE Compile VLFeat MEX files % VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command % works only under Windows and is used to re-build problematic % binaries. The preferred method of compiling VLFeat on both UNIX % and Windows is through the provided Makefiles. % % VL_COMPILE() only compiles the MEX files and assumes that the % VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has % already been built. This file is built by the Makefiles. % % By default VL_COMPILE() assumes that Visual C++ is the active % MATLAB compiler. VL_COMPILE('lcc') assumes that the active % compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does % not seem to be able to compile the latest versions of VLFeat due % to bugs in the support of 64-bit integers. Therefore it is % recommended to use Visual C++ instead. % % See also: VL_NOPREFIX(), VL_HELP(). % Authors: Andrea Vedadli, Jonghyun Choi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 1, compiler = 'visualc' ; end switch lower(compiler) case 'visualc' fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ; useLcc = false ; case 'lcc' fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ; warning('LCC may fail to compile VLFeat. See help vl_compile.') ; useLcc = true ; otherwise error('Unknown compiler ''%s''.', compiler) end vlDir = vl_root ; toolboxDir = fullfile(vlDir, 'toolbox') ; switch computer case 'PCWIN' fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ; binwDir = fullfile(vlDir, 'bin', 'win32') ; case 'PCWIN64' fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ; binwDir = fullfile(vlDir, 'bin', 'win64') ; otherwise error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ; end impLibPath = fullfile(binwDir, 'vl.lib') ; libDir = fullfile(binwDir, 'vl.dll') ; mkd(mexwDir) ; % find the subdirectories of toolbox that we should process subDirs = dir(toolboxDir) ; subDirs = subDirs([subDirs.isdir]) ; discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ; keep = cellfun('isempty', discard) ; subDirs = subDirs(keep) ; subDirs = {subDirs.name} ; % Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ~exist(fullfile(binwDir, 'vl.dll')) error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ... fullfile(binwDir, 'vl.dll')) ; end tmp = dir(fullfile(binwDir, '*.dll')) ; supportFileNames = {tmp.name} ; for fi = 1:length(supportFileNames) name = supportFileNames{fi} ; cp(fullfile(binwDir, name), ... fullfile(mexwDir, name) ) ; end % Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if useLcc lccImpLibDir = fullfile(mexwDir, 'lcc') ; lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ; lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ; lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ; mkd(lccImpLibDir) ; cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ; cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ; fprintf('Running:\n> %s\n', cmd) ; curPath = pwd ; try cd(lccImpLibDir) ; [d,w] = system(cmd) ; if d, error(w); end cd(curPath) ; catch cd(curPath) ; error(lasterr) ; end end % Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for i = 1:length(subDirs) thisDir = fullfile(toolboxDir, subDirs{i}) ; fileNames = ls(fullfile(thisDir, '*.c')); for f = 1:size(fileNames,1) fileName = fileNames(f, :) ; sp = strfind(fileName, ' '); if length(sp) > 0, fileName = fileName(1:sp-1); end filePath = fullfile(thisDir, fileName); fprintf('MEX %s\n', filePath); dot = strfind(fileName, '.'); mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']); if exist(mexFile) delete(mexFile) end cmd = {['-I' toolboxDir], ... ['-I' vlDir], ... '-O', ... '-outdir', mexwDir, ... filePath } ; if useLcc cmd{end+1} = lccImpLibPath ; else cmd{end+1} = impLibPath ; end mex(cmd{:}) ; end end % -------------------------------------------------------------------- function cp(src,dst) % -------------------------------------------------------------------- if ~exist(dst,'file') fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ; copyfile(src,dst) ; end % -------------------------------------------------------------------- function mkd(dst) % -------------------------------------------------------------------- if ~exist(dst, 'dir') fprintf('Creating directory ''%s''.', dst) ; mkdir(dst) ; end
github
cssjcai/hihca-master
vl_noprefix.m
.m
hihca-master/codes/vlfeat/toolbox/vl_noprefix.m
1,875
utf_8
97d8755f0ba139ac1304bc423d3d86d3
function vl_noprefix % VL_NOPREFIX Create a prefix-less version of VLFeat commands % VL_NOPREFIX() creats prefix-less stubs for VLFeat functions % (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs % are included in the VLFeat binary distribution anyways. Moreover, % on UNIX platforms, the stubs are generally constructed by the % Makefile. % % See also: VL_COMPILE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). root = fileparts(which(mfilename)) ; list = listMFilesX(root); outDir = fullfile(root, 'noprefix') ; if ~exist(outDir, 'dir') mkdir(outDir) ; end for li = 1:length(list) name = list(li).name(1:end-2) ; % remove .m nname = name(4:end) ; % remove vl_ stubPath = fullfile(outDir, [nname '.m']) ; fout = fopen(stubPath, 'w') ; fprintf('Creating stub %s for %s\n', stubPath, nname) ; fprintf(fout, 'function varargout = %s(varargin)\n', nname) ; fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ; fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ; fclose(fout) ; end end function list = listMFilesX(root) list = struct('name', {}, 'path', {}) ; files = dir(root) ; for fi = 1:length(files) name = files(fi).name ; if files(fi).isdir if any(regexp(name, '^(\.|\.\.|noprefix)$')) continue ; else tmp = listMFilesX(fullfile(root, name)) ; list = [list, tmp] ; end end if any(regexp(name, '^vl_(demo|test).*m$')) continue ; elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$')) continue ; elseif any(regexp(name, '\.m$')) list(end+1) = struct(... 'name', {name}, ... 'path', {fullfile(root, name)}) ; end end end
github
cssjcai/hihca-master
vl_pegasos.m
.m
hihca-master/codes/vlfeat/toolbox/misc/vl_pegasos.m
2,837
utf_8
d5e0915c439ece94eb5597a07090b67d
% VL_PEGASOS [deprecated] % VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end % parameters for vl_maketrainingset setvarargin = {}; if (sum(strcmpi('HOMKERMAP',varargin))) setvarargin{end+1} = 'HOMKERMAP'; setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1}; varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[]; varargin(find(strcmpi('HOMKERMAP',varargin),1))=[]; end if (sum(strcmpi('KChi2',varargin))) setvarargin{end+1} = 'KChi2'; varargin(find(strcmpi('KChi2',varargin),1))=[]; end if (sum(strcmpi('KINTERS',varargin))) setvarargin{end+1} = 'KINTERS'; varargin(find(strcmpi('KINTERS',varargin),1))=[]; end if (sum(strcmpi('KL1',varargin))) setvarargin{end+1} = 'KL1'; varargin(find(strcmpi('KL1',varargin),1))=[]; end if (sum(strcmpi('KJS',varargin))) setvarargin{end+1} = 'KJS'; varargin(find(strcmpi('KJS',varargin),1))=[]; end if (sum(strcmpi('Period',varargin))) setvarargin{end+1} = 'Period'; setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1}; varargin(find(strcmpi('Period',varargin),1)+1)=[]; varargin(find(strcmpi('Period',varargin),1))=[]; end if (sum(strcmpi('Window',varargin))) setvarargin{end+1} = 'Window'; setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1}; varargin(find(strcmpi('Window',varargin),1)+1)=[]; varargin(find(strcmpi('Window',varargin),1))=[]; end if (sum(strcmpi('Gamma',varargin))) setvarargin{end+1} = 'Gamma'; setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1}; varargin(find(strcmpi('Gamma',varargin),1)+1)=[]; varargin(find(strcmpi('Gamma',varargin),1))=[]; end setvarargin{:} DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:}); DATA [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
cssjcai/hihca-master
vl_svmpegasos.m
.m
hihca-master/codes/vlfeat/toolbox/misc/vl_svmpegasos.m
1,178
utf_8
009c2a2b87a375d529ed1a4dbe3af59f
% VL_SVMPEGASOS [deprecated] % VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
cssjcai/hihca-master
vl_override.m
.m
hihca-master/codes/vlfeat/toolbox/misc/vl_override.m
4,654
utf_8
e233d2ecaeb68f56034a976060c594c5
function config = vl_override(config,update,varargin) % VL_OVERRIDE Override structure subset % CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds % of the structure UPDATE to the corresponding fields of the % struture CONFIG. % % Usually CONFIG is interpreted as a list of paramters with their % default values and UPDATE as a list of new paramete values. % % VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i) % UPDATE has a field not found in CONFIG, or (ii) non-leaf values of % CONFIG are overwritten. % % VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found % in CONFIG instead of copying them. % % VL_OVERRIDE(..., 'CaseI') matches field names in a % case-insensitive manner. % % Remark:: % Fields are copied at the deepest possible level. For instance, % if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the % structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with % fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the % structure A.B=4, then the field A.B is copied, and VL_OVERRIDE() % returns the structure A.B=4 (specifying 'Warn' would warn about % the fact that the substructure B.C1, B.C2 is being deleted). % % Remark:: % Two fields are matched if they correspond exactly. Specifically, % two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B % match if, and only if, (i) A and B have the same dimensions, % (ii) IA == IB, and (iii) FA == FB. % % See also: VL_ARGPARSE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). warn = false ; skip = false ; err = false ; casei = false ; if length(varargin) == 1 & ~ischar(varargin{1}) % legacy warn = 1 ; end if ~warn & length(varargin) > 0 for i=1:length(varargin) switch lower(varargin{i}) case 'warn' warn = true ; case 'skip' skip = true ; case 'err' err = true ; case 'argparse' argparse = true ; case 'casei' casei = true ; otherwise error(sprintf('Unknown option ''%s''.',varargin{i})) ; end end end % if CONFIG is not a struct array just copy UPDATE verbatim if ~isstruct(config) config = update ; return ; end % if CONFIG is a struct array but UPDATE is not, no match can be % established and we simply copy UPDATE verbatim if ~isstruct(update) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays, but have different % dimensions then nom atch can be established and we simply copy % UPDATE verbatim if numel(update) ~= numel(config) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays of the same % dimension, we override recursively each field for idx=1:numel(update) fields = fieldnames(update) ; for i = 1:length(fields) updateFieldName = fields{i} ; if casei configFieldName = findFieldI(config, updateFieldName) ; else configFieldName = findField(config, updateFieldName) ; end if ~isempty(configFieldName) config(idx).(configFieldName) = ... vl_override(config(idx).(configFieldName), ... update(idx).(updateFieldName)) ; else if warn warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if err error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if skip if warn warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end continue ; end config(idx).(updateFieldName) = update(idx).(updateFieldName) ; end end end % -------------------------------------------------------------------- function field = findFieldI(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmpi(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end % -------------------------------------------------------------------- function field = findField(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmp(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end
github
cssjcai/hihca-master
vl_quickvis.m
.m
hihca-master/codes/vlfeat/toolbox/quickshift/vl_quickvis.m
3,696
utf_8
27f199dad4c5b9c192a5dd3abc59f9da
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts) % VL_QUICKVIS Create an edge image from a Quickshift segmentation. % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. RATIO controls the tradeoff % between color consistency and spatial consistency (See VL_QUICKSEG) and % KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG, % VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which % increase the density. % % VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at % most MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also % returns the DIST thresholds that were chosen. % % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS % specified % % [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) % also returns the MAP and GAPS from VL_QUICKSHIFT. % % See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin == 4 dists = maxdist; maxdist = max(dists); [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); else [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end [Iedge dists] = mapvis(map, gaps, dists); function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts) % MAPVIS Create an edge image from a Quickshift segmentation. % IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. MAXDIST is the maximum % distance between neighbors which increase the density. % % MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most % MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST % thresholds that were chosen. % % IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified % % See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG if nargin == 3 dists = maxdist; maxdist = max(dists); else dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh % throw away min region size instead of maxdist? ind = find(dists < maxdist); dists = dists(ind); if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end Iedge = zeros(size(map)); for i = 1:length(dists) s = find(gaps >= dists(i)); mapdist = map; mapdist(s) = s; [mapped labels] = vl_flatmap(mapdist); fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped))) borders = getborders(mapped); Iedge(borders) = dists(i); %Iedge(borders) = Iedge(borders) + 1; %Iedge(borders) = i; end %%%%%%%%% GETBORDERS function borders = getborders(map) dx = conv2(map, [-1 1], 'same'); dy = conv2(map, [-1 1]', 'same'); borders = find(dx ~= 0 | dy ~= 0);
github
cssjcai/hihca-master
vl_demo_aib.m
.m
hihca-master/codes/vlfeat/toolbox/demo/vl_demo_aib.m
2,928
utf_8
590c6db09451ea608d87bfd094662cac
function vl_demo_aib % VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB) D = 4 ; K = 20 ; randn('state',0) ; rand('state',0) ; X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ; X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ; X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ; figure(1) ; clf ; hold on ; vl_plotframe(X1,'color','r') ; vl_plotframe(X2,'color','g') ; vl_plotframe(X3,'color','b') ; axis equal ; xlim([-4 4]); ylim([-4 4]); axis off ; rectangle('position',D*[-1 -1 2 2]) vl_demo_print('aib_basic_data', .6) ; C = 1:K*K ; Pcx = zeros(3,K*K) ; f1 = quantize(X1,D,K) ; f2 = quantize(X2,D,K) ; f3 = quantize(X3,D,K) ; Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ; Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ; Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ; Pcx = Pcx / sum(Pcx(:)) ; [parents, cost] = vl_aib(Pcx) ; cutsize = [K*K, 10, 3, 2, 1] ; for i=1:length(cutsize) [cut,map,short] = vl_aibcut(parents, cutsize(i)) ; parents_cut(short > 0) = parents(short(short > 0)) ; C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ; figure(i+1) ; clf ; plotquantization(D,K,C) ; hold on ; %plottree(D,K,parents_cut) ; axis equal ; axis off ; title(sprintf('%d clusters', cutsize(i))) ; vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ; end % -------------------------------------------------------------------- function f = quantize(X,D,K) % -------------------------------------------------------------------- d = 2*D / K ; j = round((X(1,:) + D) / d) ; i = round((X(2,:) + D) / d) ; j = max(min(j,K),1) ; i = max(min(i,K),1) ; f = sub2ind([K K],i,j) ; % -------------------------------------------------------------------- function [i,j] = plotquantization(D,K,C) % -------------------------------------------------------------------- hold on ; cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ; d = 2*D / K ; for i=0:K-1 for j=0:K-1 patch(d*(j+[0 1 1 0])-D, ... d*(i+[0 0 1 1])-D, ... cl(C(j*K+i+1),:)) ; end end % -------------------------------------------------------------------- function h = plottree(D,K,parents) % -------------------------------------------------------------------- d = 2*D / K ; C = zeros(2,2*K*K-1)+NaN ; N = zeros(1,2*K*K-1) ; for i=0:K-1 for j=0:K-1 C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ; N(:,j*K+i+1) = 1 ; end end for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; if all(isnan(C(:,i))), continue; end if all(isnan(C(:,p))) C(:,p) = C(:,i) / N(i) ; else C(:,p) = C(:,p) + C(:,i) / N(i) ; end N(p) = N(p) + 1 ; end C(1,:) = C(1,:) ./ N ; C(2,:) = C(2,:) ./ N ; xt = zeros(3, 2*length(parents)-1)+NaN ; yt = zeros(3, 2*length(parents)-1)+NaN ; for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ; yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ; end h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
github
cssjcai/hihca-master
vl_demo_alldist.m
.m
hihca-master/codes/vlfeat/toolbox/demo/vl_demo_alldist.m
5,460
utf_8
6d008a64d93445b9d7199b55d58db7eb
function vl_demo_alldist % numRepetitions = 3 ; numDimensions = 1000 ; numSamplesRange = [300] ; settingsRange = {{'alldist2', 'double', 'l2', }, ... {'alldist', 'double', 'l2', 'nosimd'}, ... {'alldist', 'double', 'l2' }, ... {'alldist2', 'single', 'l2', }, ... {'alldist', 'single', 'l2', 'nosimd'}, ... {'alldist', 'single', 'l2' }, ... {'alldist2', 'double', 'l1', }, ... {'alldist', 'double', 'l1', 'nosimd'}, ... {'alldist', 'double', 'l1' }, ... {'alldist2', 'single', 'l1', }, ... {'alldist', 'single', 'l1', 'nosimd'}, ... {'alldist', 'single', 'l1' }, ... {'alldist2', 'double', 'chi2', }, ... {'alldist', 'double', 'chi2', 'nosimd'}, ... {'alldist', 'double', 'chi2' }, ... {'alldist2', 'single', 'chi2', }, ... {'alldist', 'single', 'chi2', 'nosimd'}, ... {'alldist', 'single', 'chi2' }, ... {'alldist2', 'double', 'hell', }, ... {'alldist', 'double', 'hell', 'nosimd'}, ... {'alldist', 'double', 'hell' }, ... {'alldist2', 'single', 'hell', }, ... {'alldist', 'single', 'hell', 'nosimd'}, ... {'alldist', 'single', 'hell' }, ... {'alldist2', 'double', 'kl2', }, ... {'alldist', 'double', 'kl2', 'nosimd'}, ... {'alldist', 'double', 'kl2' }, ... {'alldist2', 'single', 'kl2', }, ... {'alldist', 'single', 'kl2', 'nosimd'}, ... {'alldist', 'single', 'kl2' }, ... {'alldist2', 'double', 'kl1', }, ... {'alldist', 'double', 'kl1', 'nosimd'}, ... {'alldist', 'double', 'kl1' }, ... {'alldist2', 'single', 'kl1', }, ... {'alldist', 'single', 'kl1', 'nosimd'}, ... {'alldist', 'single', 'kl1' }, ... {'alldist2', 'double', 'kchi2', }, ... {'alldist', 'double', 'kchi2', 'nosimd'}, ... {'alldist', 'double', 'kchi2' }, ... {'alldist2', 'single', 'kchi2', }, ... {'alldist', 'single', 'kchi2', 'nosimd'}, ... {'alldist', 'single', 'kchi2' }, ... {'alldist2', 'double', 'khell', }, ... {'alldist', 'double', 'khell', 'nosimd'}, ... {'alldist', 'double', 'khell' }, ... {'alldist2', 'single', 'khell', }, ... {'alldist', 'single', 'khell', 'nosimd'}, ... {'alldist', 'single', 'khell' }, ... } ; %settingsRange = settingsRange(end-5:end) ; styles = {} ; for marker={'x','+','.','*','o'} for color={'r','g','b','k','y'} styles{end+1} = {'color', char(color), 'marker', char(marker)} ; end end for ni=1:length(numSamplesRange) for ti=1:length(settingsRange) tocs = [] ; for ri=1:numRepetitions rand('state',ri) ; randn('state',ri) ; numSamples = numSamplesRange(ni) ; settings = settingsRange{ti} ; [tocs(end+1), D] = run_experiment(numDimensions, ... numSamples, ... settings) ; end means(ni,ti) = mean(tocs) ; stds(ni,ti) = std(tocs) ; if mod(ti-1,3) == 0 D0 = D ; else err = max(abs(D(:)-D0(:))) ; fprintf('err %f\n', err) ; if err > 1, keyboard ; end end end end if 0 figure(1) ; clf ; hold on ; numStyles = length(styles) ; for ti=1:length(settingsRange) si = mod(ti - 1, numStyles) + 1 ; h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ; leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ; end end for ti=1:length(settingsRange) leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; end figure(1) ; clf ; barh(means(end,:)) ; set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ; xlabel('Time [s]') ; function [elaps, D] = run_experiment(numDimensions, numSamples, settings) distType = 'l2' ; algType = 'alldist' ; classType = 'double' ; useSimd = true ; for si=1:length(settings) arg = settings{si} ; switch arg case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'} distType = arg ; case {'alldist', 'alldist2'} algType = arg ; case {'single', 'double'} classType = arg ; case 'simd' useSimd = true ; case 'nosimd' useSimd = false ; otherwise assert(false) ; end end X = rand(numDimensions, numSamples) ; X(X < .3) = 0 ; switch classType case 'double' case 'single' X = single(X) ; end vl_simdctrl(double(useSimd)) ; switch algType case 'alldist' tic ; D = vl_alldist(X, distType) ; elaps = toc ; case 'alldist2' tic ; D = vl_alldist2(X, distType) ; elaps = toc ; end
github
cssjcai/hihca-master
vl_demo_ikmeans.m
.m
hihca-master/codes/vlfeat/toolbox/demo/vl_demo_ikmeans.m
774
utf_8
17ff0bb7259d390fb4f91ea937ba7de0
function vl_demo_ikmeans() % VL_DEMO_IKMEANS numData = 10000 ; dimension = 2 ; data = uint8(255*rand(dimension,numData)) ; numClusters = 3^3 ; [centers, assignments] = vl_ikmeans(data, numClusters); figure(1) ; clf ; axis off ; plotClusters(data, centers, assignments) ; vl_demo_print('ikmeans_2d',0.6); [tree, assignments] = vl_hikmeans(data,3,numClusters) ; figure(2) ; clf ; axis off ; plotClusters(data, [], [4 2 1] * double(assignments)) ; vl_demo_print('hikmeans_2d',0.6); function plotClusters(data, centers, assignments) hold on ; cc=jet(double(max(assignments(:)))); for i=1:max(assignments(:)) plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:)); end if ~isempty(centers) plot(centers(1,:),centers(2,:),'k.','MarkerSize',20) end
github
cssjcai/hihca-master
vl_demo_svm.m
.m
hihca-master/codes/vlfeat/toolbox/demo/vl_demo_svm.m
1,235
utf_8
7cf6b3504e4fc2cbd10ff3fec6e331a7
% VL_DEMO_SVM Demo: SVM: 2D linear learning function vl_demo_svm y=[];X=[]; % Load training data X and their labels y load('vl_demo_svm_data.mat') Xp = X(:,y==1); Xn = X(:,y==-1); figure plot(Xn(1,:),Xn(2,:),'*r') hold on plot(Xp(1,:),Xp(2,:),'*b') axis equal ; vl_demo_print('svm_training') ; % Parameters lambda = 0.01 ; % Regularization parameter maxIter = 1000 ; % Maximum number of iterations energy = [] ; % Diagnostic function function diagnostics(svm) energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ; end % Training the SVM energy = [] ; [w b info] = vl_svmtrain(X, y, lambda,... 'MaxNumIterations',maxIter,... 'DiagnosticFunction',@diagnostics,... 'DiagnosticFrequency',1) % Visualisation eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)]; line = ezplot(eq, [-0.9 0.9 -0.9 0.9]); set(line, 'Color', [0 0.8 0],'linewidth', 2); vl_demo_print('svm_training_result') ; figure hold on plot(energy(1,:),'--b') ; plot(energy(2,:),'-.g') ; plot(energy(3,:),'r') ; legend('Primal objective','Dual objective','Duality gap') xlabel('Diagnostics iteration') ylabel('Energy') vl_demo_print('svm_energy') ; end
github
cssjcai/hihca-master
vl_demo_kdtree_sift.m
.m
hihca-master/codes/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m
6,832
utf_8
e676f80ac330a351f0110533c6ebba89
function vl_demo_kdtree_sift % VL_DEMO_KDTREE_SIFT % Demonstrates the use of a kd-tree forest to match SIFT % features. If FLANN is present, this function runs a comparison % against it. % AUTORIGHS rand('state',0) ; randn('state',0); do_median = 0 ; do_mean = 1 ; % try to setup flann if ~exist('flann_search', 'file') if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ; end end do_flann = exist('nearest_neighbors') == 3 ; if ~do_flann warning('FLANN not found. Comparison disabled.') ; end maxNumComparisonsRange = [1 10 50 100 200 300 400] ; numTreesRange = [1 2 5 10] ; % get data (SIFT features) im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ; im1 = single(rgb2gray(im1)) ; im2 = single(rgb2gray(im2)) ; [f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ; [f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ; % add some noise to make matches unique d1 = single(d1) + rand(size(d1)) ; d2 = single(d2) + rand(size(d2)) ; % match exhaustively to get the ground truth elapsedDirect = tic ; D = vl_alldist(d1,d2) ; [drop, best] = min(D, [], 1) ; elapsedDirect = toc(elapsedDirect) ; for ti=1:length(numTreesRange) for vi=1:length(maxNumComparisonsRange) v = maxNumComparisonsRange(vi) ; t = numTreesRange(ti) ; if do_median tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'median', ... 'numtrees', t) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons',v) ; elapsedKD_median(vi,ti) = toc ; errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_mean tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'mean', ... 'numtrees', t) ; %kdtree = readflann(kdtree, '/tmp/flann.txt') ; %checkx(kdtree, d1, 1, 1) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons', v) ; elapsedKD_mean(vi,ti) = toc ; errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_flann tic ; [i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ... 'trees', t, ... 'checks', v)); ifla = i ; elapsedKD_flann(vi,ti) = toc; errors_flann(vi,ti) = sum(i ~= best) / length(best) ; errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ; end end end figure(1) ; clf ; leg = {} ; hnd = [] ; sty = {{'color','r'},{'color','g'},... {'color','b'},{'color','c'},... {'color','k'}} ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('percentage of incorrect matches (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_incorrect',.6) ; figure(2) ; clf ; leg = {} ; hnd = [] ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('relative overestimation of minmium distannce (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_distortion',.6) ; % -------------------------------------------------------------------- function checkx(kdtree, X, t, n, mib, mab) % -------------------------------------------------------------------- if nargin <= 4 mib = -inf * ones(size(X,1),1) ; mab = +inf * ones(size(X,1),1) ; end lc = kdtree.trees(t).nodes.lowerChild(n) ; uc = kdtree.trees(t).nodes.upperChild(n) ; if lc < 0 for i=-lc:-uc-1 di = kdtree.trees(t).dataIndex(i) ; if any(X(:,di) > mab) error('a') ; end if any(X(:,di) < mib) error('b') ; end end return end i = kdtree.trees(t).nodes.splitDimension(n) ; v = kdtree.trees(t).nodes.splitThreshold(n) ; mab_ = mab ; mab_(i) = min(mab(i), v) ; checkx(kdtree, X, t, lc, mib, mab_) ; mib_ = mib ; mib_(i) = max(mib(i), v) ; checkx(kdtree, X, t, uc, mib_, mab) ; % -------------------------------------------------------------------- function kdtree = readflann(kdtree, path) % -------------------------------------------------------------------- data = textread(path)' ; for i=1:size(data,2) nodeIds = data(1,:) ; ni = find(nodeIds == data(1,i)) ; if ~isnan(data(2,i)) % internal node li = find(nodeIds == data(4,i)) ; ri = find(nodeIds == data(5,i)) ; kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ; kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ; kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ; kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ; else di = data(3,i) + 1 ; kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ; kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ; end kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ; end
github
cssjcai/hihca-master
vl_impattern.m
.m
hihca-master/codes/vlfeat/toolbox/imop/vl_impattern.m
6,876
utf_8
1716a4d107f0186be3d11c647bc628ce
function im = vl_impattern(varargin) % VL_IMPATTERN Generate an image from a stock pattern % IM=VLPATTERN(NAME) returns an instance of the specified % pattern. These stock patterns are useful for testing algoirthms. % % All generated patterns are returned as an image of class % DOUBLE. Both gray-scale and colour images have range in [0,1]. % % VL_IMPATTERN() without arguments shows a gallery of the stock % patterns. The following patterns are supported: % % Wedge:: % The image of a wedge. % % Cone:: % The image of a cone. % % SmoothChecker:: % A checkerboard with Gaussian filtering on top. Use the % option-value pair 'sigma', SIGMA to specify the standard % deviation of the smoothing and the pair 'step', STEP to specfity % the checker size in pixels. % % ThreeDotsSquare:: % A pattern with three small dots and two squares. % % UniformNoise:: % Random i.i.d. noise. % % Blobs: % Gaussian blobs of various sizes and anisotropies. % % Blobs1: % Gaussian blobs of various orientations and anisotropies. % % Blob: % One Gaussian blob. Use the option-value pairs 'sigma', % 'orientation', and 'anisotropy' to specify the respective % parameters. 'sigma' is the scalar standard deviation of an % isotropic blob (the image domain is the rectangle % [-1,1]^2). 'orientation' is the clockwise rotation (as the Y % axis points downards). 'anisotropy' (>= 1) is the ratio of the % the largest over the smallest axis of the blob (the smallest % axis length is set by 'sigma'). Set 'cut' to TRUE to cut half % half of the blob. % % A stock image:: % Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'. % % All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but % the stock images, the default size is [128,128]. % Author: Andrea Vedaldi % Copyright (C) 2012 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin > 0 pattern=varargin{1} ; varargin=varargin(2:end) ; else pattern = 'gallery' ; end patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ... 'blob', 'blobs', 'blobs1', ... 'box', 'roofs1', 'roofs2', 'river1', 'river2'} ; % spooling switch lower(pattern) case 'wedge', im = wedge(varargin) ; case 'cone', im = cone(varargin) ; case 'smoothchecker', im = smoothChecker(varargin) ; case 'threedotssquare', im = threeDotSquare(varargin) ; case 'uniformnoise', im = uniformNoise(varargin) ; case 'blob', im = blob(varargin) ; case 'blobs', im = blobs(varargin) ; case 'blobs1', im = blobs1(varargin) ; case {'box','roofs1','roofs2','river1','river2','spots'} im = stockImage(pattern, varargin) ; case 'gallery' clf ; num = numel(patterns) ; for p = 1:num vl_tightsubplot(num,p,'box','outer') ; imagesc(vl_impattern(patterns{p}),[0 1]) ; axis image off ; title(patterns{p}) ; end colormap gray ; return ; otherwise error('Unknown patter ''%s''.', pattern) ; end if nargout == 0 clf ; imagesc(im) ; hold on ; colormap gray ; axis image off ; title(pattern) ; clear im ; end function [u,v,opts,args] = commonOpts(args) opts.size = [128 128] ; [opts,args] = vl_argparse(opts, args) ; ur = linspace(-1,1,opts.size(2)) ; vr = linspace(-1,1,opts.size(1)) ; [u,v] = meshgrid(ur,vr); function im = wedge(args) [u,v,opts,args] = commonOpts(args) ; im = abs(u) + abs(v) > (1/4) ; im(v < 0) = 0 ; function im = cone(args) [u,v,opts,args] = commonOpts(args) ; im = sqrt(u.^2+v.^2) ; im = im / max(im(:)) ; function im = smoothChecker(args) opts.size = [128 128] ; opts.step = 16 ; opts.sigma = 2 ; opts = vl_argparse(opts, args) ; [u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ; im = xor((mod(u,opts.step*2) < opts.step),... (mod(v,opts.step*2) < opts.step)) ; im = double(im) ; im = vl_imsmooth(im, opts.sigma) ; function im = threeDotSquare(args) [u,v,opts,args] = commonOpts(args) ; im = ones(size(u)) ; im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ; im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ; [drop,i] = min(abs(v(:,1))) ; [drop,j1] = min(abs(u(1,:)-1/6)) ; [drop,j2] = min(abs(u(1,:))) ; [drop,j3] = min(abs(u(1,:)+1/6)) ; im(i,j1) = 0 ; im(i,j2) = 0 ; im(i,j3) = 0 ; function im = blobs(args) [u,v,opts,args] = commonOpts(args) ; im = zeros(size(u)) ; num = 5 ; square = 2 / num ; sigma = square / 2 / 3 ; scales = logspace(log10(0.5), log10(1), num) ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ; C = inv(A'*A) ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = blob(args) [u,v,opts,args] = commonOpts(args) ; opts.sigma = 0.15 ; opts.anisotropy = .5 ; opts.orientation = 2/3 * pi ; opts.cut = false ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; th = opts.orientation ; R = [cos(th) -sin(th) ; sin(th) cos(th)] ; A = opts.sigma * R * diag([opts.anisotropy 1]) ; T = [0;0] ; [x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ; im = exp(-0.5 *(x.^2 + y.^2)) ; if opts.cut im = im .* double(x > 0) ; end function im = blobs1(args) [u,v,opts,args] = commonOpts(args) ; opts.number = 5 ; opts.sigma = [] ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; square = 2 / opts.number ; num = opts.number ; if isempty(opts.sigma) sigma = 1/6 * square ; else sigma = opts.sigma * square ; end rotations = linspace(0,pi,num+1) ; rotations(end) = [] ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; th = rotations(i) ; R = [cos(th) -sin(th); sin(th) cos(th)] ; A = sigma * R * diag([1 1/skews(j)]) ; C = inv(A*A') ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = uniformNoise(args) opts.size = [128 128] ; opts.seed = 1 ; opts = vl_argparse(opts, args) ; state = vl_twister('state') ; vl_twister('state',opts.seed) ; im = vl_twister(opts.size([2 1])) ; vl_twister('state',state) ; function im = stockImage(pattern,args) opts.size = [] ; opts = vl_argparse(opts, args) ; switch pattern case 'river1', path='river1.jpg' ; case 'river2', path='river2.jpg' ; case 'roofs1', path='roofs1.jpg' ; case 'roofs2', path='roofs2.jpg' ; case 'box', path='box.pgm' ; case 'spots', path='spots.jpg' ; end im = imread(fullfile(vl_root,'data',path)) ; im = im2double(im) ; if ~isempty(opts.size) im = imresize(im, opts.size) ; im = max(im,0) ; im = min(im,1) ; end
github
cssjcai/hihca-master
vl_tpsu.m
.m
hihca-master/codes/vlfeat/toolbox/imop/vl_tpsu.m
1,755
utf_8
09f36e1a707c069b375eb2817d0e5f13
function [U,dU,delta]=vl_tpsu(X,Y) % VL_TPSU Compute the U matrix of a thin-plate spline transformation % U=VL_TPSU(X,Y) returns the matrix % % [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ] % [ ] % [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ] % % where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is % the opposite -r^2 log(r^2) of the radial basis function of the % thin plate spline specified by X and Y. % % [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with % respect to the parameters Y. The derivatives are arranged in a % Mx2xN array, one layer per column of U. % % See also: VL_TPS(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if exist('tpsumx') U = tpsumx(X,Y) ; else M=size(X,2) ; N=size(Y,2) ; % Faster than repmat, but still fairly slow r2 = ... (X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ... (X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ; U = - rb(r2) ; end if nargout > 1 M=size(X,2) ; N=size(Y,2) ; dx = X( ones(N,1), :)' - Y( ones(1,M), :) ; dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ; r2 = (dx.^2 + dy.^2) ; r = sqrt(r2) ; coeff = drb(r)./(r+eps) ; dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ; end % The radial basis function function y = rb(r2) y = zeros(size(r2)) ; sel = find(r2 ~= 0) ; y(sel) = - r2(sel) .* log(r2(sel)) ; % The derivative of the radial basis function function y = drb(r) y = zeros(size(r)) ; sel = find(r ~= 0) ; y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
github
cssjcai/hihca-master
vl_xyz2lab.m
.m
hihca-master/codes/vlfeat/toolbox/imop/vl_xyz2lab.m
1,570
utf_8
09f95a6f9ae19c22486ec1157357f0e3
function J=vl_xyz2lab(I,il) % VL_XYZ2LAB Convert XYZ color space to LAB % J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format. % % VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55, % D65, D75, D93. The default illuminatn is E. % % See also: VL_XYZ2LUV(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 2 il='E' ; end switch lower(il) case 'a' xw = 0.4476 ; yw = 0.4074 ; case 'b' xw = 0.3324 ; yw = 0.3474 ; case 'c' xw = 0.3101 ; yw = 0.3162 ; case 'e' xw = 1/3 ; yw = 1/3 ; case 'd50' xw = 0.3457 ; yw = 0.3585 ; case 'd55' xw = 0.3324 ; yw = 0.3474 ; case 'd65' xw = 0.312713 ; yw = 0.329016 ; case 'd75' xw = 0.299 ; yw = 0.3149 ; case 'd93' xw = 0.2848 ; yw = 0.2932 ; end J=zeros(size(I)) ; % Reference white Yw = 1.0 ; Xw = xw/yw ; Zw = (1-xw-yw)/yw * Yw ; % XYZ components X = I(:,:,1) ; Y = I(:,:,2) ; Z = I(:,:,3) ; x = X/Xw ; y = Y/Yw ; z = Z/Zw ; L = 116 * f(y) - 16 ; a = 500*(f(x) - f(y)) ; b = 200*(f(y) - f(z)) ; J = cat(3,L,a,b) ; % -------------------------------------------------------------------- function b=f(a) % -------------------------------------------------------------------- sp = find(a > 0.00856) ; sm = find(a <= 0.00856) ; k = 903.3 ; b=zeros(size(a)) ; b(sp) = a(sp).^(1/3) ; b(sm) = (k*a(sm) + 16)/116 ;
github
cssjcai/hihca-master
vl_test_gmm.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_gmm.m
1,332
utf_8
76782cae6c98781c6c38d4cbf5549d94
function results = vl_test_gmm(varargin) % VL_TEST_GMM % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). vl_test_init ; end function s = setup() randn('state',0) ; s.X = randn(128, 1000) ; end function test_multithreading(s) dataTypes = {'single','double'} ; for dataType = dataTypes conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; vl_threads(0) ; [means, covariances, priors, ll, posteriors] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_twister('state',0) ; vl_threads(1) ; [means_, covariances_, priors_, ll_, posteriors_] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_assert_almost_equal(means, means_, 1e-2) ; vl_assert_almost_equal(covariances, covariances_, 1e-2) ; vl_assert_almost_equal(priors, priors_, 1e-2) ; vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ; vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ; end end
github
cssjcai/hihca-master
vl_test_twister.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_twister.m
1,251
utf_8
2bfb5a30cbd6df6ac80c66b73f8646da
function results = vl_test_twister(varargin) % VL_TEST_TWISTER vl_test_init ; function test_illegal_args() vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ; function test_seed_by_scalar() rand('twister',1) ; a = rand ; vl_twister('state',1) ; b = vl_twister ; vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ; function test_get_set_state() rand('twister',1) ; a = rand('twister') ; vl_twister('state',1) ; b = vl_twister('state') ; vl_assert_equal(a,b,'read state') ; a(1) = a(1) + 1 ; vl_twister('state',a) ; b = vl_twister('state') ; vl_assert_equal(a,b,'set state') ; function test_multi_dimensions() b = rand('twister') ; rand('twister',b) ; vl_twister('state',b) ; a=rand([1 2 3 4 5]) ; b=vl_twister([1 2 3 4 5]) ; vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ; function test_multi_multi_args() rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ; vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ; vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ; function test_square() rand('twister',1) ; a=rand(10) ; vl_twister('state',1) ; b=vl_twister(10) ; vl_assert_equal(a,b,'VL_TWISTER(N)') ;
github
cssjcai/hihca-master
vl_test_kdtree.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_kdtree.m
2,449
utf_8
9d7ad2b435a88c22084b38e5eb5f9eb9
function results = vl_test_kdtree(varargin) % VL_TEST_KDTREE vl_test_init ; function s = setup() randn('state',0) ; s.X = single(randn(10, 1000)) ; s.Q = single(randn(10, 10)) ; function test_nearest(s) for tmethod = {'median', 'mean'} for type = {@single, @double} conv = type{1} ; tmethod = char(tmethod) ; X = conv(s.X) ; Q = conv(s.Q) ; tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ; [nn, d2] = vl_kdtreequery(tree, X, Q) ; D2 = vl_alldist2(X, Q, 'l2') ; [d2_, nn_] = min(D2) ; vl_assert_equal(... nn,uint32(nn_),... 'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ; vl_assert_almost_equal(... d2,d2_,... 'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ; end end function test_nearests(s) numNeighbors = 7 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; vl_assert_equal(nn,uint32(nn_)) ; vl_assert_almost_equal(d2,d2_) ; function test_ann(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 50 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end function test_ann_forest(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 25 ; numTrees = 5 ; tree = vl_kdtreebuild(s.X, 'numTrees', 5) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end
github
cssjcai/hihca-master
vl_test_imwbackward.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_imwbackward.m
514
utf_8
33baa0784c8f6f785a2951d7f1b49199
function results = vl_test_imwbackward(varargin) % VL_TEST_IMWBACKWARD vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; function test_identity(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ; function test_invalid_args(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
github
cssjcai/hihca-master
vl_test_alphanum.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_alphanum.m
1,624
utf_8
2da2b768c2d0f86d699b8f31614aa424
function results = vl_test_alphanum(varargin) % VL_TEST_ALPHANUM vl_test_init ; function s = setup() s.strings = ... {'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ; s.sortedStrings = ... {'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ; function test_basic(s) sorted = vl_alphanum(s.strings) ; assert(isequal(sorted,s.sortedStrings)) ;
github
cssjcai/hihca-master
vl_test_printsize.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_printsize.m
1,447
utf_8
0f0b6437c648b7a2e1310900262bd765
function results = vl_test_printsize(varargin) % VL_TEST_PRINTSIZE vl_test_init ; function s = setup() s.fig = figure(1) ; s.usletter = [8.5, 11] ; % inches s.a4 = [8.26772, 11.6929] ; clf(s.fig) ; plot(1:10) ; function teardown(s) close(s.fig) ; function test_basic(s) for sigma = [1 0.5 0.2] vl_printsize(s.fig, sigma) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ; vl_assert_almost_equal(pos(1), 0, 1e-4) ; vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ; end function test_papertype(s) vl_printsize(s.fig, 1, 'papertype', 'a4') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ; function test_margin(s) m = 0.5 ; vl_printsize(s.fig, 1, 'margin', m) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ; vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ; function test_reference(s) sigma = 1 ; vl_printsize(s.fig, 1, 'reference', 'vertical') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ; vl_assert_almost_equal(pos(2), 0, 1e-4) ; vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
github
cssjcai/hihca-master
vl_test_cummax.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_cummax.m
838
utf_8
5e98ee1681d4823f32ecc4feaa218611
function results = vl_test_cummax(varargin) % VL_TEST_CUMMAX vl_test_init ; function test_basic() vl_assert_almost_equal(... vl_cummax(1), 1) ; vl_assert_almost_equal(... vl_cummax([1 2 3 4], 2), [1 2 3 4]) ; function test_multidim() a = [1 2 3 4 3 2 1] ; b = [1 2 3 4 4 4 4] ; for k=1:6 dims = ones(1,6) ; dims(k) = numel(a) ; a = reshape(a, dims) ; b = reshape(b, dims) ; vl_assert_almost_equal(... vl_cummax(a, k), b) ; end function test_storage_classes() types = {@double, @single, ... @int32, @uint32, ... @int16, @uint16, ... @int8, @uint8} ; if vl_matlabversion() > 71000 types = horzcat(types, {@int64, @uint64}) ; end for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ; end end
github
cssjcai/hihca-master
vl_test_imintegral.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_imintegral.m
1,429
utf_8
4750f04ab0ac9fc4f55df2c8583e5498
function results = vl_test_imintegral(varargin) % VL_TEST_IMINTEGRAL vl_test_init ; function state = setup() state.I = ones(5,6) ; state.correct = [ 1 2 3 4 5 6 ; 2 4 6 8 10 12 ; 3 6 9 12 15 18 ; 4 8 12 16 20 24 ; 5 10 15 20 25 30 ; ] ; function test_matlab_equivalent(s) vl_assert_equal(slow_imintegral(s.I), s.correct) ; function test_basic(s) vl_assert_equal(vl_imintegral(s.I), s.correct) ; function test_multi_dimensional(s) vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ... repmat(s.correct, [1 1 3])) ; function test_random(s) numTests = 50 ; for i = 1:numTests I = rand(5) ; vl_assert_almost_equal(vl_imintegral(s.I), ... slow_imintegral(s.I)) ; end function test_datatypes(s) vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ; vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ; vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ; function integral = slow_imintegral(I) integral = zeros(size(I)); for k = 1:size(I,3) for r = 1:size(I,1) for c = 1:size(I,2) integral(r,c,k) = sum(sum(I(1:r,1:c,k))); end end end
github
cssjcai/hihca-master
vl_test_sift.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_sift.m
1,318
utf_8
806c61f9db9f2ebb1d649c9bfcf3dc0a
function results = vl_test_sift(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ; [s.ubc.f, s.ubc.d] = ... vl_ubcread(fullfile(vl_root,'data','box.sift')) ; function test_ubc_descriptor(s) err = [] ; [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'frames', s.ubc.f) ; D2 = vl_alldist(f, s.ubc.f) ; [drop, perm] = min(D2) ; f = f(:,perm) ; d = d(:,perm) ; error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ... / mean(sqrt(sum(single(s.ubc.d).^2))) ; assert(error < 0.1, ... 'sift descriptor did not produce desctiptors similar to UBC ones') ; function test_ubc_detector(s) [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'peakthresh', .01, ... 'edgethresh', 10) ; s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ; f(4,:) = mod(f(4,:), 2*pi) ; % scale the components so that 1 pixel erro in x,y,z is equal to a % 10-th of angle. S = diag([1 1 1 20/pi]); D2 = vl_alldist(S * s.ubc.f, S * f) ; [d2,perm] = sort(min(D2)) ; error = sqrt(d2) ; quant80 = round(.8 * size(f,2)) ; % check for less than one pixel error at 80% quantile assert(error(quant80) < 1, ... 'sift detector did not produce enough keypoints similar to UBC ones') ;
github
cssjcai/hihca-master
vl_test_binsum.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_binsum.m
1,377
utf_8
f07f0f29ba6afe0111c967ab0b353a9d
function results = vl_test_binsum(varargin) % VL_TEST_BINSUM vl_test_init ; function test_three_args() vl_assert_almost_equal(... vl_binsum([0 0], 1, 2), [0 1]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, 1), [0 7]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ; function test_four_args() vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ; function test_3d_one() Z = zeros(3,3,3) ; B = 3*ones(3,1,3) ; R = Z ; R(:,3,:) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, 17, B, 2), R) ; function test_3d_two() Z = zeros(3,3,3) ; B = 3*ones(3,3,1) ; X = zeros(3,3,1) ; X(:,:,1) = 17 ; R = Z ; R(:,:,3) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, X, B, 3), R) ; function test_storage_classes() types = {@double, @single, ... @int32, @uint32, ... @int16, @uint16, ... @int8, @uint8} ; if vl_matlabversion() > 71000 types = horzcat(types, {@int64, @uint64}) ; end for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ; end end
github
cssjcai/hihca-master
vl_test_lbp.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_lbp.m
892
utf_8
a79c0ce0c85e25c0b1657f3a0b499538
function results = vl_test_lbp(varargin) % VL_TEST_TWISTER vl_test_init ; function test_unfiorm_lbps(s) % enumerate the 56 uniform lbps q = 0 ; for i=0:7 for j=1:7 I = zeros(3) ; p = mod(s.pixels - i + 8, 8) + 1 ; I(p <= j) = 1 ; f = vl_lbp(single(I), 3) ; q = q + 1 ; vl_assert_equal(find(f), q) ; end end % constant lbps I = [1 1 1 ; 1 0 1 ; 1 1 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 57) ; I = [1 1 1 ; 1 1 1 ; 1 1 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 57) ; % other lbps I = [1 0 1 ; 0 0 0 ; 1 0 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 58) ; function test_fliplr(s) randn('state',0) ; I = randn(256,256,1,'single') ; f = vl_lbp(fliplr(I), 8) ; f_ = vl_lbpfliplr(vl_lbp(I, 8)) ; vl_assert_almost_equal(f,f_,1e-3) ; function s = setup() s.pixels = [5 6 7 ; 4 NaN 0 ; 3 2 1] ;
github
cssjcai/hihca-master
vl_test_colsubset.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_colsubset.m
828
utf_8
be0c080007445b36333b863326fb0f15
function results = vl_test_colsubset(varargin) % VL_TEST_COLSUBSET vl_test_init ; function s = setup() s.x = [5 2 3 6 4 7 1 9 8 0] ; function test_beginning(s) vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ; vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ; function test_ending(s) vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ; vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ; function test_largest(s) vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ; vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ; function test_smallest(s) vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ; vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ; function test_random(s) assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
github
cssjcai/hihca-master
vl_test_alldist.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_alldist.m
2,373
utf_8
9ea1a36c97fe715dfa2b8693876808ff
function results = vl_test_alldist(varargin) % VL_TEST_ALLDIST vl_test_init ; function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js', ... 'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y), ... @(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ; types = {'single', 'double'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; vl_assert_almost_equal(... vl_alldist(X,Y,dists{d}), ... makedist(distsEquiv{d},X,Y), ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist(X,X,ker) ; kyy = vl_alldist(Y,Y,ker) ; kxy = vl_alldist(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
cssjcai/hihca-master
vl_test_ihashsum.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_ihashsum.m
581
utf_8
edc283062469af62056b0782b171f5fc
function results = vl_test_ihashsum(varargin) % VL_TEST_IHASHSUM vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(round(16*rand(2,100))) ; sel = find(all(s.data==0)) ; s.data(1,sel)=1 ; function test_hash(s) D = size(s.data,1) ; K = 5 ; h = zeros(1,K,'uint32') ; id = zeros(D,K,'uint8'); next = zeros(1,K,'uint32') ; [h,id,next] = vl_ihashsum(h,id,next,K,s.data) ; sel = vl_ihashfind(id,next,K,s.data) ; count = double(h(sel)) ; [drop,i,j] = unique(s.data','rows') ; for k=1:size(s.data,2) count_(k) = sum(j == j(k)) ; end vl_assert_equal(count,count_) ;
github
cssjcai/hihca-master
vl_test_grad.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_grad.m
434
utf_8
4d03eb33a6a4f68659f868da95930ffb
function results = vl_test_grad(varargin) % VL_TEST_GRAD vl_test_init ; function s = setup() s.I = rand(150,253) ; s.I_small = rand(2,2) ; function test_equiv(s) vl_assert_equal(gradient(s.I), vl_grad(s.I)) ; function test_equiv_small(s) vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ; function test_equiv_forward(s) Ix = diff(s.I,2,1) ; Iy = diff(s.I,2,1) ; vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
github
cssjcai/hihca-master
vl_test_whistc.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_whistc.m
1,384
utf_8
81c446d35c82957659840ab2a579ec2c
function results = vl_test_whistc(varargin) % VL_TEST_WHISTC vl_test_init ; function test_acc() x = ones(1, 10) ; e = 1 ; o = 1:10 ; vl_assert_equal(vl_whistc(x, o, e), 55) ; function test_basic() x = 1:10 ; e = 1:10 ; o = ones(1, 10) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; x = linspace(-1,11,100) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; function test_multidim() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_nan() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; x(1:7:end) = NaN ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_no_edges() x = rand(10, 20, 30) ; o = ones(size(x)) ; vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ; vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ; vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ; vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ; vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
github
cssjcai/hihca-master
vl_test_roc.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_roc.m
1,019
utf_8
9b2ae71c9dc3eda0fc54c65d55054d0c
function results = vl_test_roc(varargin) % VL_TEST_ROC vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ; function test_perfect_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(info.eer, 0) ; vl_assert_almost_equal(info.auc, 1) ; function test_swap1_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ; function test_swap1_tptn_stable(s) [tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ; function test_swap1_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(info.eer, 1/3) ; vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
github
cssjcai/hihca-master
vl_test_dsift.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_dsift.m
2,048
utf_8
fbbfb16d5a21936c1862d9551f657ccc
function results = vl_test_dsift(varargin) % VL_TEST_DSIFT vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = rgb2gray(single(I)) ; function test_fast_slow(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSize = 5 ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; [f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors', ... 'fast') ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift fast approximation not close') ; function test_sift(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSizeRange = [1 1.2 5] ; for wi = 1:length(windowSizeRange) windowSize = windowSizeRange(wi) ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; numKeys = size(f, 2) ; f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ; [f_, d_] = vl_sift(s.I, ... 'magnif', magnif, ... 'frames', f_, ... 'firstoctave', -1, ... 'levels', 5, ... 'floatdescriptors', ... 'windowsize', windowSize) ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift and sift equivalence') ; end
github
cssjcai/hihca-master
vl_test_alldist2.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_alldist2.m
2,284
utf_8
89a787e3d83516653ae8d99c808b9d67
function results = vl_test_alldist2(varargin) % VL_TEST_ALLDIST vl_test_init ; % TODO: test integer classes function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist2(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', ... 'kchi2', 'kl2', 'kl1', 'khell'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y)}; types = {'single', 'double', 'sparse'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; a = vl_alldist2(X,Y,dists{d}) ; b = makedist(distsEquiv{d},X,Y) ; vl_assert_almost_equal(a,b, ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist2(X,X,ker) ; kyy = vl_alldist2(Y,Y,ker) ; kxy = vl_alldist2(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist2(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
cssjcai/hihca-master
vl_test_fisher.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_fisher.m
2,097
utf_8
c9afd9ab635bd412cbf8be3c2d235f6b
function results = vl_test_fisher(varargin) % VL_TEST_FISHER vl_test_init ; function s = setup() randn('state',0) ; dimension = 5 ; numData = 21 ; numComponents = 3 ; s.x = randn(dimension,numData) ; s.mu = randn(dimension,numComponents) ; s.sigma2 = ones(dimension,numComponents) ; s.prior = ones(1,numComponents) ; s.prior = s.prior / sum(s.prior) ; function test_basic(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_norm(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_sqrt(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_improved(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_fast(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function enc = simple_fisher(x, mu, sigma2, pri, fast) if nargin < 5, fast = false ; end sigma = sqrt(sigma2) ; for k = 1:size(mu,2) delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ; q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ; end q = exp(bsxfun(@minus, q, max(q,[],1))) ; q = bsxfun(@times, q, 1 ./ sum(q,1)) ; n = size(x,2) ; if fast [~,i] = max(q) ; q = zeros(size(q)) ; q(sub2ind(size(q),i,1:n)) = 1 ; end for k = 1:size(mu,2) u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ; v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ; end enc = cat(1, u{:}, v{:}) ;
github
cssjcai/hihca-master
vl_test_imsmooth.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_imsmooth.m
1,837
utf_8
718235242cad61c9804ba5e881c22f59
function results = vl_test_imsmooth(varargin) % VL_TEST_IMSMOOTH vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; I = max(min(vl_imdown(I),1),0) ; s.I = single(I) ; function test_pad_by_continuity(s) % Convolving a constant signal padded with continuity does not change % the signal. I = ones(3) ; for ker = {'triangular', 'gaussian'} ker = char(ker) ; J = vl_imsmooth(I, 2, ... 'kernel', ker, ... 'padding', 'continuity') ; vl_assert_almost_equal(J, I, 1e-4, ... 'padding by continutiy with kernel = %s', ker) ; end function test_kernels(s) for ker = {'triangular', 'gaussian'} ker = char(ker) ; for type = {@single, @double} for simd = [0 1] for sigma = [1 2 7] for step = [1 2 3] vl_simdctrl(simd) ; conv = type{1} ; g = equivalent_kernel(ker, sigma) ; J = vl_imsmooth(conv(s.I), sigma, ... 'kernel', ker, ... 'padding', 'zero', ... 'subsample', step) ; J_ = conv(convolve(s.I, g, step)) ; vl_assert_almost_equal(J, J_, 1e-4, ... 'kernel=%s sigma=%f step=%d simd=%d', ... ker, sigma, step, simd) ; end end end end end function g = equivalent_kernel(ker, sigma) switch ker case 'gaussian' W = ceil(4*sigma) ; g = exp(-.5*((-W:W)/(sigma+eps)).^2) ; case 'triangular' W = max(round(sigma),1) ; g = W - abs(-W+1:W-1) ; end g = g / sum(g) ; function I = convolve(I, g, step) if strcmp(class(I),'single') g = single(g) ; else g = double(g) ; end for k=1:size(I,3) I(:,:,k) = conv2(g,g,I(:,:,k),'same'); end I = I(1:step:end,1:step:end,:) ;
github
cssjcai/hihca-master
vl_test_svmtrain.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_svmtrain.m
4,277
utf_8
071b7c66191a22e8236fda16752b27aa
function results = vl_test_svmtrain(varargin) % VL_TEST_SVMTRAIN vl_test_init ; end function s = setup() randn('state',0) ; Np = 10 ; Nn = 10 ; xp = diag([1 3])*randn(2, Np) ; xn = diag([1 3])*randn(2, Nn) ; xp(1,:) = xp(1,:) + 2 + 1 ; xn(1,:) = xn(1,:) - 2 + 1 ; s.x = [xp xn] ; s.y = [ones(1,Np) -ones(1,Nn)] ; s.lambda = 0.01 ; s.biasMultiplier = 10 ; if 0 figure(1) ; clf; vl_plotframe(xp, 'g') ; hold on ; vl_plotframe(xn, 'r') ; axis equal ; grid on ; end % Run LibSVM as an accuate solver to compare results with. Note that % LibSVM optimizes a slightly different cost function due to the way % the bias is handled. % [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ; s.w = [1.180762951236242; 0.098366470721632] ; s.b = -1.540018443946204 ; s.obj = obj(s, s.w, s.b) ; end function test_sgd_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sgd', ... 'BiasMultiplier', s.biasMultiplier, ... 'BiasLearningRate', 1/s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % there are no absolute guarantees on the objective gap, but % the heuristic SGD uses as stopping criterion seems reasonable % within a factor 10 at least. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-2) ; end end function test_sdca_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % the gap with the accurate solver cannot be % greater than the duality gap. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-3) ; end end function test_weights(s) for algo = {'sgd', 'sdca'} for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; numRepeats = 10 ; pos = find(s.y > 0) ; neg = find(s.y < 0) ; weights = ones(1, numel(s.y)) ; weights(pos) = numRepeats ; % simulate weighting by repeating positives [w b info] = vl_svmtrain(... s.x(:, [repmat(pos,1,numRepeats) neg]), ... s.y(:, [repmat(pos,1,numRepeats) neg]), ... s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4) ; % apply weigthing [w_ b_ info_] = vl_svmtrain(... s.x, ... s.y, ... s.lambda, ... 'Solver', char(algo), ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4, ... 'Weights', weights) ; vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ; end end end function test_homkermap(s) for solver = {'sgd', 'sdca'} for conv = {@single,@double} conv = conv{1} ; dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ; vl_twister('state',0) ; [w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ; x_hom = vl_homkermap(conv(s.x), 1) ; vl_twister('state',0) ; [w b] = vl_svmtrain(x_hom, s.y, s.lambda) ; vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ; end end end function [w,b] = accurate_solver(X, y, lambda, biasMultiplier) addpath opt/libsvm/matlab/ N = size(X,2) ; model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ; w = X(:,model.SVs) * model.sv_coef ; b = - model.rho ; format long ; disp('model w:') disp(w) disp('bias b:') disp(b) end function o = obj(s, w, b) o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ; end
github
cssjcai/hihca-master
vl_test_phow.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_phow.m
549
utf_8
f761a3bb218af855986263c67b2da411
function results = vl_test_phow(varargin) % VL_TEST_PHOPW vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = single(s.I) ; function test_gray(s) [f,d] = vl_phow(s.I, 'color', 'gray') ; assert(size(d,1) == 128) ; function test_rgb(s) [f,d] = vl_phow(s.I, 'color', 'rgb') ; assert(size(d,1) == 128*3) ; function test_hsv(s) [f,d] = vl_phow(s.I, 'color', 'hsv') ; assert(size(d,1) == 128*3) ; function test_opponent(s) [f,d] = vl_phow(s.I, 'color', 'opponent') ; assert(size(d,1) == 128*3) ;
github
cssjcai/hihca-master
vl_test_kmeans.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_kmeans.m
3,632
utf_8
0e1d6f4f8101c8982a0e743e0980c65a
function results = vl_test_kmeans(varargin) % VL_TEST_KMEANS % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). vl_test_init ; function s = setup() randn('state',0) ; s.X = randn(128, 100) ; function test_basic(s) [centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ; [centers_, assignments_, en_] = simpleKMeans(s.X, 10) ; assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ; function test_algorithms(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; [centers, assignments, en] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Lloyd', ... 'Distance', distance) ; vl_twister('state',0) ; [centers_, assignments_, en_] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Elkan', ... 'Distance', distance) ; vl_twister('state',0) ; [centers__, assignments__, en__] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'ANN', ... 'Distance', distance, ... 'NumTrees', 3, ... 'MaxNumComparisons',0) ; vl_assert_almost_equal(centers, centers_, 1e-5) ; vl_assert_almost_equal(assignments, assignments_, 1e-5) ; vl_assert_almost_equal(en, en_, 1e-4) ; vl_assert_almost_equal(centers, centers__, 1e-5) ; vl_assert_almost_equal(assignments, assignments__, 1e-5) ; vl_assert_almost_equal(en, en__, 1e-4) ; vl_assert_almost_equal(centers_, centers__, 1e-5) ; vl_assert_almost_equal(assignments_, assignments__, 1e-5) ; vl_assert_almost_equal(en_, en__, 1e-4) ; end end function test_patterns(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; data = [1 1 0 0 ; 1 0 1 0] ; data = conversion(data) ; [centers, assignments, en] = vl_kmeans(data, 4, ... 'NumRepetitions', 100, ... 'Distance', distance) ; assert(isempty(setdiff(data', centers', 'rows'))) ; end end function [centers, assignments, en] = simpleKMeans(X, numCenters) [dimension, numData] = size(X) ; centers = randn(dimension, numCenters) ; for iter = 1:10 [dists, assignments] = min(vl_alldist(centers, X)) ; en = sum(dists) ; centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ; centers = vl_binsum(centers, ... [X ; ones(1,numData)], ... repmat(assignments, dimension+1, 1), 2) ; centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ; end
github
cssjcai/hihca-master
vl_test_hikmeans.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_hikmeans.m
463
utf_8
dc3b493646e66316184e86ff4e6138ab
function results = vl_test_hikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [tree, assign] = vl_hikmeans(s.data,3,100) ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ;
github
cssjcai/hihca-master
vl_test_aib.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_aib.m
1,277
utf_8
78978ae54e7ebe991d136336ba4bf9c6
function results = vl_test_aib(varargin) % VL_TEST_AIB vl_test_init ; function s = setup() s = [] ; function test_basic(s) Pcx = [.3 .3 0 0 0 0 .2 .2] ; % This results in the AIB tree % % 1 - \ % 5 - \ % 2 - / \ % - 7 % 3 - \ / % 6 - / % 4 - / % % coded by the map [5 5 6 6 7 1] (1 denotes the root). [parents,cost] = vl_aib(Pcx) ; vl_assert_equal(parents, [5 5 6 6 7 7 1]) ; vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ; [cut,map,short] = vl_aibcut(parents,2) ; vl_assert_equal(cut, [5 6]) ; vl_assert_equal(map, [1 1 2 2 1 2 0]) ; vl_assert_equal(short, [5 5 6 6 5 6 7]) ; function test_cluster_null(s) Pcx = [.5 .5 0 0 0 0 0 0] ; % This results in the AIB tree % % 1 - \ % 5 % 2 - / % % 3 x % % 4 x % % If ClusterNull is specified, the values 3 and 4 % which have zero probability are merged first % % 1 ----------\ % 7 % 2 ----- \ / % 6-/ % 3 -\ / % 5 -/ % 4 -/ parents1 = vl_aib(Pcx) ; parents2 = vl_aib(Pcx,'ClusterNull') ; vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ; vl_assert_equal(parents2(3), parents2(4)) ; function x = mi(P) % mutual information P1 = sum(P,1) ; P2 = sum(P,2) ; x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
github
cssjcai/hihca-master
vl_test_plotbox.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_plotbox.m
414
utf_8
aa06ce4932a213fb933bbede6072b029
function results = vl_test_plotbox(varargin) % VL_TEST_PLOTBOX vl_test_init ; function test_basic(s) figure(1) ; clf ; vl_plotbox([-1 -1 1 1]') ; xlim([-2 2]) ; ylim([-2 2]) ; close(1) ; function test_multiple(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10)) ; close(1) ; function test_style(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ; close(1) ;
github
cssjcai/hihca-master
vl_test_imarray.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_imarray.m
795
utf_8
c5e6a5aa8c2e63e248814f5bd89832a8
function results = vl_test_imarray(varargin) % VL_TEST_IMARRAY vl_test_init ; function test_movie_rgb(s) A = rand(23,15,3,4) ; B = vl_imarray(A,'movie',true) ; function test_movie_indexed(s) cmap = get(0,'DefaultFigureColormap') ; A = uint8(size(cmap,1)*rand(23,15,4)) ; A = min(A,size(cmap,1)-1) ; B = vl_imarray(A,'movie',true) ; function test_movie_gray_indexed(s) A = uint8(255*rand(23,15,4)) ; B = vl_imarray(A,'movie',true,'cmap',gray(256)) ; for k=1:size(A,3) vl_assert_equal(squeeze(A(:,:,k)), ... frame2im(B(k))) ; end function test_basic(s) M = 3 ; N = 4 ; width = 32 ; height = 15 ; for i=1:M for j=1:N A{i,j} = rand(width,height) ; end end A1 = A'; A1 = cat(3,A1{:}) ; A2 = cell2mat(A) ; B = vl_imarray(A1, 'layout', [M N]) ; vl_assert_equal(A2,B) ;
github
cssjcai/hihca-master
vl_test_homkermap.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_homkermap.m
1,903
utf_8
c157052bf4213793a961bde1f73fb307
function results = vl_test_homkermap(varargin) % VL_TEST_HOMKERMAP vl_test_init ; function check_ker(ker, n, window, period) args = {n, ker, 'window', window} ; if nargin > 3 args = {args{:}, 'period', period} ; end x = [-1 -.5 0 .5 1] ; y = linspace(0,2,100) ; for conv = {@single, @double} x = feval(conv{1}, x) ; y = feval(conv{1}, y) ; sx = sign(x) ; sy = sign(y) ; psix = vl_homkermap(x, args{:}) ; psiy = vl_homkermap(y, args{:}) ; k = vl_alldist(psix,psiy,'kl2') ; k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ; vl_assert_almost_equal(k, k_, 2e-2) ; end function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ; function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ; function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ; function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ; function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ; function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ; function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ; function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ; function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ; function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ; function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ; function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ; function test_gamma() x = linspace(0,1,20) ; for gamma = linspace(.2,2,10) k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ; psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ; assert(norm(k - psix'*psix) < 1e-2) ; end function test_negative() x = linspace(-1,1,20) ; k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ; psix = vl_homkermap(x, 3, 'kchi2') ; assert(norm(k - psix'*psix) < 1e-2) ;
github
cssjcai/hihca-master
vl_test_slic.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_slic.m
200
utf_8
12a6465e3ef5b4bcfd7303cd8a9229d4
function results = vl_test_slic(varargin) % VL_TEST_SLIC vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; function test_slic(s) segmentation = vl_slic(s.im, 10, 0.1) ;
github
cssjcai/hihca-master
vl_test_ikmeans.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_ikmeans.m
466
utf_8
1ee2f647ac0035ed0d704a0cd615b040
function results = vl_test_ikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [centers, assign] = vl_ikmeans(s.data,100) ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ;
github
cssjcai/hihca-master
vl_test_mser.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_mser.m
242
utf_8
1ad33563b0c86542a2978ee94e0f4a39
function results = vl_test_mser(varargin) % VL_TEST_MSER vl_test_init ; function s = setup() s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ; function test_mser(s) [regions,frames] = vl_mser(s.im) ; mask = vl_erfill(s.im, regions(1)) ;
github
cssjcai/hihca-master
vl_test_inthist.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_inthist.m
811
utf_8
459027d0c54d8f197563a02ab66ef45d
function results = vl_test_inthist(varargin) % VL_TEST_INTHIST vl_test_init ; function s = setup() rand('state',0) ; s.labels = uint32(8*rand(123, 76, 3)) ; function test_basic(s) l = 10 ; hist = vl_inthist(s.labels, 'numlabels', l) ; hist_ = inthist_slow(s.labels, l) ; vl_assert_equal(double(hist),hist_) ; function test_sample(s) rand('state',0) ; boxes = 10 * rand(4,20) + .5 ; boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ; boxes = min(boxes, 10) ; boxes = uint32(boxes) ; inthist = vl_inthist(s.labels) ; hist = vl_sampleinthist(inthist, boxes) ; function hist = inthist_slow(labels, numLabels) m = size(labels,1) ; n = size(labels,2) ; l = numLabels ; b = zeros(m*n,l) ; b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ; b = reshape(b,m,n,l) ; for k=1:l hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ; end
github
cssjcai/hihca-master
vl_test_imdisttf.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_imdisttf.m
1,885
utf_8
ae921197988abeb984cbcdf9eaf80e77
function results = vl_test_imdisttf(varargin) % VL_TEST_DISTTF vl_test_init ; function test_basic() for conv = {@single, @double} conv = conv{1} ; I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ; D = vl_imdisttf(I); assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ; I(2,2) = -3 ; [D,map] = vl_imdisttf(I) ; assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ; assert(isequal(map, 5 * ones(3))) ; end function test_1x1() assert(isequal(1, vl_imdisttf(1))) ; function test_rand() I = rand(13,31) ; for t=1:4 param = [rand randn rand randn] ; [D0,map0] = imdisttf_equiv(I,param) ; [D,map] = vl_imdisttf(I,param) ; vl_assert_almost_equal(D,D0,1e-10) assert(isequal(map,map0)) ; end function test_param() I = zeros(3,4) ; I(1,1) = -1 ; [D,map] = vl_imdisttf(I,[1 0 1 0]); assert(isequal(-[1 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ;], D)) ; D0 = -[1 .9 .6 .1 ; 0 0 0 0 ; 0 0 0 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[1 .9 .6 .1 ; .9 .8 .5 0 ; .6 .5 .2 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 .1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[.9 1 .9 .6 ; .8 .9 .8 .5 ; .5 .6 .5 .2 ; ] ; [D,map] = vl_imdisttf(I,[.1 1 .1 0]); vl_assert_almost_equal(D,D0,1e-10); function test_special() I = rand(13,31) -.5 ; D = vl_imdisttf(I, [0 0 1e5 0]) ; vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10); D = vl_imdisttf(I, [1e5 0 0 0]) ; vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10); function [D,map]=imdisttf_equiv(I,param) D = inf + zeros(size(I)) ; map = zeros(size(I)) ; ur = 1:size(D,2) ; vr = 1:size(D,1) ; [u,v] = meshgrid(ur,vr) ; for v_=vr for u_=ur E = I(v_,u_) + ... param(1) * (u - u_ - param(2)).^2 + ... param(3) * (v - v_ - param(4)).^2 ; map(E < D) = sub2ind(size(I),v_,u_) ; D = min(D,E) ; end end
github
cssjcai/hihca-master
vl_test_vlad.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_vlad.m
1,977
utf_8
d3797288d6edb1d445b890db3780c8ce
function results = vl_test_vlad(varargin) % VL_TEST_VLAD vl_test_init ; function s = setup() randn('state',0) ; s.x = randn(128,256) ; s.mu = randn(128,16) ; assignments = rand(16, 256) ; s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ; function test_basic (s) x = [1, 2, 3] ; mu = [0, 0, 0] ; assignments = eye(3) ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 2 3]') ; mu = [0, 1, 2] ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 1 1]') ; phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ; vl_assert_equal(phi, [2 2 2]') ; function test_rand (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ; vl_assert_equal(phi, phi_) ; function test_norm (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments) ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_sqrt (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_individual (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_mass (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function enc = simple_vlad(x, mu, assign) for i = 1:size(assign,1) enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ; end enc = cat(1, enc{:}) ;
github
cssjcai/hihca-master
vl_test_pr.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_pr.m
3,763
utf_8
4d1da5ccda1a7df2bec35b8f12fdd620
function results = vl_test_pr(varargin) % VL_TEST_PR vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ; function test_perfect_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(info.auc, 1) ; vl_assert_almost_equal(info.ap, 1) ; vl_assert_almost_equal(info.ap_interp_11, 1) ; function test_swap1_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ; function test_swap1_tptn_stable(s) [rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ; vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ; function test_swap1_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores1) ; clf; vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ; vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ; vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ; function test_inf(s) scores = [1 -inf -1 -1 -1 -1] ; labels = [1 1 -1 -1 -1 -1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ; vl_assert_equal(numel(rc1), numel(rc2) + 1) ; vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ; vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ; vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ; vl_assert_almost_equal(info2.auc, 0.5) ; vl_assert_almost_equal(info2.ap, 0.5) ; vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ; function test_inf_stable(s) scores = [-1 -1 -1 -1 -inf +1] ; labels = [-1 -1 -1 -1 +1 +1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ; [rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ; [rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ; % stability does not change scores vl_assert_almost_equal(info1,info1_) ; vl_assert_almost_equal(info2,info2_) ; % unstable with inf (first point (0,1) is conventional) vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1]) vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6]) % unstable without inf vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5]) vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5]) % stable with inf (no conventional point here) vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ; vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ; % stable without inf (no conventional point and -inf are NaN) vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ; vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ; function test_normalised_pr(s) scores = [+1 +2] ; labels = [+1 -1] ; [rc1,pr1,info1] = vl_pr(labels,scores) ; [rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ; vl_assert_almost_equal(pr1, pr2) ; vl_assert_almost_equal(rc1, rc2) ; scores_ = [+1 +2 +2 +2] ; labels_ = [+1 -1 -1 -1] ; [rc3,pr3,info3] = vl_pr(labels_,scores_) ; [rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ; vl_assert_almost_equal(info3, info4) ; function test_normalised_pr_corner_cases(s) scores = 1:10 ; labels = ones(1,10) ; [rc1,pr1,info1] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc1, (0:10)/10) ; vl_assert_almost_equal(pr1, ones(1,11)) ; scores = 1:10 ; labels = zeros(1,10) ; [rc2,pr2,info2] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc2, zeros(1,11)) ; vl_assert_almost_equal(pr2, ones(1,11)) ;
github
cssjcai/hihca-master
vl_test_hog.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_hog.m
1,555
utf_8
eed7b2a116d142040587dc9c4eb7cd2e
function results = vl_test_hog(varargin) % VL_TEST_HOG vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; [x,y]= meshgrid(linspace(-1,1,128)) ; s.round = single(x.^2+y.^2); s.imSmall = s.im(1:128,1:128,:) ; s.imSmall = s.im ; s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ; function test_basic_call(s) cellSize = 8 ; hog = vl_hog(s.im, cellSize) ; function test_bilinear_orientations(s) cellSize = 8 ; vl_hog(s.im, cellSize, 'bilinearOrientations') ; function test_variants_and_flipping(s) variants = {'uoctti', 'dalaltriggs'} ; numOrientationsRange = 3:9 ; cellSize = 8 ; for cellSize = [4 8 16] for i=1:numel(variants) for j=1:numel(numOrientationsRange) args = {'bilinearOrientations', ... 'variant', variants{i}, ... 'numOrientations', numOrientationsRange(j)} ; hog = vl_hog(s.imSmall, cellSize, args{:}) ; perm = vl_hog('permutation', args{:}) ; hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ; hog2 = hog(:,end:-1:1,perm) ; %norm(hog1(:)-hog2(:)) vl_assert_almost_equal(hog1,hog2,1e-3) ; end end end function test_polar(s) cellSize = 8 ; im = s.round ; for b = [0 1] if b args = {'bilinearOrientations'} ; else args = {} ; end hog1 = vl_hog(im, cellSize, args{:}) ; [ix,iy] = vl_grad(im) ; m = sqrt(ix.^2 + iy.^2) ; a = atan2(iy,ix) ; m(:,[1 end]) = 0 ; m([1 end],:) = 0 ; hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ; vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ; end
github
cssjcai/hihca-master
vl_test_argparse.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_argparse.m
795
utf_8
e72185b27206d0ee1dfdc19fe77a5be6
function results = vl_test_argparse(varargin) % VL_TEST_ARGPARSE vl_test_init ; function test_basic() opts.field1 = 1 ; opts.field2 = 2 ; opts.field3 = 3 ; opts_ = opts ; opts_.field1 = 3 ; opts_.field2 = 10 ; opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ; assert(isequal(opts, opts_)) ; opts_.field1 = 9 ; opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ; assert(isequal(opts, opts_)) ; function test_error() opts.field1 = 1 ; try opts = vl_argparse(opts, {'field2', 5}) ; catch e return ; end assert(false) ; function test_leftovers() opts1.field1 = 1 ; opts2.field2 = 1 ; opts1_.field1 = 2 ; opts2_.field2 = 2 ; [opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ; opts2 = vl_argparse(opts2, args) ; assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
github
cssjcai/hihca-master
vl_test_liop.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_liop.m
1,023
utf_8
a162be369073bed18e61210f44088cf3
function results = vl_test_liop(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() randn('state',0) ; s.patch = randn(65,'single') ; xr = -32:32 ; [x,y] = meshgrid(xr) ; s.blob = - single(x.^2+y.^2) ; function test_basic(s) d = vl_liop(s.patch) ; function test_blob(s) % with a blob, all local intensity order pattern are equal. In % particular, if the blob intensity decreases away from the center, % then all local intensities sampled in a neighbourhood of 2 elements % are already sorted (see LIOP details). d = vl_liop(s.blob, ... 'IntensityThreshold', 0, ... 'NumNeighbours', 2, ... 'NumSpatialBins', 1) ; assert(isequal(d, single([1;0]))) ; function test_neighbours(s) for n=2:5 for p=1:3 d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ; assert(numel(d) == p * factorial(n)) ; end end function test_multiple(s) x = randn(31,31,3, 'single') ; d = vl_liop(x) ; for i=1:3 d_(:,i) = vl_liop(squeeze(x(:,:,i))) ; end assert(isequal(d,d_)) ;
github
cssjcai/hihca-master
vl_test_binsearch.m
.m
hihca-master/codes/vlfeat/toolbox/xtest/vl_test_binsearch.m
1,339
utf_8
85dc020adce3f228fe7dfb24cf3acc63
function results = vl_test_binsearch(varargin) % VL_TEST_BINSEARCH vl_test_init ; function test_inf_bins() x = [-inf -1 0 1 +inf] ; vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ; vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ; vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ; vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ; function test_empty() vl_assert_equal(vl_binsearch([], []), []) ; function test_bnd() vl_assert_equal(vl_binsearch([], [1]), [0]) ; vl_assert_equal(vl_binsearch([], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([], [+inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [.9]), [0]) ; vl_assert_equal(vl_binsearch([1], [1]), [1]) ; vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ; function test_basic() vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ; vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ; vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ; function test_frac() vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10)) vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ... fliplr(floor(1:.5:10))) ; function test_array() a = reshape(1:100,10,10) ; b = reshape(1:.5:100.5, 2, []) ; c = floor(b) ; vl_assert_equal(vl_binsearch(a,b), c) ;
github
cssjcai/hihca-master
vl_roc.m
.m
hihca-master/codes/vlfeat/toolbox/plotop/vl_roc.m
10,113
utf_8
22fd8ff455ee62a96ffd94b9074eafeb
function [tpr,tnr,info] = vl_roc(labels, scores, varargin) %VL_ROC ROC curve. % [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating % Characteristic (ROC) curve [1]. LABELS is a row vector of ground % truth labels, greater than zero for a positive sample and smaller % than zero for a negative one. SCORES is a row vector of % corresponding sample scores, usually obtained from a % classifier. The scores induce a ranking of the samples where % larger scores should correspond to positive labels. % % Without output arguments, the function plots the ROC graph of the % specified data in the current graphical axis. % % Otherwise, the function returns the true positive and true % negative rates TPR and TNR. These are vectors of the same size of % LABELS and SCORES and are computed as follows. Samples are ranked % by decreasing scores, starting from rank 1. TPR(K) and TNR(K) are % the true positive and true negative rates when samples of rank % smaller or equal to K-1 are predicted to be positive. So for % example TPR(3) is the true positive rate when the two samples with % largest score are predicted to be positive. Similarly, TPR(1) is % the true positive rate when no samples are predicted to be % positive, i.e. the constant 0. % % Setting a label to zero ignores the corresponding sample in the % calculations, as if the sample was removed from the data. Setting % the score of a sample to -INF causes the function to assume that % that sample was never retrieved. If there are samples with -INF % score, the ROC curve is incomplete as the maximum recall is less % than 1. % % [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO % with the following fields: % % info.auc:: Area under the ROC curve (AUC). % This is the area under the ROC plot, the parametric curve % (FPR(S), TPR(S)). The PLOT option can be used to plot variants % of this curve, which affects the calculation of a corresponding % AUC. % % info.eer:: Equal error rate (EER). % The equal error rate is the value of FPR (or FNR) when the ROC % curves intersects the line connecting (0,0) to (1,1). % % info.eerThreshold:: EER threshold. % The value of the score for which the EER is attained. % % VL_ROC() accepts the following options: % % Plot:: [] % Setting this option turns on plotting unconditionally. The % following plot variants are supported: % % tntp:: Plot TPR against TNR (standard ROC plot). % tptn:: Plot TNR against TPR (recall on the horizontal axis). % fptp:: Plot TPR against FPR. % fpfn:: Plot FNR against FPR (similar to a DET curve). % % Note that this option will affect the INFO.AUC value computation % too. % % NumPositives:: [] % NumNegatives:: [] % If either of these parameters is set to a number, the function % pretends that LABELS contains the specified number of % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entries in % LABELS. The additional positive/negative labels are appended to % the end of the sequence as if they had -INF scores (as explained % above, the function interprets such samples as `not % retrieved'). This feature can be used to evaluate the % performance of a large-scale retrieval experiment in which only % a subset of highly-scoring results are recorded for efficiency % reason. % % Stable:: false % If set to true, TPR and TNR are returned in the same order % of LABELS and SCORES rather than being sorted by decreasing % score. % % About the ROC curve:: % Consider a classifier that predicts as positive all samples whose % score is not smaller than a threshold S. The ROC curve represents % the performance of such classifier as the threshold S is % changed. Formally, define % % P = overall num. of positive samples, % N = overall num. of negative samples, % % and for each threshold S % % TP(S) = num. of samples that are correctly classified as positive, % TN(S) = num. of samples that are correctly classified as negative, % FP(S) = num. of samples that are incorrectly classified as positive, % FN(S) = num. of samples that are incorrectly classified as negative. % % Consider also the rates: % % TPR = TP(S) / P, FNR = FN(S) / P, % TNR = TN(S) / N, FPR = FP(S) / N, % % and notice that, by definition, % % P = TP(S) + FN(S) , N = TN(S) + FP(S), % 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S). % % The ROC curve is the parametric curve (FPR(S), TPR(S)) obtained % as the classifier threshold S is varied in the reals. The TPR is % the same as `recall' in a PR curve (see VL_PR()). % % The ROC curve is contained in the square with vertices (0,0) The % (average) ROC curve of a random classifier is a line which % connects (1,0) and (0,1). % % The ROC curve is independent of the prior probability of the % labels (i.e. of P/(P+N) and N/(P+N)). % % REFERENCES: % [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic % % See also: VL_PR(), VL_DET(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.plot = [] ; opts.stable = false ; opts = vl_argparse(opts,varargin) ; % compute the rates small = 1e-10 ; tpr = tp / max(p, small) ; fpr = fp / max(n, small) ; fnr = 1 - tpr ; tnr = 1 - fpr ; do_plots = ~isempty(opts.plot) || nargout == 0 ; if isempty(opts.plot), opts.plot = 'fptp' ; end % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || do_plots % Area under the curve. Since the curve is a staircase (in the % sense that for each sample either tn is decremented by one % or tp is incremented by one but the other remains fixed), % the integral is particularly simple and exact. switch opts.plot case 'tntp', info.auc = -sum(tpr .* diff([0 tnr])) ; case 'fptp', info.auc = +sum(tpr .* diff([0 fpr])) ; case 'tptn', info.auc = +sum(tnr .* diff([0 tpr])) ; case 'fpfn', info.auc = +sum(fnr .* diff([0 fpr])) ; otherwise error('''%s'' is not a valid PLOT type.', opts.plot); end % Equal error rate. One must find the index S in correspondence of % which TNR(S) and TPR(s) cross. Note that TPR(S) is non-decreasing, % TNR(S) is non-increasing, and from rank S to rank S+1 only one of % the two quantities can change. Hence there are exactly two types % of crossing points: % % 1) TNR(S) = TNR(S+1) = EER and TPR(S) <= EER, TPR(S+1) > EER, % 2) TPR(S) = TPR(S+1) = EER and TNR(S) > EER, TNR(S+1) <= EER. % % Moreover, if the maximum TPR is smaller than 1, then it is % possible that neither of the two cases realizes. In the latter % case, we return EER=NaN. s = max(find(tnr > tpr)) ; if s == length(tpr) info.eer = NaN ; info.eerThreshold = 0 ; else if tpr(s) == tpr(s+1) info.eer = 1 - tpr(s) ; else info.eer = 1 - tnr(s) ; end info.eerThreshold = scores(perm(s)) ; end end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if do_plots cla ; hold on ; switch lower(opts.plot) case 'tntp' hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true negative rate') ; ylabel('true positive rate (recall)') ; loc = 'sw' ; case 'fptp' hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ; spline([1 0], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive rate') ; ylabel('true positive rate (recall)') ; loc = 'se' ; case 'tptn' hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true positive rate (recall)') ; ylabel('false positive rate') ; loc = 'sw' ; case 'fpfn' hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive (false alarm) rate') ; ylabel('false negative (miss) rate') ; loc = 'ne' ; otherwise error('''%s'' is not a valid PLOT type.', opts.plot); end grid on ; xlim([0 1]) ; ylim([0 1]) ; axis square ; title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ... 'interpreter', 'none') ; legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable tpr(1) = [] ; tnr(1) = [] ; tpr_ = tpr ; tnr_ = tnr ; tpr = NaN(size(tpr)) ; tnr = NaN(size(tnr)) ; tpr(perm) = tpr_ ; tnr(perm) = tnr_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
cssjcai/hihca-master
vl_click.m
.m
hihca-master/codes/vlfeat/toolbox/plotop/vl_click.m
2,661
utf_8
6982e869cf80da57fdf68f5ebcd05a86
function P = vl_click(N,varargin) ; % VL_CLICK Click a point % P=VL_CLICK() let the user click a point in the current figure and % returns its coordinates in P. P is a two dimensiona vectors where % P(1) is the point X-coordinate and P(2) the point Y-coordinate. The % user can abort the operation by pressing any key, in which case the % empty matrix is returned. % % P=VL_CLICK(N) lets the user select N points in a row. The user can % stop inserting points by pressing any key, in which case the % partial list is returned. % % VL_CLICK() accepts the following options: % % PlotMarker:: [0] % Plot a marker as points are selected. The markers are deleted on % exiting the function. % % See also: VL_CLICKPOINT(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). plot_marker = 0 ; for k=1:2:length(varargin) switch lower(varargin{k}) case 'plotmarker' plot_marker = varargin{k+1} ; otherwise error(['Uknown option ''', varargin{k}, '''.']) ; end end if nargin < 1 N=1; end % -------------------------------------------------------------------- % Do job % -------------------------------------------------------------------- fig = gcf ; is_hold = ishold ; hold on ; bhandler = get(fig,'WindowButtonDownFcn') ; khandler = get(fig,'KeyPressFcn') ; pointer = get(fig,'Pointer') ; set(fig,'WindowButtonDownFcn',@click_handler) ; set(fig,'KeyPressFcn',@key_handler) ; set(fig,'Pointer','crosshair') ; P=[] ; h=[] ; data.exit=0; guidata(fig,data) ; while size(P,2) < N uiwait(fig) ; data = guidata(fig) ; if(data.exit) break ; end P = [P data.P] ; if( plot_marker ) h=[h plot(data.P(1),data.P(2),'rx')] ; end end if ~is_hold hold off ; end if( plot_marker ) pause(.1); delete(h) ; end set(fig,'WindowButtonDownFcn',bhandler) ; set(fig,'KeyPressFcn',khandler) ; set(fig,'Pointer',pointer) ; % ==================================================================== function click_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; P = get(gca, 'CurrentPoint') ; P = [P(1,1); P(1,2)] ; data.P = P ; guidata(obj,data) ; uiresume(gcbo) ; % ==================================================================== function key_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; data.exit = 1 ; guidata(obj,data) ; uiresume(gcbo) ;
github
cssjcai/hihca-master
vl_pr.m
.m
hihca-master/codes/vlfeat/toolbox/plotop/vl_pr.m
9,138
utf_8
c7fe6832d2b6b9917896810c52a05479
function [recall, precision, info] = vl_pr(labels, scores, varargin) %VL_PR Precision-recall curve. % [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the % precision-recall (PR) curve. LABELS are the ground truth labels, % greather than zero for a positive sample and smaller than zero for % a negative one. SCORES are the scores of the samples obtained from % a classifier, where lager scores should correspond to positive % samples. % % Samples are ranked by decreasing scores, starting from rank 1. % PRECISION(K) and RECALL(K) are the precison and recall when % samples of rank smaller or equal to K-1 are predicted to be % positive and the remaining to be negative. So for example % PRECISION(3) is the percentage of positive samples among the two % samples with largest score. PRECISION(1) is the precision when no % samples are predicted to be positive and is conventionally set to % the value 1. % % Set to zero the lables of samples that should be ignored in the % evaluation. Set to -INF the scores of samples which are not % retrieved. If there are samples with -INF score, then the PR curve % may have maximum recall smaller than 1, unless the INCLUDEINF % option is used (see below). The options NUMNEGATIVES and % NUMPOSITIVES can be used to add additional surrogate samples with % -INF score (see below). % % [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional % structure INFO with the following fields: % % info.auc:: % The area under the precision-recall curve. If the INTERPOLATE % option is set to FALSE, then trapezoidal interpolation is used % to integrate the PR curve. If the INTERPOLATE option is set to % TRUE, then the curve is piecewise constant and no other % approximation is introduced in the calculation of the area. In % the latter case, INFO.AUC is the same as INFO.AP. % % info.ap:: % Average precision as defined by TREC. This is the average of the % precision observed each time a new positive sample is % recalled. In this calculation, any sample with -INF score % (unless INCLUDEINF is used) and any additional positive induced % by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE % option is set to true, the AP is computed from the interpolated % precision and the result is the same as INFO.AUC. Note that AP % as defined by TREC normally does not use interpolation [1]. % % info.ap_interp_11:: % 11-points interpolated average precision as defined by TREC. % This is the average of the maximum precision for recall levels % greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in % the PASCAL VOC challenge up to the 2008 edition. % % info.auc_pa08:: % Deprecated. It is the same of INFO.AP_INTERP_11. % % VL_PR(...) with no output arguments plots the PR curve in the % current axis. % % VL_PR() accepts the following options: % % Interpolate:: false % If set to true, use interpolated precision. The interpolated % precision is defined as the maximum precision for a given recall % level and onwards. Here it is implemented as the culumative % maximum from low to high scores of the precision. % % NumPositives:: [] % NumNegatives:: [] % If set to a number, pretend that LABELS contains this may % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entrires in % LABELS. The additional positive/negative labels are appended to % the end of the sequence, as if they had -INF scores (not % retrieved). This is useful to evaluate large retrieval systems % for which one stores ony a handful of top results for efficiency % reasons. % % IncludeInf:: false % If set to true, data with -INF score SCORES is included in the % evaluation and the maximum recall is 1 even if -INF scores are % present. This option does not include any additional positive or % negative data introduced by specifying NUMPOSITIVES and % NUMNEGATIVES. % % Stable:: false % If set to true, RECALL and PRECISION are returned in the same order % of LABELS and SCORES rather than being sorted by decreasing % score (increasing recall). Samples with -INF scores are assigned % RECALL and PRECISION equal to NaN. % % NormalizePrior:: [] % If set to a scalar, reweights positive and negative labels so % that the fraction of positive ones is equal to the specified % value. This computes the normalised PR curves of [2] % % About the PR curve:: % This section uses the same symbols used in the documentation of % the VL_ROC() function. In addition to those quantities, define: % % PRECISION(S) = TP(S) / (TP(S) + FP(S)) % RECALL(S) = TPR(S) = TP(S) / P % % The precision is the fraction of positivie predictions which are % correct, and the recall is the fraction of positive labels that % have been correctly classified (recalled). Notice that the recall % is also equal to the true positive rate for the ROC curve (see % VL_ROC()). % % REFERENCES: % [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to % Information Retrieval. Cambridge University Press, 2008. % [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in % object detectors. In Proc. ECCV, 2012. % % See also VL_ROC(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). % TP and FP are the vectors of true positie and false positve label % counts for decreasing scores, P and N are the total number of % positive and negative labels. Note that if certain options are used % some labels may actually not be stored explicitly by LABELS, so P+N % can be larger than the number of element of LABELS. [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.stable = false ; opts.interpolate = false ; opts.normalizePrior = [] ; opts = vl_argparse(opts,varargin) ; % compute precision and recall small = 1e-10 ; recall = tp / max(p, small) ; if isempty(opts.normalizePrior) precision = max(tp, small) ./ max(tp + fp, small) ; else a = opts.normalizePrior ; precision = max(tp * a/max(p,small), small) ./ ... max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ; end % interpolate precision if needed if opts.interpolate precision = fliplr(vl_cummax(fliplr(precision))) ; end % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || nargout == 0 % area under the curve using trapezoid interpolation if ~opts.interpolate info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ; end % average precision (for each recalled positive sample) sel = find(diff(recall)) + 1 ; info.ap = sum(precision(sel)) / p ; if opts.interpolate info.auc = info.ap ; end % TREC 11 points average interpolated precision info.ap_interp_11 = 0.0 ; for rc = linspace(0,1,11) pr = max([0, precision(recall >= rc)]) ; info.ap_interp_11 = info.ap_interp_11 + pr / 11 ; end % legacy definition info.auc_pa08 = info.ap_interp_11 ; end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if nargout == 0 cla ; hold on ; plot(recall,precision,'linewidth',2) ; if isempty(opts.normalizePrior) randomPrecision = p / (p + n) ; else randomPrecision = opts.normalizePrior ; end spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ; axis square ; grid on ; xlim([0 1]) ; xlabel('recall') ; ylim([0 1]) ; ylabel('precision') ; title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ... info.auc * 100, ... info.ap * 100, ... info.ap_interp_11 * 100)) ; if opts.interpolate legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ; else legend('PR', 'PR rand.', 'Location', 'SouthEast') ; end clear recall precision info ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable precision(1) = [] ; recall(1) = [] ; precision_ = precision ; recall_ = recall ; precision = NaN(size(precision)) ; recall = NaN(size(recall)) ; precision(perm) = precision_ ; recall(perm) = recall_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
cssjcai/hihca-master
vl_ubcread.m
.m
hihca-master/codes/vlfeat/toolbox/sift/vl_ubcread.m
3,015
utf_8
e8ddd3ecd87e76b6c738ba153fef050f
function [f,d] = vl_ubcread(file, varargin) % SIFTREAD Read Lowe's SIFT implementation data files % [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D % from FILE in UBC (Lowe's original implementation of SIFT) format % and returns F and D as defined by VL_SIFT(). % % VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by % Oxford VGG implementations . % % See also: VL_SIFT(), VL_HELP(). % Authors: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.verbosity = 0 ; opts.format = 'ubc' ; opts = vl_argparse(opts, varargin) ; g = fopen(file, 'r'); if g == -1 error(['Could not open file ''', file, '''.']) ; end [header, count] = fscanf(g, '%d', [1 2]) ; if count ~= 2 error('Invalid keypoint file header.'); end switch opts.format case 'ubc' numKeypoints = header(1) ; descrLen = header(2) ; case 'oxford' numKeypoints = header(2) ; descrLen = header(1) ; otherwise error('Unknown format ''%s''.', opts.format) ; end if(opts.verbosity > 0) fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ; end %creates two output matrices switch opts.format case 'ubc' P = zeros(4,numKeypoints) ; case 'oxford' P = zeros(5,numKeypoints) ; end L = zeros(descrLen, numKeypoints) ; %parse tmp.key for k = 1:numKeypoints switch opts.format case 'ubc' % Record format: i,j,s,th [record, count] = fscanf(g, '%f', [1 4]) ; if count ~= 4 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; case 'oxford' % Record format: x, y, a, b, c such that x' [a b ; b c] x = 1 [record, count] = fscanf(g, '%f', [1 5]) ; if count ~= 5 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; end % Record format: descriptor [record, count] = fscanf(g, '%d', [1 descrLen]) ; if count ~= descrLen error(... sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) ); end L(:,k) = record(:) ; end fclose(g) ; switch opts.format case 'ubc' P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ; d=uint8(L) ; p=[1 2 3 4 5 6 7 8] ; q=[1 8 7 6 5 4 3 2] ; for j=0:3 for i=0:3 d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ; end end case 'oxford' P(1:2,:) = P(1:2,:) + 1 ; % matlab origin f = P ; f(3:5,:) = inv2x2(f(3:5,:)) ; d = uint8(L) ; end % -------------------------------------------------------------------- function S = inv2x2(C) % -------------------------------------------------------------------- den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ; S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
github
cssjcai/hihca-master
vl_frame2oell.m
.m
hihca-master/codes/vlfeat/toolbox/sift/vl_frame2oell.m
2,806
utf_8
c93792632f630743485fa4c2cf12d647
function eframes = vl_frame2oell(frames) % VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse % EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an % oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with % one frame per column. % % A frame is either a point, a disc, an oriented disc, an ellipse, % or an oriented ellipse. These are represented respectively by 2, % 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An % oriented ellipse is the most general geometric frame; hence, there % is no loss of information in this conversion. % % If FRAME is an oriented disc or ellipse, then the conversion is % immediate. If, however, FRAME is not oriented (it is either a % point or an unoriented disc or ellipse), then an orientation must % be assigned. The orientation is chosen in such a way that the % affine transformation that maps the standard oriented frame into % the output EFRAME does not rotate the Y axis. If frames represent % detected visual features, this convention corresponds to assume % that features are upright. % % If FRAME is a point, then the output is an ellipse with null area. % % See: <a href="matlab:vl_help('tut.frame')">feature frames</a>, % VL_PLOTFRAME(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). [D,K] = size(frames) ; eframes = zeros(6,K) ; switch D case 2 eframes(1:2,:) = frames(1:2,:) ; case 3 eframes(1:2,:) = frames(1:2,:) ; eframes(3,:) = frames(3,:) ; eframes(6,:) = frames(3,:) ; case 4 r = frames(3,:) ; c = r.*cos(frames(4,:)) ; s = r.*sin(frames(4,:)) ; eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = [c ; s ; -s ; c] ; case 5 eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = mapFromS(frames(3:5,:)) ; case 6 eframes = frames ; otherwise error('FRAMES format is unknown.') ; end % -------------------------------------------------------------------- function A = mapFromS(S) % -------------------------------------------------------------------- % Returns the (stacking of the) 2x2 matrix A that maps the unit circle % into the ellipses satisfying the equation x' inv(S) x = 1. Here S % is a stacked covariance matrix, with elements S11, S12 and S22. % % The goal is to find A such that AA' = S. In order to let the Y % direction unaffected (upright feature), the assumption is taht % A = [a b ; 0 c]. Hence % % AA' = [a^2, ab ; ab, b^2+c^2] = S. A = zeros(4,size(S,2)) ; a = sqrt(S(1,:)); b = S(2,:) ./ max(a, 1e-18) ; A(1,:) = a ; A(2,:) = b ; A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
github
cssjcai/hihca-master
vl_plotsiftdescriptor.m
.m
hihca-master/codes/vlfeat/toolbox/sift/vl_plotsiftdescriptor.m
5,114
utf_8
a4e125a8916653f00143b61cceda2f23
function h=vl_plotsiftdescriptor(d,f,varargin) % VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor % VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a % matrix, it plots one descriptor per column. D has the same format % used by VL_SIFT(). % % VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to % the SIFT frames F, specified as columns of the matrix F. F has the % same format used by VL_SIFT(). % % H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line % drawing representing the descriptors. % % The function assumes that the SIFT descriptors use the standard % configuration of 4x4 spatial bins and 8 orientations bins. The % following parameters can be used to change this: % % NumSpatialBins:: 4 % Number of spatial bins in both spatial directions X and Y. % % NumOrientationBins:: 8 % Number of orientation bis. % % MagnificationFactor:: 3 % Magnification factor. The width of one bin is equal to the scale % of the keypoint F multiplied by this factor. % % See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.magnificationFactor = 3.0 ; opts.numSpatialBins = 4 ; opts.numOrientationBins = 8 ; opts.maxValue = 0 ; if nargin > 1 if ~ isnumeric(f) error('F must be a numeric type (use [] to leave it unspecified)') ; end end opts = vl_argparse(opts, varargin) ; % -------------------------------------------------------------------- % Check the arguments % -------------------------------------------------------------------- if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins) error('The number of rows of D does not match the geometry of the descriptor') ; end if nargin > 1 if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6)) error('F must be either empty of have from 2 to six rows.'); end if size(f,1) == 2 % translation only f(3:6,:) = deal([10 0 0 10]') ; %f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 3 % translation and scale f(3:6,:) = [1 0 0 1]' * f(3,:) ; %f = [f; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 4 c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if size(f,1) == 5 assert(false) ; c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if(~isempty(f) & size(f,2) ~= size(d,2)) error('D and F have incompatible dimension') ; end end % Descriptors are often non-double numeric arrays d = double(d) ; K = size(d,2) ; if nargin < 2 | isempty(f) f = repmat([0;0;1;0;0;1],1,K) ; end % -------------------------------------------------------------------- % Do the job % -------------------------------------------------------------------- xall=[] ; yall=[] ; for k=1:K [x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ; xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ; yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ; end h=line(xall,yall) ; % -------------------------------------------------------------------- function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue) % -------------------------------------------------------------------- % Get the coordinates of the lines of the SIFT grid; each bin has side 1 [x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ; % Get the corresponding bin centers xc = x(1:end-1,1:end-1) + 0.5 ; yc = y(1:end-1,1:end-1) + 0.5 ; % Rescale the descriptor range so that the biggest peak fits inside the bin diagram if maxValue d = 0.4 * d / maxValue ; else d = 0.4 * d / max(d(:)+eps) ; end % We scramble the the centers to have them in row major order % (descriptor convention). xc = xc' ; yc = yc' ; % Each spatial bin contains a star with numOrientationBins tips xc = repmat(xc(:)',numOrientationBins,1) ; yc = repmat(yc(:)',numOrientationBins,1) ; % Do the stars th=linspace(0,2*pi,numOrientationBins+1) ; th=th(1:end-1) ; xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ; yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ; xd = xd .* d(:)' ; yd = yd .* d(:)' ; % Re-arrange in sequential order the lines to draw nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ; x1 = xc(:)' ; y1 = yc(:)' ; x2 = x1 + xd ; y2 = y1 + yd ; xstars = [x1;x2;nans] ; ystars = [y1;y2;nans] ; % Horizontal lines of the grid nans = NaN * ones(1,numSpatialBins+1); xh = [x(:,1)' ; x(:,end)' ; nans] ; yh = [y(:,1)' ; y(:,end)' ; nans] ; % Verical lines of the grid xv = [x(1,:) ; x(end,:) ; nans] ; yv = [y(1,:) ; y(end,:) ; nans] ; x=[xstars(:)' xh(:)' xv(:)'] ; y=[ystars(:)' yh(:)' yv(:)'] ;
github
cssjcai/hihca-master
phow_caltech101.m
.m
hihca-master/codes/vlfeat/apps/phow_caltech101.m
11,594
utf_8
7f4890a2e6844ca56debbfe23cca64f3
function phow_caltech101() % PHOW_CALTECH101 Image classification in the Caltech-101 dataset % This program demonstrates how to use VLFeat to construct an image % classifier on the Caltech-101 data. The classifier uses PHOW % features (dense SIFT), spatial histograms of visual words, and a % Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT, % kd-trees, and homogeneous kernel map. The program also % demonstrates VLFeat PEGASOS SVM solver, although for this small % dataset other solvers such as LIBLINEAR can be more efficient. % % By default 15 training images are used, which should result in % about 64% performance (a good performance considering that only a % single feature type is being used). % % Call PHOW_CALTECH101 to train and test a classifier on a small % subset of the Caltech-101 data. Note that the program % automatically downloads a copy of the Caltech-101 data from the % Internet if it cannot find a local copy. % % Edit the PHOW_CALTECH101 file to change the program configuration. % % To run on the entire dataset change CONF.TINYPROBLEM to FALSE. % % The Caltech-101 data is saved into CONF.CALDIR, which defaults to % 'data/caltech-101'. Change this path to the desired location, for % instance to point to an existing copy of the Caltech-101 data. % % The program can also be used to train a model on custom data by % pointing CONF.CALDIR to it. Just create a subdirectory for each % class and put the training images there. Make sure to adjust % CONF.NUMTRAIN accordingly. % % Intermediate files are stored in the directory CONF.DATADIR. All % such files begin with the prefix CONF.PREFIX, which can be changed % to test different parameter settings without overriding previous % results. % % The program saves the trained model in % <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to % test novel images independently of the Caltech data. % % load('data/baseline-model.mat') ; # change to the model path % label = model.classify(model, im) ; % % Author: Andrea Vedaldi % Copyright (C) 2011-2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). conf.calDir = 'data/caltech-101' ; conf.dataDir = 'data/' ; conf.autoDownloadData = true ; conf.numTrain = 15 ; conf.numTest = 15 ; conf.numClasses = 102 ; conf.numWords = 600 ; conf.numSpatialX = [2 4] ; conf.numSpatialY = [2 4] ; conf.quantizer = 'kdtree' ; conf.svm.C = 10 ; conf.svm.solver = 'sdca' ; %conf.svm.solver = 'sgd' ; %conf.svm.solver = 'liblinear' ; conf.svm.biasMultiplier = 1 ; conf.phowOpts = {'Step', 3} ; conf.clobber = false ; conf.tinyProblem = true ; conf.prefix = 'baseline' ; conf.randSeed = 1 ; if conf.tinyProblem conf.prefix = 'tiny' ; conf.numClasses = 5 ; conf.numSpatialX = 2 ; conf.numSpatialY = 2 ; conf.numWords = 300 ; conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ; end conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ; conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ; conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ; conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ; randn('state',conf.randSeed) ; rand('state',conf.randSeed) ; vl_twister('state',conf.randSeed) ; % -------------------------------------------------------------------- % Download Caltech-101 data % -------------------------------------------------------------------- if ~exist(conf.calDir, 'dir') || ... (~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ... ~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes'))) if ~conf.autoDownloadData error(... ['Caltech-101 data not found. ' ... 'Set conf.autoDownloadData=true to download the required data.']) ; end vl_xmkdir(conf.calDir) ; calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ... 'Caltech101/101_ObjectCategories.tar.gz'] ; fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ; untar(calUrl, conf.calDir) ; end if ~exist(fullfile(conf.calDir, 'airplanes'),'dir') conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ; end % -------------------------------------------------------------------- % Setup data % -------------------------------------------------------------------- classes = dir(conf.calDir) ; classes = classes([classes.isdir]) ; classes = {classes(3:conf.numClasses+2).name} ; images = {} ; imageClass = {} ; for ci = 1:length(classes) ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ; ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ; ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ; images = {images{:}, ims{:}} ; imageClass{end+1} = ci * ones(1,length(ims)) ; end selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ; selTest = setdiff(1:length(images), selTrain) ; imageClass = cat(2, imageClass{:}) ; model.classes = classes ; model.phowOpts = conf.phowOpts ; model.numSpatialX = conf.numSpatialX ; model.numSpatialY = conf.numSpatialY ; model.quantizer = conf.quantizer ; model.vocab = [] ; model.w = [] ; model.b = [] ; model.classify = @classify ; % -------------------------------------------------------------------- % Train vocabulary % -------------------------------------------------------------------- if ~exist(conf.vocabPath) || conf.clobber % Get some PHOW descriptors to train the dictionary selTrainFeats = vl_colsubset(selTrain, 30) ; descrs = {} ; %for ii = 1:length(selTrainFeats) parfor ii = 1:length(selTrainFeats) im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ; im = standarizeImage(im) ; [drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ; end descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ; descrs = single(descrs) ; % Quantize the descriptors to get the visual words vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ; save(conf.vocabPath, 'vocab') ; else load(conf.vocabPath) ; end model.vocab = vocab ; if strcmp(model.quantizer, 'kdtree') model.kdtree = vl_kdtreebuild(vocab) ; end % -------------------------------------------------------------------- % Compute spatial histograms % -------------------------------------------------------------------- if ~exist(conf.histPath) || conf.clobber hists = {} ; parfor ii = 1:length(images) % for ii = 1:length(images) fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ; im = imread(fullfile(conf.calDir, images{ii})) ; hists{ii} = getImageDescriptor(model, im); end hists = cat(2, hists{:}) ; save(conf.histPath, 'hists') ; else load(conf.histPath) ; end % -------------------------------------------------------------------- % Compute feature map % -------------------------------------------------------------------- psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ; % -------------------------------------------------------------------- % Train SVM % -------------------------------------------------------------------- if ~exist(conf.modelPath) || conf.clobber switch conf.svm.solver case {'sgd', 'sdca'} lambda = 1 / (conf.svm.C * length(selTrain)) ; w = [] ; parfor ci = 1:length(classes) perm = randperm(length(selTrain)) ; fprintf('Training model for class %s\n', classes{ci}) ; y = 2 * (imageClass(selTrain) == ci) - 1 ; [w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ... 'Solver', conf.svm.solver, ... 'MaxNumIterations', 50/lambda, ... 'BiasMultiplier', conf.svm.biasMultiplier, ... 'Epsilon', 1e-3); end case 'liblinear' svm = train(imageClass(selTrain)', ... sparse(double(psix(:,selTrain))), ... sprintf(' -s 3 -B %f -c %f', ... conf.svm.biasMultiplier, conf.svm.C), ... 'col') ; w = svm.w(:,1:end-1)' ; b = svm.w(:,end)' ; end model.b = conf.svm.biasMultiplier * b ; model.w = w ; save(conf.modelPath, 'model') ; else load(conf.modelPath) ; end % -------------------------------------------------------------------- % Test SVM and evaluate % -------------------------------------------------------------------- % Estimate the class of the test images scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ; [drop, imageEstClass] = max(scores, [], 1) ; % Compute the confusion matrix idx = sub2ind([length(classes), length(classes)], ... imageClass(selTest), imageEstClass(selTest)) ; confus = zeros(length(classes)) ; confus = vl_binsum(confus, ones(size(idx)), idx) ; % Plots figure(1) ; clf; subplot(1,2,1) ; imagesc(scores(:,[selTrain selTest])) ; title('Scores') ; set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ; subplot(1,2,2) ; imagesc(confus) ; title(sprintf('Confusion matrix (%.2f %% accuracy)', ... 100 * mean(diag(confus)/conf.numTest) )) ; print('-depsc2', [conf.resultPath '.ps']) ; save([conf.resultPath '.mat'], 'confus', 'conf') ; % ------------------------------------------------------------------------- function im = standarizeImage(im) % ------------------------------------------------------------------------- im = im2single(im) ; if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end % ------------------------------------------------------------------------- function hist = getImageDescriptor(model, im) % ------------------------------------------------------------------------- im = standarizeImage(im) ; width = size(im,2) ; height = size(im,1) ; numWords = size(model.vocab, 2) ; % get PHOW features [frames, descrs] = vl_phow(im, model.phowOpts{:}) ; % quantize local descriptors into visual words switch model.quantizer case 'vq' [drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ; case 'kdtree' binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ... single(descrs), ... 'MaxComparisons', 50)) ; end for i = 1:length(model.numSpatialX) binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ; binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ; % combined quantization bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ... binsy,binsx,binsa) ; hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ; hist = vl_binsum(hist, ones(size(bins)), bins) ; hists{i} = single(hist / sum(hist)) ; end hist = cat(1,hists{:}) ; hist = hist / sum(hist) ; % ------------------------------------------------------------------------- function [className, score] = classify(model, im) % ------------------------------------------------------------------------- hist = getImageDescriptor(model, im) ; psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ; scores = model.w' * psix + model.b' ; [score, best] = max(scores) ; className = model.classes{best} ;
github
cssjcai/hihca-master
sift_mosaic.m
.m
hihca-master/codes/vlfeat/apps/sift_mosaic.m
4,621
utf_8
8fa3ad91b401b8f2400fb65944c79712
function mosaic = sift_mosaic(im1, im2) % SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC % % SIFT_MOSAIC demonstrates matching two images based on SIFT % features and RANSAC and computing their mosaic. % % SIFT_MOSAIC by itself runs the algorithm on two standard test % images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two % custom images IM1 and IM2. % AUTORIGHTS if nargin == 0 im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ; end % make single im1 = im2single(im1) ; im2 = im2single(im2) ; % make grayscale if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end % -------------------------------------------------------------------- % SIFT matches % -------------------------------------------------------------------- [f1,d1] = vl_sift(im1g) ; [f2,d2] = vl_sift(im2g) ; [matches, scores] = vl_ubcmatch(d1,d2) ; numMatches = size(matches,2) ; X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ; X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ; % -------------------------------------------------------------------- % RANSAC with homography model % -------------------------------------------------------------------- clear H score ok ; for t = 1:100 % estimate homograpyh subset = vl_colsubset(1:numMatches, 4) ; A = [] ; for i = subset A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ; end [U,S,V] = svd(A) ; H{t} = reshape(V(:,9),3,3) ; % score homography X2_ = H{t} * X1 ; du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ; dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ; ok{t} = (du.*du + dv.*dv) < 6*6 ; score(t) = sum(ok{t}) ; end [score, best] = max(score) ; H = H{best} ; ok = ok{best} ; % -------------------------------------------------------------------- % Optional refinement % -------------------------------------------------------------------- function err = residual(H) u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ; v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ; d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ; du = X2(1,ok) - u ./ d ; dv = X2(2,ok) - v ./ d ; err = sum(du.*du + dv.*dv) ; end if exist('fminsearch') == 2 H = H / H(3,3) ; opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ; H(1:8) = fminsearch(@residual, H(1:8)', opts) ; else warning('Refinement disabled as fminsearch was not found.') ; end % -------------------------------------------------------------------- % Show matches % -------------------------------------------------------------------- dh1 = max(size(im2,1)-size(im1,1),0) ; dh2 = max(size(im1,1)-size(im2,1),0) ; figure(1) ; clf ; subplot(2,1,1) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ... [f1(2,matches(1,:));f2(2,matches(2,:))]) ; title(sprintf('%d tentative matches', numMatches)) ; axis image off ; subplot(2,1,2) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ... [f1(2,matches(1,ok));f2(2,matches(2,ok))]) ; title(sprintf('%d (%.2f%%) inliner matches out of %d', ... sum(ok), ... 100*sum(ok)/numMatches, ... numMatches)) ; axis image off ; drawnow ; % -------------------------------------------------------------------- % Mosaic % -------------------------------------------------------------------- box2 = [1 size(im2,2) size(im2,2) 1 ; 1 1 size(im2,1) size(im2,1) ; 1 1 1 1 ] ; box2_ = inv(H) * box2 ; box2_(1,:) = box2_(1,:) ./ box2_(3,:) ; box2_(2,:) = box2_(2,:) ./ box2_(3,:) ; ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ; vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ; [u,v] = meshgrid(ur,vr) ; im1_ = vl_imwbackward(im2double(im1),u,v) ; z_ = H(3,1) * u + H(3,2) * v + H(3,3) ; u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ; v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ; im2_ = vl_imwbackward(im2double(im2),u_,v_) ; mass = ~isnan(im1_) + ~isnan(im2_) ; im1_(isnan(im1_)) = 0 ; im2_(isnan(im2_)) = 0 ; mosaic = (im1_ + im2_) ./ mass ; figure(2) ; clf ; imagesc(mosaic) ; axis image off ; title('Mosaic') ; if nargout == 0, clear mosaic ; end end
github
cssjcai/hihca-master
encodeImage.m
.m
hihca-master/codes/vlfeat/apps/recognition/encodeImage.m
5,278
utf_8
5d9dc6161995b8e10366b5649bf4fda4
function descrs = encodeImage(encoder, im, varargin) % ENCODEIMAGE Apply an encoder to an image % DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER % to image IM, returning a corresponding code vector PSI. % % IM can be an image, the path to an image, or a cell array of % the same, to operate on multiple images. % % ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE % directory to store encodings for the given images. The cache % is used only if the images are specified as file names. % % See also: TRAINENCODER(). % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.cacheDir = [] ; opts.cacheChunkSize = 512 ; opts = vl_argparse(opts,varargin) ; if ~iscell(im), im = {im} ; end % break the computation into cached chunks startTime = tic ; descrs = cell(1, numel(im)) ; numChunks = ceil(numel(im) / opts.cacheChunkSize) ; for c = 1:numChunks n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ; chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ; if ~isempty(opts.cacheDir) && exist(chunkPath) fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ; load(chunkPath, 'data') ; else range = (c-1)*opts.cacheChunkSize + (1:n) ; fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ... mfilename, numel(range), ... c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ; data = processChunk(encoder, im(range)) ; if ~isempty(opts.cacheDir) save(chunkPath, 'data') ; end end descrs{c} = data ; clear data ; end descrs = cat(2,descrs{:}) ; % -------------------------------------------------------------------- function psi = processChunk(encoder, im) % -------------------------------------------------------------------- psi = cell(1,numel(im)) ; if numel(im) > 1 & matlabpool('size') > 1 parfor i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end else % avoiding parfor makes debugging easier for i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end end psi = cat(2, psi{:}) ; % -------------------------------------------------------------------- function psi = encodeOne(encoder, im) % -------------------------------------------------------------------- im = encoder.readImageFn(im) ; features = encoder.extractorFn(im) ; imageSize = size(im) ; psi = {} ; for i = 1:size(encoder.subdivisions,2) minx = encoder.subdivisions(1,i) * imageSize(2) ; miny = encoder.subdivisions(2,i) * imageSize(1) ; maxx = encoder.subdivisions(3,i) * imageSize(2) ; maxy = encoder.subdivisions(4,i) * imageSize(1) ; ok = ... minx <= features.frame(1,:) & features.frame(1,:) < maxx & ... miny <= features.frame(2,:) & features.frame(2,:) < maxy ; descrs = encoder.projection * bsxfun(@minus, ... features.descr(:,ok), ... encoder.projectionCenter) ; if encoder.renormalize descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ; end w = size(im,2) ; h = size(im,1) ; frames = features.frame(1:2,:) ; frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ; descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ; switch encoder.type case 'bovw' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 100) ; z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ; z = sqrt(z) ; case 'fv' z = vl_fisher(descrs, ... encoder.means, ... encoder.covariances, ... encoder.priors, ... 'Improved') ; case 'vlad' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 15) ; assign = zeros(encoder.numWords, numel(words), 'single') ; assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ; z = vl_vlad(descrs, ... encoder.words, ... assign, ... 'SquareRoot', ... 'NormalizeComponents') ; end z = z / max(sqrt(sum(z.^2)), 1e-12) ; psi{i} = z(:) ; end psi = cat(1, psi{:}) ; % -------------------------------------------------------------------- function psi = getFromCache(name, cache) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; if exist(cachePath, 'file') data = load(cachePath) ; psi = data.psi ; else psi = [] ; end % -------------------------------------------------------------------- function storeToCache(name, cache, psi) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; vl_xmkdir(cache) ; data.psi = psi ; save(cachePath, '-STRUCT', 'data') ;
github
cssjcai/hihca-master
experiments.m
.m
hihca-master/codes/vlfeat/apps/recognition/experiments.m
6,905
utf_8
1e4a4911eed4a451b9488b9e6cc9b39c
function experiments() % EXPERIMENTS Run image classification experiments % The experimens download a number of benchmark datasets in the % 'data/' subfolder. Make sure that there are several GBs of % space available. % % By default, experiments run with a lite option turned on. This % quickly runs all of them on tiny subsets of the actual data. % This is used only for testing; to run the actual experiments, % set the lite variable to false. % % Running all the experiments is a slow process. Using parallel % MATLAB and several cores/machiens is suggested. % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). lite = true ; clear ex ; ex(1).prefix = 'fv-aug' ; ex(1).trainOpts = {'C', 10} ; ex(1).datasets = {'fmd', 'scene67'} ; ex(1).seed = 1 ; ex(1).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(2) = ex(1) ; ex(2).datasets = {'caltech101'} ; ex(2).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(3) = ex(1) ; ex(3).datasets = {'voc07'} ; ex(3).C = 1 ; ex(4) = ex(1) ; ex(4).prefix = 'vlad-aug' ; ex(4).opts = {... 'type', 'vlad', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(5) = ex(4) ; ex(5).datasets = {'caltech101'} ; ex(5).opts{end} = ex(2).opts{end} ; ex(6) = ex(4) ; ex(6).datasets = {'voc07'} ; ex(6).C = 1 ; ex(7) = ex(1) ; ex(7).prefix = 'bovw-aug' ; ex(7).opts = {... 'type', 'bovw', ... 'numWords', 4096, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(8) = ex(7) ; ex(8).datasets = {'caltech101'} ; ex(8).opts{end} = ex(2).opts{end} ; ex(9) = ex(7) ; ex(9).datasets = {'voc07'} ; ex(9).C = 1 ; ex(10).prefix = 'fv' ; ex(10).trainOpts = {'C', 10} ; ex(10).datasets = {'fmd', 'scene67'} ; ex(10).seed = 1 ; ex(10).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(11) = ex(10) ; ex(11).datasets = {'caltech101'} ; ex(11).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(12) = ex(10) ; ex(12).datasets = {'voc07'} ; ex(12).C = 1 ; ex(13).prefix = 'fv-sp' ; ex(13).trainOpts = {'C', 10} ; ex(13).datasets = {'fmd', 'scene67'} ; ex(13).seed = 1 ; ex(13).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1', '3x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(14) = ex(13) ; ex(14).datasets = {'caltech101'} ; ex(14).opts{6} = {'1x1', '2x2'} ; ex(14).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(15) = ex(13) ; ex(15).datasets = {'voc07'} ; ex(15).C = 1 ; if lite, tag = 'lite' ; else, tag = 'ex' ; end for i=1:numel(ex) for j=1:numel(ex(i).datasets) dataset = ex(i).datasets{j} ; if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts) ex(i).trainOpts = {} ; end traintest(... 'prefix', [tag '-' dataset '-' ex(i).prefix], ... 'seed', ex(i).seed, ... 'dataset', char(dataset), ... 'datasetDir', fullfile('data', dataset), ... 'lite', lite, ... ex(i).trainOpts{:}, ... 'encoderParams', ex(i).opts) ; end end % print HTML table pf('<table>\n') ; ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ; pr('FV', ... ge([tag '-voc07-fv'],'ap11'), ... ge([tag '-caltech101-fv']), ... ge([tag '-scene67-fv']), ... ge([tag '-fmd-fv'])) ; pr('FV + aug.', ... ge([tag '-voc07-fv-aug'],'ap11'), ... ge([tag '-caltech101-fv-aug']), ... ge([tag '-scene67-fv-aug']), ... ge([tag '-fmd-fv-aug'])) ; pr('FV + s.p.', ... ge([tag '-voc07-fv-sp'],'ap11'), ... ge([tag '-caltech101-fv-sp']), ... ge([tag '-scene67-fv-sp']), ... ge([tag '-fmd-fv-sp'])) ; %pr('VLAD', ... % ge([tag '-voc07-vlad'],'ap11'), ... % ge([tag '-caltech101-vlad']), ... % ge([tag '-scene67-vlad']), ... % ge([tag '-fmd-vlad'])) ; pr('VLAD + aug.', ... ge([tag '-voc07-vlad-aug'],'ap11'), ... ge([tag '-caltech101-vlad-aug']), ... ge([tag '-scene67-vlad-aug']), ... ge([tag '-fmd-vlad-aug'])) ; %pr('VLAD+sp', ... % ge([tag '-voc07-vlad-sp'],'ap11'), ... % ge([tag '-caltech101-vlad-sp']), ... % ge([tag '-scene67-vlad-sp']), ... % ge([tag '-fmd-vlad-sp'])) ; %pr('BOVW', ... % ge([tag '-voc07-bovw'],'ap11'), ... % ge([tag '-caltech101-bovw']), ... % ge([tag '-scene67-bovw']), ... % ge([tag '-fmd-bovw'])) ; pr('BOVW + aug.', ... ge([tag '-voc07-bovw-aug'],'ap11'), ... ge([tag '-caltech101-bovw-aug']), ... ge([tag '-scene67-bovw-aug']), ... ge([tag '-fmd-bovw-aug'])) ; %pr('BOVW+sp', ... % ge([tag '-voc07-bovw-sp'],'ap11'), ... % ge([tag '-caltech101-bovw-sp']), ... % ge([tag '-scene67-bovw-sp']), ... % ge([tag '-fmd-bovw-sp'])) ; pf('</table>\n'); function pf(str) fprintf(str) ; function str = ge(name, format) if nargin == 1, format = 'acc'; end data = load(fullfile('data', name, 'result.mat')) ; switch format case 'acc' str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ; case 'ap11' str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ; end function pr(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end fprintf('</tr>\n') ; function ph(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end fprintf('</tr>\n') ;
github
cssjcai/hihca-master
getDenseSIFT.m
.m
hihca-master/codes/vlfeat/apps/recognition/getDenseSIFT.m
1,679
utf_8
2059c0a2a4e762226d89121408c6e51c
function features = getDenseSIFT(im, varargin) % GETDENSESIFT Extract dense SIFT features % FEATURES = GETDENSESIFT(IM) extract dense SIFT features from % image IM. % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.scales = logspace(log10(1), log10(.25), 5) ; opts.contrastthreshold = 0 ; opts.step = 3 ; opts.rootSift = false ; opts.normalizeSift = true ; opts.binSize = 8 ; opts.geometry = [4 4 8] ; opts.sigma = 0 ; opts = vl_argparse(opts, varargin) ; dsiftOpts = {'norm', 'fast', 'floatdescriptors', ... 'step', opts.step, ... 'size', opts.binSize, ... 'geometry', opts.geometry} ; if size(im,3)>1, im = rgb2gray(im) ; end im = im2single(im) ; im = vl_imsmooth(im, opts.sigma) ; for si = 1:numel(opts.scales) im_ = imresize(im, opts.scales(si)) ; [frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ; % root SIFT if opts.rootSift descrs{si} = sqrt(descrs{si}) ; end if opts.normalizeSift descrs{si} = snorm(descrs{si}) ; end % zero low contrast descriptors info.contrast{si} = frames{si}(3,:) ; kill = info.contrast{si} < opts.contrastthreshold ; descrs{si}(:,kill) = 0 ; % store frames frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ; frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ; end features.frame = cat(2, frames{:}) ; features.descr = cat(2, descrs{:}) ; features.contrast = cat(2, info.contrast{:}) ; function x = snorm(x) x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
github
cssjcai/hihca-master
test_examples.m
.m
hihca-master/codes/matconvnet/utils/test_examples.m
1,591
utf_8
16831be7382a9343beff5cc3fe301e51
function test_examples() %TEST_EXAMPLES Test some of the examples in the `examples/` directory addpath examples/mnist ; addpath examples/cifar ; trainOpts.gpus = [] ; trainOpts.continue = true ; num = 1 ; exps = {} ; for networkType = {'dagnn', 'simplenn'} for index = 1:4 clear ex ; ex.trainOpts = trainOpts ; ex.networkType = char(networkType) ; ex.index = index ; exps{end+1} = ex ; end end if num > 1 if isempty(gcp('nocreate')), parpool('local',num) ; end parfor e = 1:numel(exps) test_one(exps{e}) ; end else for e = 1:numel(exps) test_one(exps{e}) ; end end % ------------------------------------------------------------------------ function test_one(ex) % ------------------------------------------------------------------------- suffix = ['-' ex.networkType] ; switch ex.index case 1 cnn_mnist(... 'expDir', ['data/test-mnist' suffix], ... 'batchNormalization', false, ... 'networkType', ex.networkType, ... 'train', ex.trainOpts) ; case 2 cnn_mnist(... 'expDir', ['data/test-mnist-bnorm' suffix], ... 'batchNormalization', true, ... 'networkType', ex.networkType, ... 'train', ex.trainOpts) ; case 3 cnn_cifar(... 'expDir', ['data/test-cifar-lenet' suffix], ... 'modelType', 'lenet', ... 'networkType', ex.networkType, ... 'train', ex.trainOpts) ; case 4 cnn_cifar(... 'expDir', ['data/test-cifar-nin' suffix], ... 'modelType', 'nin', ... 'networkType', ex.networkType, ... 'train', ex.trainOpts) ; end
github
cssjcai/hihca-master
cnn_train_dag.m
.m
hihca-master/codes/matconvnet/examples/cnn_train_dag.m
13,468
utf_8
a9acd7cb82e9dfd3e29bb5c94bee9fe7
function [net,stats] = cnn_train_dag(net, imdb, getBatch, varargin) %CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper % CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with % the DagNN wrapper instead of the SimpleNN wrapper. % Copyright (C) 2014-16 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.expDir = fullfile('data','exp') ; opts.continue = true ; opts.batchSize = 256 ; opts.numSubBatches = 1 ; opts.train = [] ; opts.val = [] ; opts.gpus = [] ; opts.prefetch = false ; opts.numEpochs = 300 ; opts.learningRate = 0.001 ; opts.weightDecay = 0.0005 ; opts.momentum = 0.9 ; opts.randomSeed = 0 ; opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ; opts.profile = false ; opts.derOutputs = {'objective', 1} ; opts.extractStatsFn = @extractStats ; opts.plotStatistics = true; opts = vl_argparse(opts, varargin) ; if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end if isnan(opts.train), opts.train = [] ; end % ------------------------------------------------------------------------- % Initialization % ------------------------------------------------------------------------- evaluateMode = isempty(opts.train) ; if ~evaluateMode if isempty(opts.derOutputs) error('DEROUTPUTS must be specified when training.\n') ; end end state.getBatch = getBatch ; stats = [] ; % ------------------------------------------------------------------------- % Train and validate % ------------------------------------------------------------------------- modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep)); modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ; start = opts.continue * findLastCheckpoint(opts.expDir) ; if start >= 1 fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ; [net, stats] = loadState(modelPath(start)) ; end for epoch=start+1:opts.numEpochs % Set the random seed based on the epoch and opts.randomSeed. % This is important for reproducibility, including when training % is restarted from a checkpoint. rng(epoch + opts.randomSeed) ; prepareGPUs(opts, epoch == start+1) ; % Train for one epoch. state.epoch = epoch ; state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ; state.train = opts.train(randperm(numel(opts.train))) ; % shuffle state.val = opts.val(randperm(numel(opts.val))) ; state.imdb = imdb ; if numel(opts.gpus) <= 1 [stats.train(epoch),prof] = process_epoch(net, state, opts, 'train') ; stats.val(epoch) = process_epoch(net, state, opts, 'val') ; if opts.profile profview(0,prof) ; keyboard ; end else savedNet = net.saveobj() ; spmd net_ = dagnn.DagNN.loadobj(savedNet) ; [stats_.train, prof_] = process_epoch(net_, state, opts, 'train') ; stats_.val = process_epoch(net_, state, opts, 'val') ; if labindex == 1, savedNet_ = net_.saveobj() ; end end net = dagnn.DagNN.loadobj(savedNet_{1}) ; stats__ = accumulateStats(stats_) ; stats.train(epoch) = stats__.train ; stats.val(epoch) = stats__.val ; if opts.profile mpiprofile('viewer', [prof_{:,1}]) ; keyboard ; end clear net_ stats_ stats__ savedNet savedNet_ ; end % save if ~evaluateMode saveState(modelPath(epoch), net, stats) ; end if opts.plotStatistics switchFigure(1) ; clf ; plots = setdiff(... cat(2,... fieldnames(stats.train)', ... fieldnames(stats.val)'), {'num', 'time'}) ; for p = plots p = char(p) ; values = zeros(0, epoch) ; leg = {} ; for f = {'train', 'val'} f = char(f) ; if isfield(stats.(f), p) tmp = [stats.(f).(p)] ; values(end+1,:) = tmp(1,:)' ; leg{end+1} = f ; end end subplot(1,numel(plots),find(strcmp(p,plots))) ; plot(1:epoch, values','o-') ; xlabel('epoch') ; title(p) ; legend(leg{:}) ; grid on ; end drawnow ; print(1, modelFigPath, '-dpdf') ; end end % ------------------------------------------------------------------------- function [stats, prof] = process_epoch(net, state, opts, mode) % ------------------------------------------------------------------------- % initialize empty momentum if strcmp(mode,'train') state.momentum = num2cell(zeros(1, numel(net.params))) ; end % move CNN to GPU as needed numGpus = numel(opts.gpus) ; if numGpus >= 1 net.move('gpu') ; if strcmp(mode,'train') state.momentum = cellfun(@gpuArray,state.momentum,'UniformOutput',false) ; end end if numGpus > 1 mmap = map_gradients(opts.memoryMapFile, net, numGpus) ; else mmap = [] ; end % profile if opts.profile if numGpus <= 1 profile clear ; profile on ; else mpiprofile reset ; mpiprofile on ; end end subset = state.(mode) ; num = 0 ; stats.num = 0 ; % return something even if subset = [] stats.time = 0 ; adjustTime = 0 ; start = tic ; for t=1:opts.batchSize:numel(subset) fprintf('%s: epoch %02d: %3d/%3d:', mode, state.epoch, ... fix((t-1)/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ; batchSize = min(opts.batchSize, numel(subset) - t + 1) ; for s=1:opts.numSubBatches % get this image batch and prefetch the next batchStart = t + (labindex-1) + (s-1) * numlabs ; batchEnd = min(t+opts.batchSize-1, numel(subset)) ; batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ; num = num + numel(batch) ; if numel(batch) == 0, continue ; end inputs = state.getBatch(state.imdb, batch) ; if opts.prefetch if s == opts.numSubBatches batchStart = t + (labindex-1) + opts.batchSize ; batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ; else batchStart = batchStart + numlabs ; end nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ; state.getBatch(state.imdb, nextBatch) ; end if strcmp(mode, 'train') net.mode = 'normal' ; net.accumulateParamDers = (s ~= 1) ; net.eval(inputs, opts.derOutputs) ; else net.mode = 'test' ; net.eval(inputs) ; end end % accumulate gradient if strcmp(mode, 'train') if ~isempty(mmap) write_gradients(mmap, net) ; labBarrier() ; end state = accumulate_gradients(state, net, opts, batchSize, mmap) ; end % get statistics time = toc(start) + adjustTime ; batchTime = time - stats.time ; stats = opts.extractStatsFn(net) ; stats.num = num ; stats.time = time ; currentSpeed = batchSize / batchTime ; averageSpeed = (t + batchSize - 1) / time ; if t == opts.batchSize + 1 % compensate for the first iteration, which is an outlier adjustTime = 2*batchTime - time ; stats.time = time + adjustTime ; end fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ; for f = setdiff(fieldnames(stats)', {'num', 'time'}) f = char(f) ; fprintf(' %s:', f) ; fprintf(' %.3f', stats.(f)) ; end fprintf('\n') ; end if ~isempty(mmap) unmap_gradients(mmap) ; end if opts.profile if numGpus <= 1 prof = profile('info') ; profile off ; else prof = mpiprofile('info'); mpiprofile off ; end else prof = [] ; end net.reset() ; net.move('cpu') ; % ------------------------------------------------------------------------- function state = accumulate_gradients(state, net, opts, batchSize, mmap) % ------------------------------------------------------------------------- numGpus = numel(opts.gpus) ; otherGpus = setdiff(1:numGpus, labindex) ; for p=1:numel(net.params) % accumualte gradients from multiple labs (GPUs) if needed if numGpus > 1 tag = net.params(p).name ; for g = otherGpus tmp = gpuArray(mmap.Data(g).(tag)) ; net.params(p).der = net.params(p).der + tmp ; end end switch net.params(p).trainMethod case 'average' % mainly for batch normalization thisLR = net.params(p).learningRate ; net.params(p).value = ... (1 - thisLR) * net.params(p).value + ... (thisLR/batchSize/net.params(p).fanout) * net.params(p).der ; case 'gradient' thisDecay = opts.weightDecay * net.params(p).weightDecay ; thisLR = state.learningRate * net.params(p).learningRate ; state.momentum{p} = opts.momentum * state.momentum{p} ... - thisDecay * net.params(p).value ... - (1 / batchSize) * net.params(p).der ; net.params(p).value = net.params(p).value + thisLR * state.momentum{p} ; case 'otherwise' error('Unknown training method ''%s'' for parameter ''%s''.', ... net.params(p).trainMethod, ... net.params(p).name) ; end end % ------------------------------------------------------------------------- function mmap = map_gradients(fname, net, numGpus) % ------------------------------------------------------------------------- format = {} ; for i=1:numel(net.params) format(end+1,1:3) = {'single', size(net.params(i).value), net.params(i).name} ; end format(end+1,1:3) = {'double', [3 1], 'errors'} ; if ~exist(fname) && (labindex == 1) f = fopen(fname,'wb') ; for g=1:numGpus for i=1:size(format,1) fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ; end end fclose(f) ; end labBarrier() ; mmap = memmapfile(fname, ... 'Format', format, ... 'Repeat', numGpus, ... 'Writable', true) ; % ------------------------------------------------------------------------- function write_gradients(mmap, net) % ------------------------------------------------------------------------- for i=1:numel(net.params) mmap.Data(labindex).(net.params(i).name) = gather(net.params(i).der) ; end % ------------------------------------------------------------------------- function unmap_gradients(mmap) % ------------------------------------------------------------------------- % ------------------------------------------------------------------------- function stats = accumulateStats(stats_) % ------------------------------------------------------------------------- for s = {'train', 'val'} s = char(s) ; total = 0 ; % initialize stats stucture with same fields and same order as % stats_{1} stats__ = stats_{1} ; names = fieldnames(stats__.(s))' ; values = zeros(1, numel(names)) ; fields = cat(1, names, num2cell(values)) ; stats.(s) = struct(fields{:}) ; for g = 1:numel(stats_) stats__ = stats_{g} ; num__ = stats__.(s).num ; total = total + num__ ; for f = setdiff(fieldnames(stats__.(s))', 'num') f = char(f) ; stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ; if g == numel(stats_) stats.(s).(f) = stats.(s).(f) / total ; end end end stats.(s).num = total ; end % ------------------------------------------------------------------------- function stats = extractStats(net) % ------------------------------------------------------------------------- sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ; stats = struct() ; for i = 1:numel(sel) stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ; end % ------------------------------------------------------------------------- function saveState(fileName, net, stats) % ------------------------------------------------------------------------- net_ = net ; net = net_.saveobj() ; save(fileName, 'net', 'stats') ; % ------------------------------------------------------------------------- function [net, stats] = loadState(fileName) % ------------------------------------------------------------------------- load(fileName, 'net', 'stats') ; net = dagnn.DagNN.loadobj(net) ; % ------------------------------------------------------------------------- function epoch = findLastCheckpoint(modelDir) % ------------------------------------------------------------------------- list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ; tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ; epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ; epoch = max([epoch 0]) ; % ------------------------------------------------------------------------- function switchFigure(n) % ------------------------------------------------------------------------- if get(0,'CurrentFigure') ~= n try set(0,'CurrentFigure',n) ; catch figure(n) ; end end % ------------------------------------------------------------------------- function prepareGPUs(opts, cold) % ------------------------------------------------------------------------- numGpus = numel(opts.gpus) ; if numGpus > 1 % check parallel pool integrity as it could have timed out pool = gcp('nocreate') ; if ~isempty(pool) && pool.NumWorkers ~= numGpus delete(pool) ; end pool = gcp('nocreate') ; if isempty(pool) parpool('local', numGpus) ; cold = true ; end if exist(opts.memoryMapFile) delete(opts.memoryMapFile) ; end end if numGpus >= 1 && cold fprintf('%s: resetting GPU\n', mfilename) if numGpus == 1 gpuDevice(opts.gpus) else spmd, gpuDevice(opts.gpus(labindex)), end end end %end
github
cssjcai/hihca-master
cnn_train.m
.m
hihca-master/codes/matconvnet/examples/cnn_train.m
18,017
utf_8
a48457fdbed83db01574fdc9373e6283
function [net, stats] = cnn_train(net, imdb, getBatch, varargin) %CNN_TRAIN An example implementation of SGD for training CNNs % CNN_TRAIN() is an example learner implementing stochastic % gradient descent with momentum to train a CNN. It can be used % with different datasets and tasks by providing a suitable % getBatch function. % % The function automatically restarts after each training epoch by % checkpointing. % % The function supports training on CPU or on one or more GPUs % (specify the list of GPU IDs in the `gpus` option). % Copyright (C) 2014-16 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.expDir = fullfile('data','exp') ; opts.continue = true ; opts.batchSize = 256 ; opts.numSubBatches = 1 ; opts.train = [] ; opts.val = [] ; opts.gpus = [] ; opts.prefetch = false ; opts.numEpochs = 300 ; opts.learningRate = 0.001 ; opts.weightDecay = 0.0005 ; opts.momentum = 0.9 ; opts.randomSeed = 0 ; opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ; opts.profile = false ; opts.conserveMemory = true ; opts.backPropDepth = +inf ; opts.sync = false ; opts.cudnn = true ; opts.errorFunction = 'multiclass' ; opts.errorLabels = {} ; opts.plotDiagnostics = false ; opts.plotStatistics = true; opts = vl_argparse(opts, varargin) ; if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end if isnan(opts.train), opts.train = [] ; end if isnan(opts.val), opts.val = [] ; end % ------------------------------------------------------------------------- % Initialization % ------------------------------------------------------------------------- net = vl_simplenn_tidy(net); % fill in some eventually missing values net.layers{end-1}.precious = 1; % do not remove predictions, used for error vl_simplenn_display(net, 'batchSize', opts.batchSize) ; evaluateMode = isempty(opts.train) ; if ~evaluateMode for i=1:numel(net.layers) if isfield(net.layers{i}, 'weights') J = numel(net.layers{i}.weights) ; if ~isfield(net.layers{i}, 'learningRate') net.layers{i}.learningRate = ones(1, J, 'single') ; end if ~isfield(net.layers{i}, 'weightDecay') net.layers{i}.weightDecay = ones(1, J, 'single') ; end end end end % setup error calculation function hasError = true ; if isstr(opts.errorFunction) switch opts.errorFunction case 'none' opts.errorFunction = @error_none ; hasError = false ; case 'multiclass' opts.errorFunction = @error_multiclass ; if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end case 'binary' opts.errorFunction = @error_binary ; if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end otherwise error('Unknown error function ''%s''.', opts.errorFunction) ; end end state.getBatch = getBatch ; stats = [] ; % ------------------------------------------------------------------------- % Train and validate % ------------------------------------------------------------------------- modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep)); modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ; start = opts.continue * findLastCheckpoint(opts.expDir) ; if start >= 1 fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ; [net, stats] = loadState(modelPath(start)) ; end for epoch=start+1:opts.numEpochs % Set the random seed based on the epoch and opts.randomSeed. % This is important for reproducibility, including when training % is restarted from a checkpoint. rng(epoch + opts.randomSeed) ; prepareGPUs(opts, epoch == start+1) ; % Train for one epoch. state.epoch = epoch ; state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ; state.train = opts.train(randperm(numel(opts.train))) ; % shuffle state.val = opts.val(randperm(numel(opts.val))) ; state.imdb = imdb ; if numel(opts.gpus) <= 1 [net,stats.train(epoch),prof] = process_epoch(net, state, opts, 'train') ; [~,stats.val(epoch)] = process_epoch(net, state, opts, 'val') ; if opts.profile profview(0,prof) ; keyboard ; end else spmd(numGpus) [net_, stats_.train, prof_] = process_epoch(net, state, opts, 'train') ; [~, stats_.val] = process_epoch(net_, state, opts, 'val') ; if labindex == 1, savedNet_ = net_ ; end end net = savedNet_{1} ; stats__ = accumulateStats(stats_) ; stats.train(epoch) = stats__.train ; stats.val(epoch) = stats__.val ; if opts.profile mpiprofile('viewer', [prof_{:,1}]) ; keyboard ; end clear net_ stats_ stats__ savedNet_ ; end % save if ~evaluateMode saveState(modelPath(epoch), net, stats) ; end if opts.plotStatistics switchFigure(1) ; clf ; plots = setdiff(... cat(2,... fieldnames(stats.train)', ... fieldnames(stats.val)'), {'num', 'time'}) ; for p = plots p = char(p) ; values = zeros(0, epoch) ; leg = {} ; for f = {'train', 'val'} f = char(f) ; if isfield(stats.(f), p) tmp = [stats.(f).(p)] ; values(end+1,:) = tmp(1,:)' ; leg{end+1} = f ; end end subplot(1,numel(plots),find(strcmp(p,plots))) ; plot(1:epoch, values','o-') ; xlabel('epoch') ; title(p) ; legend(leg{:}) ; grid on ; end drawnow ; print(1, modelFigPath, '-dpdf') ; end end % ------------------------------------------------------------------------- function err = error_multiclass(opts, labels, res) % ------------------------------------------------------------------------- predictions = gather(res(end-1).x) ; [~,predictions] = sort(predictions, 3, 'descend') ; % be resilient to badly formatted labels if numel(labels) == size(predictions, 4) labels = reshape(labels,1,1,1,[]) ; end % skip null labels mass = single(labels(:,:,1,:) > 0) ; if size(labels,3) == 2 % if there is a second channel in labels, used it as weights mass = mass .* labels(:,:,2,:) ; labels(:,:,2,:) = [] ; end m = min(5, size(predictions,3)) ; error = ~bsxfun(@eq, predictions, labels) ; err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ; err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ; % ------------------------------------------------------------------------- function err = error_binary(opts, labels, res) % ------------------------------------------------------------------------- predictions = gather(res(end-1).x) ; error = bsxfun(@times, predictions, labels) < 0 ; err = sum(error(:)) ; % ------------------------------------------------------------------------- function err = error_none(opts, labels, res) % ------------------------------------------------------------------------- err = zeros(0,1) ; % ------------------------------------------------------------------------- function [net_cpu,stats,prof] = process_epoch(net, state, opts, mode) % ------------------------------------------------------------------------- % initialize empty momentum if strcmp(mode,'train') state.momentum = {} ; for i = 1:numel(net.layers) if isfield(net.layers{i}, 'weights') for j = 1:numel(net.layers{i}.weights) state.layers{i}.momentum{j} = 0 ; end end end end % move CNN to GPU as needed numGpus = numel(opts.gpus) ; if numGpus >= 1 net = vl_simplenn_move(net, 'gpu') ; end if numGpus > 1 mmap = map_gradients(opts.memoryMapFile, net, numGpus) ; else mmap = [] ; end % profile if opts.profile if numGpus <= 1 profile clear ; profile on ; else mpiprofile reset ; mpiprofile on ; end end subset = state.(mode) ; num = 0 ; stats.num = 0 ; % return something even if subset = [] stats.time = 0 ; adjustTime = 0 ; res = [] ; error = [] ; start = tic ; for t=1:opts.batchSize:numel(subset) fprintf('%s: epoch %02d: %3d/%3d:', mode, state.epoch, ... fix((t-1)/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ; batchSize = min(opts.batchSize, numel(subset) - t + 1) ; for s=1:opts.numSubBatches % get this image batch and prefetch the next batchStart = t + (labindex-1) + (s-1) * numlabs ; batchEnd = min(t+opts.batchSize-1, numel(subset)) ; batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ; num = num + numel(batch) ; if numel(batch) == 0, continue ; end [im, labels] = state.getBatch(state.imdb, batch) ; if opts.prefetch if s == opts.numSubBatches batchStart = t + (labindex-1) + opts.batchSize ; batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ; else batchStart = batchStart + numlabs ; end nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ; state.getBatch(state.imdb, nextBatch) ; end if numGpus >= 1 im = gpuArray(im) ; end if strcmp(mode, 'train') dzdy = 1 ; evalMode = 'normal' ; else dzdy = [] ; evalMode = 'test' ; end net.layers{end}.class = labels ; res = vl_simplenn(net, im, dzdy, res, ... 'accumulate', s ~= 1, ... 'mode', evalMode, ... 'conserveMemory', opts.conserveMemory, ... 'backPropDepth', opts.backPropDepth, ... 'sync', opts.sync, ... 'cudnn', opts.cudnn) ; % accumulate errors error = sum([error, [... sum(double(gather(res(end).x))) ; reshape(opts.errorFunction(opts, labels, res),[],1) ; ]],2) ; end % accumulate gradient if strcmp(mode, 'train') if ~isempty(mmap) write_gradients(mmap, net) ; labBarrier() ; end [state, net] = accumulate_gradients(state, net, res, opts, batchSize, mmap) ; end % get statistics time = toc(start) + adjustTime ; batchTime = time - stats.time ; stats = extractStats(net, opts, error / num) ; stats.num = num ; stats.time = time ; currentSpeed = batchSize / batchTime ; averageSpeed = (t + batchSize - 1) / time ; if t == opts.batchSize + 1 % compensate for the first iteration, which is an outlier adjustTime = 2*batchTime - time ; stats.time = time + adjustTime ; end fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ; for f = setdiff(fieldnames(stats)', {'num', 'time'}) f = char(f) ; fprintf(' %s:', f) ; fprintf(' %.3f', stats.(f)) ; end fprintf('\n') ; % collect diagnostic statistics if strcmp(mode, 'train') && opts.plotDiagnostics switchfigure(2) ; clf ; diagn = [res.stats] ; diagnvar = horzcat(diagn.variation) ; barh(diagnvar) ; set(gca,'TickLabelInterpreter', 'none', ... 'YTick', 1:numel(diagnvar), ... 'YTickLabel',horzcat(diagn.label), ... 'YDir', 'reverse', ... 'XScale', 'log', ... 'XLim', [1e-5 1]) ; drawnow ; end end if ~isempty(mmap) unmap_gradients(mmap) ; end if opts.profile if numGpus <= 1 prof = profile('info') ; profile off ; else prof = mpiprofile('info'); mpiprofile off ; end else prof = [] ; end net_cpu = vl_simplenn_move(net, 'cpu') ; % ------------------------------------------------------------------------- function [state, net] = accumulate_gradients(state, net, res, opts, batchSize, mmap) % ------------------------------------------------------------------------- numGpus = numel(opts.gpus) ; otherGpus = setdiff(1:numGpus, labindex) ; for l=numel(net.layers):-1:1 for j=1:numel(res(l).dzdw) % accumualte gradients from multiple labs (GPUs) if needed if numGpus > 1 tag = sprintf('l%d_%d',l,j) ; for g = otherGpus tmp = gpuArray(mmap.Data(g).(tag)) ; res(l).dzdw{j} = res(l).dzdw{j} + tmp ; end end if j == 3 && strcmp(net.layers{l}.type, 'bnorm') % special case for learning bnorm moments thisLR = net.layers{l}.learningRate(j) ; net.layers{l}.weights{j} = ... (1 - thisLR) * net.layers{l}.weights{j} + ... (thisLR/batchSize) * res(l).dzdw{j} ; else % standard gradient training thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j) ; thisLR = state.learningRate * net.layers{l}.learningRate(j) ; state.layers{l}.momentum{j} = opts.momentum * state.layers{l}.momentum{j} ... - thisDecay * net.layers{l}.weights{j} ... - (1 / batchSize) * res(l).dzdw{j} ; net.layers{l}.weights{j} = net.layers{l}.weights{j} + ... thisLR * state.layers{l}.momentum{j} ; end % if requested, collect some useful stats for debugging if opts.plotDiagnostics variation = [] ; label = '' ; switch net.layers{l}.type case {'conv','convt'} variation = thisLR * mean(abs(state.layers{l}.momentum{j}(:))) ; if j == 1 % fiters base = mean(abs(net.layers{l}.weights{j}(:))) ; label = 'filters' ; else % biases base = mean(abs(res(l+1).x(:))) ; label = 'biases' ; end variation = variation / base ; label = sprintf('%s_%s', net.layers{l}.name, label) ; end res(l).stats.variation(j) = variation ; res(l).stats.label{j} = label ; end end end % ------------------------------------------------------------------------- function mmap = map_gradients(fname, net, numGpus) % ------------------------------------------------------------------------- format = {} ; for i=1:numel(net.layers) for j=1:numel(net.layers(i).params) par = net.layers(i).params{j} ; format(end+1,1:3) = {'single', size(par), sprintf('l%d_%d',i,j)} ; end end format(end+1,1:3) = {'double', [3 1], 'errors'} ; if ~exist(fname) && (labindex == 1) f = fopen(fname,'wb') ; for g=1:numGpus for i=1:size(format,1) fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ; end end fclose(f) ; end labBarrier() ; mmap = memmapfile(fname, ... 'Format', format, ... 'Repeat', numGpus, ... 'Writable', true) ; % ------------------------------------------------------------------------- function write_gradients(mmap, net, res) % ------------------------------------------------------------------------- for i=1:numel(net.layers) for j=1:numel(res(i).dzdw) mmap.Data(labindex).(sprintf('l%d_%d',i,j)) = gather(res(i).dzdw{j}) ; end end % ------------------------------------------------------------------------- function unmap_gradients(mmap) % ------------------------------------------------------------------------- % ------------------------------------------------------------------------- function stats = accumulateStats(stats_) % ------------------------------------------------------------------------- for s = {'train', 'val'} s = char(s) ; total = 0 ; % initialize stats stucture with same fields and same order as % stats_{1} stats__ = stats_{1} ; names = fieldnames(stats__.(s))' ; values = zeros(1, numel(names)) ; fields = cat(1, names, num2cell(values)) ; stats.(s) = struct(fields{:}) ; for g = 1:numel(stats_) stats__ = stats_{g} ; num__ = stats__.(s).num ; total = total + num__ ; for f = setdiff(fieldnames(stats__.(s))', 'num') f = char(f) ; stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ; if g == numel(stats_) stats.(s).(f) = stats.(s).(f) / total ; end end end stats.(s).num = total ; end % ------------------------------------------------------------------------- function stats = extractStats(net, opts, errors) % ------------------------------------------------------------------------- stats.objective = errors(1) ; for i = 1:numel(opts.errorLabels) stats.(opts.errorLabels{i}) = errors(i+1) ; end % ------------------------------------------------------------------------- function saveState(fileName, net, stats) % ------------------------------------------------------------------------- save(fileName, 'net', 'stats') ; % ------------------------------------------------------------------------- function [net, stats] = loadState(fileName) % ------------------------------------------------------------------------- load(fileName, 'net', 'stats') ; net = vl_simplenn_tidy(net) ; % ------------------------------------------------------------------------- function epoch = findLastCheckpoint(modelDir) % ------------------------------------------------------------------------- list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ; tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ; epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ; epoch = max([epoch 0]) ; % ------------------------------------------------------------------------- function switchFigure(n) % ------------------------------------------------------------------------- if get(0,'CurrentFigure') ~= n try set(0,'CurrentFigure',n) ; catch figure(n) ; end end % ------------------------------------------------------------------------- function prepareGPUs(opts, cold) % ------------------------------------------------------------------------- numGpus = numel(opts.gpus) ; if numGpus > 1 % check parallel pool integrity as it could have timed out pool = gcp('nocreate') ; if ~isempty(pool) && pool.NumWorkers ~= numGpus delete(pool) ; end pool = gcp('nocreate') ; if isempty(pool) parpool('local', numGpus) ; cold = true ; end if exist(opts.memoryMapFile) delete(opts.memoryMapFile) ; end end if numGpus >= 1 && cold fprintf('%s: resetting GPU\n', mfilename) if numGpus == 1 gpuDevice(opts.gpus) else spmd, gpuDevice(opts.gpus(labindex)), end end end
github
cssjcai/hihca-master
cnn_stn_cluttered_mnist.m
.m
hihca-master/codes/matconvnet/examples/spatial_transformer/cnn_stn_cluttered_mnist.m
3,872
utf_8
3235801f70028cc27d54d15ec2964808
function [net, info] = cnn_stn_cluttered_mnist(varargin) %CNN_STN_CLUTTERED_MNIST Demonstrates training a spatial transformer % The spatial transformer network (STN) is trained on the % cluttered MNIST dataset. run(fullfile(fileparts(mfilename('fullpath')),... '..', '..', 'matlab', 'vl_setupnn.m')) ; opts.dataDir = fullfile(vl_rootnn, 'data') ; opts.useSpatialTransformer = true ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.dataPath = fullfile(opts.dataDir,'cluttered-mnist.mat') ; if opts.useSpatialTransformer opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-stn') ; else opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-no-stn') ; end [opts, varargin] = vl_argparse(opts, varargin) ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.dataURL = 'http://www.vlfeat.org/matconvnet/download/data/cluttered-mnist.mat' ; opts.train = struct() ; opts = vl_argparse(opts, varargin) ; if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end; % -------------------------------------------------------------------- % Prepare data % -------------------------------------------------------------------- if exist(opts.imdbPath, 'file') imdb = load(opts.imdbPath) ; else imdb = getImdDB(opts) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end net = cnn_stn_cluttered_mnist_init([60 60], true) ; % initialize the network net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ; % -------------------------------------------------------------------- % Train % -------------------------------------------------------------------- fbatch = @(i,b) getBatch(opts.train,i,b); [net, info] = cnn_train_dag(net, imdb, fbatch, ... 'expDir', opts.expDir, ... net.meta.trainOpts, ... opts.train, ... 'val', find(imdb.images.set == 2)) ; % -------------------------------------------------------------------- % Show transformer % -------------------------------------------------------------------- figure(100) ; clf ; v = net.getVarIndex('xST') ; net.vars(v).precious = true ; net.eval({'input',imdb.images.data(:,:,:,1:6)}) ; for t = 1:6 subplot(2,6,t) ; imagesc(imdb.images.data(:,:,:,t)) ; axis image off ; subplot(2,6,6+t) ; imagesc(net.vars(v).value(:,:,:,t)) ; axis image off ; colormap gray ; end % -------------------------------------------------------------------- function inputs = getBatch(opts, imdb, batch) % -------------------------------------------------------------------- if ~isa(imdb.images.data, 'gpuArray') && numel(opts.gpus) > 0 imdb.images.data = gpuArray(imdb.images.data); imdb.images.labels = gpuArray(imdb.images.labels); end images = imdb.images.data(:,:,:,batch) ; labels = imdb.images.labels(1,batch) ; inputs = {'input', images, 'label', labels} ; % -------------------------------------------------------------------- function imdb = getImdDB(opts) % -------------------------------------------------------------------- % Prepare the IMDB structure: if ~exist(opts.dataDir, 'dir') mkdir(opts.dataDir) ; end if ~exist(opts.dataPath) fprintf('Downloading %s to %s.\n', opts.dataURL, opts.dataPath) ; urlwrite(opts.dataURL, opts.dataPath) ; end dat = load(opts.dataPath); set = [ones(1,numel(dat.y_tr)) 2*ones(1,numel(dat.y_vl)) 3*ones(1,numel(dat.y_ts))]; data = single(cat(4,dat.x_tr,dat.x_vl,dat.x_ts)); imdb.images.data = data ; imdb.images.labels = single(cat(2, dat.y_tr,dat.y_vl,dat.y_ts)) ; imdb.images.set = set ; imdb.meta.sets = {'train', 'val', 'test'} ; imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
github
cssjcai/hihca-master
cnn_cifar.m
.m
hihca-master/codes/matconvnet/examples/cifar/cnn_cifar.m
5,334
utf_8
eb9aa887d804ee635c4295a7a397206f
function [net, info] = cnn_cifar(varargin) % CNN_CIFAR Demonstrates MatConvNet on CIFAR-10 % The demo includes two standard model: LeNet and Network in % Network (NIN). Use the 'modelType' option to choose one. run(fullfile(fileparts(mfilename('fullpath')), ... '..', '..', 'matlab', 'vl_setupnn.m')) ; opts.modelType = 'lenet' ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.expDir = fullfile(vl_rootnn, 'data', ... sprintf('cifar-%s', opts.modelType)) ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.dataDir = fullfile(vl_rootnn, 'data','cifar') ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.whitenData = true ; opts.contrastNormalization = true ; opts.networkType = 'simplenn' ; opts.train = struct() ; opts = vl_argparse(opts, varargin) ; if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end; % ------------------------------------------------------------------------- % Prepare model and data % ------------------------------------------------------------------------- switch opts.modelType case 'lenet' net = cnn_cifar_init('networkType', opts.networkType) ; case 'nin' net = cnn_cifar_init_nin('networkType', opts.networkType) ; otherwise error('Unknown model type ''%s''.', opts.modelType) ; end if exist(opts.imdbPath, 'file') imdb = load(opts.imdbPath) ; else imdb = getCifarImdb(opts) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end net.meta.classes.name = imdb.meta.classes(:)' ; % ------------------------------------------------------------------------- % Train % ------------------------------------------------------------------------- switch opts.networkType case 'simplenn', trainfn = @cnn_train ; case 'dagnn', trainfn = @cnn_train_dag ; end [net, info] = trainfn(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' fn = @(x,y) getSimpleNNBatch(x,y) ; case 'dagnn' bopts = struct('numGpus', numel(opts.train.gpus)) ; fn = @(x,y) getDagNNBatch(bopts,x,y) ; end % ------------------------------------------------------------------------- function [images, labels] = getSimpleNNBatch(imdb, batch) % ------------------------------------------------------------------------- images = imdb.images.data(:,:,:,batch) ; labels = imdb.images.labels(1,batch) ; if rand > 0.5, images=fliplr(images) ; 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 if opts.numGpus > 0 images = gpuArray(images) ; end inputs = {'input', images, 'label', labels} ; % ------------------------------------------------------------------------- function imdb = getCifarImdb(opts) % ------------------------------------------------------------------------- % Preapre the imdb structure, returns image data with mean image subtracted 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{:})); % remove mean in any case dataMean = mean(data(:,:,:,set == 1), 4); data = bsxfun(@minus, data, dataMean); % normalize by image mean and std as suggested in `An Analysis of % Single-Layer Networks in Unsupervised Feature Learning` Adam % Coates, Honglak Lee, Andrew Y. Ng if opts.contrastNormalization z = reshape(data,[],60000) ; z = bsxfun(@minus, z, mean(z,1)) ; n = std(z,0,1) ; z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ; data = reshape(z, 32, 32, 3, []) ; end if opts.whitenData z = reshape(data,[],60000) ; W = z(:,set == 1)*z(:,set == 1)'/60000 ; [V,D] = eig(W) ; % the scale is selected to approximately preserve the norm of W d2 = diag(D) ; en = sqrt(mean(d2)) ; z = V*diag(en./max(sqrt(d2), 10))*V'*z ; data = reshape(z, 32, 32, 3, []) ; end 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;
github
cssjcai/hihca-master
cnn_imagenet_init.m
.m
hihca-master/codes/matconvnet/examples/imagenet/cnn_imagenet_init.m
14,796
utf_8
77b5cb742e5492a199b796e58430dfcc
function net = cnn_imagenet_init(varargin) % CNN_IMAGENET_INIT Initialize a standard CNN for ImageNet opts.scale = 1 ; opts.initBias = 0.1 ; opts.weightDecay = 1 ; %opts.weightInitMethod = 'xavierimproved' ; opts.weightInitMethod = 'gaussian' ; opts.model = 'alexnet' ; opts.batchNormalization = false ; opts.networkType = 'simplenn' ; opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB opts = vl_argparse(opts, varargin) ; % Define layers switch opts.model case 'alexnet' net.meta.normalization.imageSize = [227, 227, 3] ; net = alexnet(net, opts) ; bs = 256 ; case 'vgg-f' net.meta.normalization.imageSize = [224, 224, 3] ; net = vgg_f(net, opts) ; bs = 256 ; case 'vgg-m' net.meta.normalization.imageSize = [224, 224, 3] ; net = vgg_m(net, opts) ; bs = 196 ; case 'vgg-s' net.meta.normalization.imageSize = [224, 224, 3] ; net = vgg_s(net, opts) ; bs = 128 ; case 'vgg-vd-16' net.meta.normalization.imageSize = [224, 224, 3] ; net = vgg_vd(net, opts) ; bs = 32 ; case 'vgg-vd-19' net.meta.normalization.imageSize = [224, 224, 3] ; net = vgg_vd(net, opts) ; bs = 24 ; otherwise error('Unknown model ''%s''', opts.model) ; end % final touches switch lower(opts.weightInitMethod) case {'xavier', 'xavierimproved'} net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ; end net.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ; % Meta parameters net.meta.inputSize = net.meta.normalization.imageSize ; net.meta.normalization.border = 256 - net.meta.normalization.imageSize(1:2) ; net.meta.normalization.interpolation = 'bicubic' ; net.meta.normalization.averageImage = [] ; net.meta.normalization.keepAspect = true ; net.meta.augmentation.rgbVariance = zeros(0,3) ; net.meta.augmentation.transformation = 'stretch' ; if ~opts.batchNormalization lr = logspace(-2, -4, 60) ; else lr = logspace(-1, -4, 20) ; end net.meta.trainOpts.learningRate = lr ; net.meta.trainOpts.numEpochs = numel(lr) ; net.meta.trainOpts.batchSize = bs ; net.meta.trainOpts.weightDecay = 0.0005 ; % Fill in default values net = vl_simplenn_tidy(net) ; % Switch to DagNN if requested switch lower(opts.networkType) case 'simplenn' % done case 'dagnn' net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ; net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ... {'prediction','label'}, 'top1err') ; net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ... 'opts', {'topK',5}), ... {'prediction','label'}, 'top5err') ; otherwise assert(false) ; end % -------------------------------------------------------------------- function net = add_block(net, opts, id, h, w, in, out, stride, pad) % -------------------------------------------------------------------- info = vl_simplenn_display(net) ; fc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ; if fc name = 'fc' ; else name = 'conv' ; end convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ; net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ... 'weights', {{init_weight(opts, h, w, in, out, 'single'), ... ones(out, 1, 'single')*opts.initBias}}, ... 'stride', stride, ... 'pad', pad, ... 'learningRate', [1 2], ... 'weightDecay', [opts.weightDecay 0], ... 'opts', {convOpts}) ; if opts.batchNormalization net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%s',id), ... 'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single'), ... zeros(out, 2, 'single')}}, ... 'learningRate', [2 1 0.3], ... 'weightDecay', [0 0]) ; end net.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ; % ------------------------------------------------------------------------- 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 % -------------------------------------------------------------------- function net = add_norm(net, opts, id) % -------------------------------------------------------------------- if ~opts.batchNormalization net.layers{end+1} = struct('type', 'normalize', ... 'name', sprintf('norm%s', id), ... 'param', [5 1 0.0001/5 0.75]) ; end % -------------------------------------------------------------------- function net = add_dropout(net, opts, id) % -------------------------------------------------------------------- if ~opts.batchNormalization net.layers{end+1} = struct('type', 'dropout', ... 'name', sprintf('dropout%s', id), ... 'rate', 0.5) ; end % -------------------------------------------------------------------- function net = alexnet(net, opts) % -------------------------------------------------------------------- net.layers = {} ; net = add_block(net, opts, '1', 11, 11, 3, 96, 4, 0) ; net = add_norm(net, opts, '1') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '2', 5, 5, 48, 256, 1, 2) ; net = add_norm(net, opts, '2') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '3', 3, 3, 256, 384, 1, 1) ; net = add_block(net, opts, '4', 3, 3, 192, 384, 1, 1) ; net = add_block(net, opts, '5', 3, 3, 192, 256, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ; net = add_dropout(net, opts, '6') ; net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ; net = add_dropout(net, opts, '7') ; net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ; net.layers(end) = [] ; if opts.batchNormalization, net.layers(end) = [] ; end % -------------------------------------------------------------------- function net = vgg_s(net, opts) % -------------------------------------------------------------------- net.layers = {} ; net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ; net = add_norm(net, opts, '1') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 3, ... 'pad', [0 2 0 2]) ; net = add_block(net, opts, '2', 5, 5, 96, 256, 1, 0) ; net = add_norm(net, opts, '2') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', [0 1 0 1]) ; net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ; net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ; net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 3, ... 'pad', [0 1 0 1]) ; net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ; net = add_dropout(net, opts, '6') ; net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ; net = add_dropout(net, opts, '7') ; net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ; net.layers(end) = [] ; if opts.batchNormalization, net.layers(end) = [] ; end % -------------------------------------------------------------------- function net = vgg_m(net, opts) % -------------------------------------------------------------------- net.layers = {} ; net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ; net = add_norm(net, opts, '1') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '2', 5, 5, 96, 256, 2, 1) ; net = add_norm(net, opts, '2') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', [0 1 0 1]) ; net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ; net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ; net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ; net = add_dropout(net, opts, '6') ; net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ; net = add_dropout(net, opts, '7') ; net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ; net.layers(end) = [] ; if opts.batchNormalization, net.layers(end) = [] ; end % -------------------------------------------------------------------- function net = vgg_f(net, opts) % -------------------------------------------------------------------- net.layers = {} ; net = add_block(net, opts, '1', 11, 11, 3, 64, 4, 0) ; net = add_norm(net, opts, '1') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', [0 1 0 1]) ; net = add_block(net, opts, '2', 5, 5, 64, 256, 1, 2) ; net = add_norm(net, opts, '2') ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '3', 3, 3, 256, 256, 1, 1) ; net = add_block(net, opts, '4', 3, 3, 256, 256, 1, 1) ; net = add_block(net, opts, '5', 3, 3, 256, 256, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ; net = add_dropout(net, opts, '6') ; net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ; net = add_dropout(net, opts, '7') ; net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ; net.layers(end) = [] ; if opts.batchNormalization, net.layers(end) = [] ; end % -------------------------------------------------------------------- function net = vgg_vd(net, opts) % -------------------------------------------------------------------- net.layers = {} ; net = add_block(net, opts, '1_1', 3, 3, 3, 64, 1, 1) ; net = add_block(net, opts, '1_2', 3, 3, 64, 64, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '2_1', 3, 3, 64, 128, 1, 1) ; net = add_block(net, opts, '2_2', 3, 3, 128, 128, 1, 1) ; net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '3_1', 3, 3, 128, 256, 1, 1) ; net = add_block(net, opts, '3_2', 3, 3, 256, 256, 1, 1) ; net = add_block(net, opts, '3_3', 3, 3, 256, 256, 1, 1) ; if strcmp(opts.model, 'vgg-vd-19') net = add_block(net, opts, '3_4', 3, 3, 256, 256, 1, 1) ; end net.layers{end+1} = struct('type', 'pool', 'name', 'pool3', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '4_1', 3, 3, 256, 512, 1, 1) ; net = add_block(net, opts, '4_2', 3, 3, 512, 512, 1, 1) ; net = add_block(net, opts, '4_3', 3, 3, 512, 512, 1, 1) ; if strcmp(opts.model, 'vgg-vd-19') net = add_block(net, opts, '4_4', 3, 3, 512, 512, 1, 1) ; end net.layers{end+1} = struct('type', 'pool', 'name', 'pool4', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '5_1', 3, 3, 512, 512, 1, 1) ; net = add_block(net, opts, '5_2', 3, 3, 512, 512, 1, 1) ; net = add_block(net, opts, '5_3', 3, 3, 512, 512, 1, 1) ; if strcmp(opts.model, 'vgg-vd-19') net = add_block(net, opts, '5_4', 3, 3, 512, 512, 1, 1) ; end net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net = add_block(net, opts, '6', 7, 7, 512, 4096, 1, 0) ; net = add_dropout(net, opts, '6') ; net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ; net = add_dropout(net, opts, '7') ; net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ; net.layers(end) = [] ; if opts.batchNormalization, net.layers(end) = [] ; end
github
cssjcai/hihca-master
cnn_imagenet.m
.m
hihca-master/codes/matconvnet/examples/imagenet/cnn_imagenet.m
7,094
utf_8
9c6d4e185ff55b33f00f87a91ff8d397
function [net, info] = cnn_imagenet(varargin) %CNN_IMAGENET Demonstrates training a CNN on ImageNet % This demo demonstrates training the AlexNet, VGG-F, VGG-S, VGG-M, % VGG-VD-16, and VGG-VD-19 architectures on ImageNet data. run(fullfile(fileparts(mfilename('fullpath')), ... '..', '..', 'matlab', 'vl_setupnn.m')) ; opts.dataDir = fullfile(vl_rootnn, 'data','ILSVRC2012') ; opts.modelType = 'alexnet' ; opts.networkType = 'simplenn' ; opts.batchNormalization = true ; opts.weightInitMethod = 'gaussian' ; [opts, varargin] = vl_argparse(opts, varargin) ; sfx = opts.modelType ; if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end sfx = [sfx '-' opts.networkType] ; opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' sfx]) ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.numFetchThreads = 12 ; opts.lite = false ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.train = struct() ; opts = vl_argparse(opts, varargin) ; if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end; % ------------------------------------------------------------------------- % Prepare model % ------------------------------------------------------------------------- net = cnn_imagenet_init('model', opts.modelType, ... 'batchNormalization', opts.batchNormalization, ... 'weightInitMethod', opts.weightInitMethod, ... 'networkType', opts.networkType) ; % ------------------------------------------------------------------------- % Prepare data % ------------------------------------------------------------------------- if exist(opts.imdbPath) imdb = load(opts.imdbPath) ; else imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end % Set the class names in the network net.meta.classes.name = imdb.classes.name ; net.meta.classes.description = imdb.classes.description ; % Compute image statistics (mean, RGB covariances, etc.) imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ; if exist(imageStatsPath) load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ; else [averageImage, rgbMean, rgbCovariance] = getImageStats(opts, net.meta, imdb) ; save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ; end % Set the image average (use either an image or a color) %net.meta.normalization.averageImage = averageImage ; net.meta.normalization.averageImage = rgbMean ; % Set data augmentation statistics [v,d] = eig(rgbCovariance) ; net.meta.augmentation.rgbVariance = 0.1*sqrt(d)*v' ; clear v d ; % ------------------------------------------------------------------------- % Learn % ------------------------------------------------------------------------- switch opts.networkType case 'simplenn', trainFn = @cnn_train ; case 'dagnn', trainFn = @cnn_train_dag ; end [net, info] = trainFn(net, imdb, getBatchFn(opts, net.meta), ... 'expDir', opts.expDir, ... net.meta.trainOpts, ... opts.train) ; % ------------------------------------------------------------------------- % Deploy % ------------------------------------------------------------------------- net = cnn_imagenet_deploy(net) ; modelPath = fullfile(opts.expDir, 'net-deployed.mat') switch opts.networkType case 'simplenn' save(modelPath, '-struct', 'net') ; case 'dagnn' net_ = net.saveobj() ; save(modelPath, '-struct', 'net_') ; clear net_ ; end % ------------------------------------------------------------------------- function fn = getBatchFn(opts, meta) % ------------------------------------------------------------------------- useGpu = numel(opts.train.gpus) > 0 ; bopts.numThreads = opts.numFetchThreads ; bopts.imageSize = meta.normalization.imageSize ; bopts.border = meta.normalization.border ; bopts.averageImage = meta.normalization.averageImage ; bopts.rgbVariance = meta.augmentation.rgbVariance ; bopts.transformation = meta.augmentation.transformation ; switch lower(opts.networkType) case 'simplenn' fn = @(x,y) getSimpleNNBatch(bopts,x,y) ; case 'dagnn' fn = @(x,y) getDagNNBatch(bopts,useGpu,x,y) ; end % ------------------------------------------------------------------------- function [im,labels] = getSimpleNNBatch(opts, imdb, batch) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; isVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ; if ~isVal % training im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0) ; else % validation: disable data augmentation im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0, ... 'transformation', 'none') ; end if nargout > 0 labels = imdb.images.label(batch) ; end % ------------------------------------------------------------------------- function inputs = getDagNNBatch(opts, useGpu, imdb, batch) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; isVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ; if ~isVal % training im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0) ; else % validation: disable data augmentation im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0, ... 'transformation', 'none') ; end if nargout > 0 if useGpu im = gpuArray(im) ; end labels = imdb.images.label(batch) ; inputs = {'input', im, 'label', labels} ; end % ------------------------------------------------------------------------- function [averageImage, rgbMean, rgbCovariance] = getImageStats(opts, meta, imdb) % ------------------------------------------------------------------------- train = find(imdb.images.set == 1) ; train = train(1: 101: end); bs = 256 ; opts.networkType = 'simplenn' ; fn = getBatchFn(opts, meta) ; avg = {}; rgbm1 = {}; rgbm2 = {}; for t=1:bs:numel(train) batch_time = tic ; batch = train(t:min(t+bs-1, numel(train))) ; fprintf('collecting image stats: batch starting with image %d ...', batch(1)) ; temp = fn(imdb, batch) ; z = reshape(permute(temp,[3 1 2 4]),3,[]) ; n = size(z,2) ; avg{end+1} = mean(temp, 4) ; rgbm1{end+1} = sum(z,2)/n ; rgbm2{end+1} = z*z'/n ; batch_time = toc(batch_time) ; fprintf(' %.2f s (%.1f images/s)\n', batch_time, numel(batch)/ batch_time) ; end averageImage = mean(cat(4,avg{:}),4) ; rgbm1 = mean(cat(2,rgbm1{:}),2) ; rgbm2 = mean(cat(3,rgbm2{:}),3) ; rgbMean = rgbm1 ; rgbCovariance = rgbm2 - rgbm1*rgbm1' ;
github
cssjcai/hihca-master
cnn_imagenet_deploy.m
.m
hihca-master/codes/matconvnet/examples/imagenet/cnn_imagenet_deploy.m
6,583
utf_8
d997af6242f62f37353261224655d713
function net = cnn_imagenet_deploy(net) %CNN_IMAGENET_DEPLOY Deploy a CNN isDag = isa(net, 'dagnn.DagNN') ; if isDag dagRemoveLayersOfType(net, 'dagnn.Loss') ; dagRemoveLayersOfType(net, 'dagnn.DropOut') ; else net = simpleRemoveLayersOfType(net, 'softmaxloss') ; net = simpleRemoveLayersOfType(net, 'dropout') ; end if isDag net.addLayer('prob', dagnn.SoftMax(), 'prediction', 'prob', {}) ; else net.layers{end+1} = struct('name', 'prob', 'type', 'softmax') ; end if isDag dagMergeBatchNorm(net) ; dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ; else net = simpleMergeBatchNorm(net) ; net = simpleRemoveLayersOfType(net, 'bnorm') ; end if ~isDag net = simpleRemoveMomentum(net) ; end % Switch to use MatConvNet default memory limit for CuDNN (512 MB) if ~isDag for l = simpleFindLayersOfType(net, 'conv') net.layers{l}.opts = removeCuDNNMemoryLimit(net.layers{l}.opts) ; end else for name = dagFindLayersOfType(net, 'dagnn.Conv') l = net.getLayerIndex(char(name)) ; net.layers(l).block.opts = removeCuDNNMemoryLimit(net.layers(l).block.opts) ; end end % ------------------------------------------------------------------------- function opts = removeCuDNNMemoryLimit(opts) % ------------------------------------------------------------------------- remove = false(1, numel(opts)) ; for i = 1:numel(opts) if isstr(opts{i}) && strcmp(lower(opts{i}), 'CudnnWorkspaceLimit') remove([i i+1]) = true ; end end opts = opts(~remove) ; % ------------------------------------------------------------------------- function net = simpleRemoveMomentum(net) % ------------------------------------------------------------------------- for l = 1:numel(net.layers) if isfield(net.layers{l}, 'momentum') net.layers{l} = rmfield(net.layers{l}, 'momentum') ; end end % ------------------------------------------------------------------------- function layers = simpleFindLayersOfType(net, type) % ------------------------------------------------------------------------- layers = find(cellfun(@(x)strcmp(x.type, type), net.layers)) ; % ------------------------------------------------------------------------- function net = simpleRemoveLayersOfType(net, type) % ------------------------------------------------------------------------- layers = simpleFindLayersOfType(net, type) ; net.layers(layers) = [] ; % ------------------------------------------------------------------------- function layers = dagFindLayersWithOutput(net, outVarName) % ------------------------------------------------------------------------- layers = {} ; for l = 1:numel(net.layers) if any(strcmp(net.layers(l).outputs, outVarName)) layers{1,end+1} = net.layers(l).name ; end end % ------------------------------------------------------------------------- function layers = dagFindLayersOfType(net, type) % ------------------------------------------------------------------------- layers = [] ; for l = 1:numel(net.layers) if isa(net.layers(l).block, type) layers{1,end+1} = net.layers(l).name ; end end % ------------------------------------------------------------------------- function dagRemoveLayersOfType(net, type) % ------------------------------------------------------------------------- names = dagFindLayersOfType(net, type) ; for i = 1:numel(names) layer = net.layers(net.getLayerIndex(names{i})) ; net.removeLayer(names{i}) ; net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ; end % ------------------------------------------------------------------------- function dagMergeBatchNorm(net) % ------------------------------------------------------------------------- names = dagFindLayersOfType(net, 'dagnn.BatchNorm') ; for name = names name = char(name) ; layer = net.layers(net.getLayerIndex(name)) ; % merge into previous conv layer playerName = dagFindLayersWithOutput(net, layer.inputs{1}) ; playerName = playerName{1} ; playerIndex = net.getLayerIndex(playerName) ; player = net.layers(playerIndex) if ~isa(player.block, 'dagnn.Conv') error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ; end % if the convolution layer does not have a bias, % recreate it to have one if ~player.block.hasBias block = player.block ; block.hasBias = true ; net.renameLayer(playerName, 'tmp') ; net.addLayer(playerName, ... block, ... player.inputs, ... player.outputs, ... {player.params{1}, sprintf('%s_b',playerName)}) ; net.removeLayer('tmp') ; playerIndex = net.getLayerIndex(playerName) ; player = net.layers(playerIndex) ; biases = net.getParamIndex(player.params{2}) ; net.params(biases).value = zeros(block.size(4), 1, 'single') ; end filters = net.getParamIndex(player.params{1}) ; biases = net.getParamIndex(player.params{2}) ; multipliers = net.getParamIndex(layer.params{1}) ; offsets = net.getParamIndex(layer.params{2}) ; moments = net.getParamIndex(layer.params{3}) ; [filtersValue, biasesValue] = mergeBatchNorm(... net.params(filters).value, ... net.params(biases).value, ... net.params(multipliers).value, ... net.params(offsets).value, ... net.params(moments).value) ; net.params(filters).value = filtersValue ; net.params(biases).value = biasesValue ; end % ------------------------------------------------------------------------- function net = simpleMergeBatchNorm(net) % ------------------------------------------------------------------------- for l = 1:numel(net.layers) if strcmp(net.layers{l}.type, 'bnorm') if ~strcmp(net.layers{l-1}.type, 'conv') error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ; end [filters, biases] = mergeBatchNorm(... net.layers{l-1}.weights{1}, ... net.layers{l-1}.weights{2}, ... net.layers{l}.weights{1}, ... net.layers{l}.weights{2}, ... net.layers{l}.weights{3}) ; net.layers{l-1}.weights = {filters, biases} ; end end % ------------------------------------------------------------------------- function [filters, biases] = mergeBatchNorm(filters, biases, multipliers, offsets, moments) % ------------------------------------------------------------------------- % wk / sqrt(sigmak^2 + eps) % bk - wk muk / sqrt(sigmak^2 + eps) a = multipliers(:) ./ moments(:,2) ; b = offsets(:) - moments(:,1) .* a ; biases(:) = biases(:) + b(:) ; sz = size(filters) ; numFilters = sz(4) ; filters = reshape(bsxfun(@times, reshape(filters, [], numFilters), a'), sz) ;
github
cssjcai/hihca-master
cnn_imagenet_evaluate.m
.m
hihca-master/codes/matconvnet/examples/imagenet/cnn_imagenet_evaluate.m
5,194
utf_8
ba3f0f3f96ec666b73e979324c93a300
function info = cnn_imagenet_evaluate(varargin) % CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet run(fullfile(fileparts(mfilename('fullpath')), ... '..', '..', 'matlab', 'vl_setupnn.m')) ; opts.dataDir = fullfile('data', 'ILSVRC2012') ; opts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ; opts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.networkType = [] ; opts.lite = false ; opts.numFetchThreads = 12 ; opts.train.batchSize = 128 ; opts.train.numEpochs = 1 ; opts.train.gpus = [] ; opts.train.prefetch = true ; opts.train.expDir = opts.expDir ; opts = vl_argparse(opts, varargin) ; display(opts); % ------------------------------------------------------------------------- % Database initialization % ------------------------------------------------------------------------- if exist(opts.imdbPath) imdb = load(opts.imdbPath) ; else imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end % ------------------------------------------------------------------------- % Network initialization % ------------------------------------------------------------------------- net = load(opts.modelPath) ; if isfield(net, 'net') ; net = net.net ; end % Cannot use isa('dagnn.DagNN') because it is not an object yet isDag = isfield(net, 'params') ; if isDag opts.networkType = 'dagnn' ; net = dagnn.DagNN.loadobj(net) ; trainfn = @cnn_train_dag ; % Drop existing loss layers drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ; for n = {net.layers(drop).name} net.removeLayer(n) ; end % Extract raw predictions from softmax sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ; predVar = 'prediction' ; for n = {net.layers(sftmx).name} % check if output l = net.getLayerIndex(n) ; v = net.getVarIndex(net.layers(l).outputs{1}) ; if net.vars(v).fanout == 0 % remove this layer and update prediction variable predVar = net.layers(l).inputs{1} ; net.removeLayer(n) ; end end % Add custom objective and loss layers on top of raw predictions net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ... {predVar,'label'}, 'objective') ; net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ... {predVar,'label'}, 'top1err') ; net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ... 'opts', {'topK',5}), ... {predVar,'label'}, 'top5err') ; % Make sure that the input is called 'input' v = net.getVarIndex('data') ; if ~isnan(v) net.renameVar('data', 'input') ; end % Swtich to test mode net.mode = 'test' ; else opts.networkType = 'simplenn' ; net = vl_simplenn_tidy(net) ; trainfn = @cnn_train ; net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss end % Synchronize label indexes used in IMDB with the ones used in NET imdb = cnn_imagenet_sync_labels(imdb, net); % Run evaluation [net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ... opts.train, ... 'train', NaN, ... 'val', find(imdb.images.set==2)) ; % ------------------------------------------------------------------------- function fn = getBatchFn(opts, meta) % ------------------------------------------------------------------------- useGpu = numel(opts.train.gpus) > 0 ; bopts = meta.normalization ; bopts.numThreads = opts.numFetchThreads ; % Most networks are trained by resizing images to 256 pixels and then % cropping a slightly smaller subarea. Reproduce this effect (center % crop) for a more accurate evaluation (it also avoids resizing the % images if these have been pre-processed to be of this size, which % accelerates everything). bopts.border = 256 - meta.normalization.imageSize ; switch lower(opts.networkType) case 'simplenn' fn = @(x,y) getSimpleNNBatch(bopts,x,y) ; case 'dagnn' fn = @(x,y) getDagNNBatch(bopts,useGpu,x,y) ; end % ------------------------------------------------------------------------- function [im,labels] = getSimpleNNBatch(opts, imdb, batch) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0) ; labels = imdb.images.label(batch) ; % ------------------------------------------------------------------------- function inputs = getDagNNBatch(opts, useGpu, imdb, batch) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; im = cnn_imagenet_get_batch(images, opts, ... 'prefetch', nargout == 0) ; if nargout > 0 if useGpu im = gpuArray(im) ; end inputs = {'input', im, 'label', imdb.images.label(batch)} ; end
github
cssjcai/hihca-master
cnn_mnist_init.m
.m
hihca-master/codes/matconvnet/examples/mnist/cnn_mnist_init.m
3,111
utf_8
367b1185af58e108aec40b61818ec6e7
function net = cnn_mnist_init(varargin) % CNN_MNIST_LENET Initialize a CNN similar for MNIST opts.batchNormalization = true ; opts.networkType = 'simplenn' ; opts = vl_argparse(opts, varargin) ; rng('default'); rng(0) ; f=1/100 ; net.layers = {} ; net.layers{end+1} = struct('type', 'conv', ... 'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'pool', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'conv', ... 'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'pool', ... 'method', 'max', ... 'pool', [2 2], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'conv', ... 'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'conv', ... 'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'softmaxloss') ; % optionally switch to batch normalization if opts.batchNormalization net = insertBnorm(net, 1) ; net = insertBnorm(net, 4) ; net = insertBnorm(net, 7) ; end % Meta parameters net.meta.inputSize = [28 28 1] ; net.meta.trainOpts.learningRate = 0.001 ; net.meta.trainOpts.numEpochs = 20 ; net.meta.trainOpts.batchSize = 100 ; % Fill in defaul values net = vl_simplenn_tidy(net) ; % Switch to DagNN if requested switch lower(opts.networkType) case 'simplenn' % done case 'dagnn' net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ; net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ... {'prediction', 'label'}, 'error') ; net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ... 'opts', {'topk', 5}), {'prediction', 'label'}, 'top5err') ; otherwise assert(false) ; end % -------------------------------------------------------------------- function net = insertBnorm(net, l) % -------------------------------------------------------------------- assert(isfield(net.layers{l}, 'weights')); ndim = size(net.layers{l}.weights{1}, 4); layer = struct('type', 'bnorm', ... 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ... 'learningRate', [1 1 0.05], ... 'weightDecay', [0 0]) ; net.layers{l}.biases = [] ; net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
github
cssjcai/hihca-master
cnn_mnist.m
.m
hihca-master/codes/matconvnet/examples/mnist/cnn_mnist.m
4,529
utf_8
eb7627005308bd4d978f29b279cee26e
function [net, info] = cnn_mnist(varargin) %CNN_MNIST Demonstrates MatConvNet on MNIST run(fullfile(fileparts(mfilename('fullpath')),... '..', '..', 'matlab', 'vl_setupnn.m')) ; opts.batchNormalization = false ; opts.networkType = 'simplenn' ; [opts, varargin] = vl_argparse(opts, varargin) ; sfx = opts.networkType ; if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end opts.expDir = fullfile(vl_rootnn, 'data', ['mnist-baseline-' sfx]) ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.dataDir = fullfile(vl_rootnn, 'data', 'mnist') ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.train = struct() ; opts = vl_argparse(opts, varargin) ; if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end; % -------------------------------------------------------------------- % Prepare data % -------------------------------------------------------------------- net = cnn_mnist_init('batchNormalization', opts.batchNormalization, ... 'networkType', opts.networkType) ; if exist(opts.imdbPath, 'file') imdb = load(opts.imdbPath) ; else imdb = getMnistImdb(opts) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ; % -------------------------------------------------------------------- % Train % -------------------------------------------------------------------- switch opts.networkType case 'simplenn', trainfn = @cnn_train ; case 'dagnn', trainfn = @cnn_train_dag ; end [net, info] = trainfn(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' fn = @(x,y) getSimpleNNBatch(x,y) ; case 'dagnn' bopts = struct('numGpus', numel(opts.train.gpus)) ; fn = @(x,y) getDagNNBatch(bopts,x,y) ; end % -------------------------------------------------------------------- function [images, labels] = getSimpleNNBatch(imdb, batch) % -------------------------------------------------------------------- images = imdb.images.data(:,:,:,batch) ; labels = imdb.images.labels(1,batch) ; % -------------------------------------------------------------------- function inputs = getDagNNBatch(opts, imdb, batch) % -------------------------------------------------------------------- images = imdb.images.data(:,:,:,batch) ; labels = imdb.images.labels(1,batch) ; if opts.numGpus > 0 images = gpuArray(images) ; end inputs = {'input', images, 'label', labels} ; % -------------------------------------------------------------------- function imdb = getMnistImdb(opts) % -------------------------------------------------------------------- % Preapre the imdb structure, returns image data with mean image subtracted files = {'train-images-idx3-ubyte', ... 'train-labels-idx1-ubyte', ... 't10k-images-idx3-ubyte', ... 't10k-labels-idx1-ubyte'} ; if ~exist(opts.dataDir, 'dir') mkdir(opts.dataDir) ; end for i=1:4 if ~exist(fullfile(opts.dataDir, files{i}), 'file') url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ; fprintf('downloading %s\n', url) ; gunzip(url, opts.dataDir) ; end end f=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ; x1=fread(f,inf,'uint8'); fclose(f) ; x1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ; f=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ; x2=fread(f,inf,'uint8'); fclose(f) ; x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ; f=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ; y1=fread(f,inf,'uint8'); fclose(f) ; y1=double(y1(9:end)')+1 ; f=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ; y2=fread(f,inf,'uint8'); fclose(f) ; y2=double(y2(9:end)')+1 ; set = [ones(1,numel(y1)) 3*ones(1,numel(y2))]; data = single(reshape(cat(3, x1, x2),28,28,1,[])); dataMean = mean(data(:,:,:,set == 1), 4); data = bsxfun(@minus, data, dataMean) ; imdb.images.data = data ; imdb.images.data_mean = dataMean; imdb.images.labels = cat(2, y1, y2) ; imdb.images.set = set ; imdb.meta.sets = {'train', 'val', 'test'} ; imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
github
cssjcai/hihca-master
vl_nnloss.m
.m
hihca-master/codes/matconvnet/matlab/vl_nnloss.m
10,914
utf_8
3cb323deb2caf15d2f112af93d2b616c
function Y = vl_nnloss(X,c,dzdy,varargin) %VL_NNLOSS CNN categorical or attribute loss. % Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction % scores X given the categorical labels C. % % The prediction scores X are organised as a field of prediction % vectors, represented by a H x W x D x N array. The first two % dimensions, H and W, are spatial and correspond to the height and % width of the field; the third dimension D is the number of % categories or classes; finally, the dimension N is the number of % data items (images) packed in the array. % % While often one has H = W = 1, the case W, H > 1 is useful in % dense labelling problems such as image segmentation. In the latter % case, the loss is summed across pixels (contributions can be % weighed using the `InstanceWeights` option described below). % % The array C contains the categorical labels. In the simplest case, % C is an array of integers in the range [1, D] with N elements % specifying one label for each of the N images. If H, W > 1, the % same label is implicitly applied to all spatial locations. % % In the second form, C has dimension H x W x 1 x N and specifies a % categorical label for each spatial location. % % In the third form, C has dimension H x W x D x N and specifies % attributes rather than categories. Here elements in C are either % +1 or -1 and C, where +1 denotes that an attribute is present and % -1 that it is not. The key difference is that multiple attributes % can be active at the same time, while categories are mutually % exclusive. By default, the loss is *summed* across attributes % (unless otherwise specified using the `InstanceWeights` option % described below). % % DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block % projected onto the output derivative DZDY. DZDX and DZDY have the % same dimensions as X and Y respectively. % % VL_NNLOSS() supports several loss functions, which can be selected % by using the option `type` described below. When each scalar c in % C is interpreted as a categorical label (first two forms above), % the following losses can be used: % % Classification error:: `classerror` % L(X,c) = (argmax_q X(q) ~= c). Note that the classification % error derivative is flat; therefore this loss is useful for % assessment, but not for training a model. % % Top-K classification error:: `topkerror` % L(X,c) = (rank X(c) in X <= K). The top rank is the one with % highest score. For K=1, this is the same as the % classification error. K is controlled by the `topK` option. % % Log loss:: `log` % L(X,c) = - log(X(c)). This function assumes that X(c) is the % predicted probability of class c (hence the vector X must be non % negative and sum to one). % % Softmax log loss (multinomial logistic loss):: `softmaxlog` % L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)). % This is the same as the `log` loss, but renormalizes the % predictions using the softmax function. % % Multiclass hinge loss:: `mhinge` % L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is % the score margin for class c against the other classes. See % also the `mmhinge` loss below. % % Multiclass structured hinge loss:: `mshinge` % L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c} % X(q). This is the same as the `mhinge` loss, but computes the % margin between the prediction scores first. This is also known % the Crammer-Singer loss, an example of a structured prediction % loss. % % When C is a vector of binary attribures c in (+1,-1), each scalar % prediction score x is interpreted as voting for the presence or % absence of a particular attribute. The following losses can be % used: % % Binary classification error:: `binaryerror` % L(x,c) = (sign(x - t) ~= c). t is a threshold that can be % specified using the `threshold` option and defaults to zero. If % x is a probability, it should be set to 0.5. % % Binary log loss:: `binarylog` % L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the % probability that the attribute is active (c=+1). Hence x must be % a number in the range [0,1]. This is the binary version of the % `log` loss. % % Logistic log loss:: `logisticlog` % L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog` % loss, but implicitly normalizes the score x into a probability % using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 + % exp(-x)). This is also equivalent to `softmaxlog` loss where % class c=+1 is assigned score x and class c=-1 is assigned score % 0. % % Hinge loss:: `hinge` % L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for % binary classification. This is equivalent to the `mshinge` loss % if class c=+1 is assigned score x and class c=-1 is assigned % score 0. % % VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals % options: % % InstanceWeights:: [] % Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is % a per-instance weight extracted from the array % `InstanceWeights`. For categorical losses, this is either a H x % W x 1 or a H x W x 1 x N array. For attribute losses, this is % either a H x W x D or a H x W x D x N array. % % TopK:: 5 % Top-K value for the top-K error. Note that K should not % exceed the number of labels. % % See also: VL_NNSOFTMAX(). % Copyright (C) 2014-15 Andrea Vedaldi. % Copyright (C) 2016 Karel Lenc. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.instanceWeights = [] ; opts.classWeights = [] ; opts.threshold = 0 ; opts.loss = 'softmaxlog' ; opts.topK = 5 ; opts = vl_argparse(opts, varargin, 'nonrecursive') ; inputSize = [size(X,1) size(X,2) size(X,3) size(X,4)] ; % Form 1: C has one label per image. In this case, get C in form 2 or % form 3. c = gather(c) ; if numel(c) == inputSize(4) c = reshape(c, [1 1 1 inputSize(4)]) ; c = repmat(c, inputSize(1:2)) ; end hasIgnoreLabel = any(c(:) == 0); % -------------------------------------------------------------------- % Spatial weighting % -------------------------------------------------------------------- labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ; assert(isequal(labelSize(1:2), inputSize(1:2))) ; assert(labelSize(4) == inputSize(4)) ; instanceWeights = [] ; switch lower(opts.loss) case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'} % there must be one categorical label per prediction vector assert(labelSize(3) == 1) ; if hasIgnoreLabel % null labels denote instances that should be skipped instanceWeights = cast(c(:,:,1,:) ~= 0, 'like', c) ; end case {'binaryerror', 'binarylog', 'logistic', 'hinge'} % there must be one categorical label per prediction scalar assert(labelSize(3) == inputSize(3)) ; if hasIgnoreLabel % null labels denote instances that should be skipped instanceWeights = cast(c ~= 0, 'like', c) ; end otherwise error('Unknown loss ''%s''.', opts.loss) ; end if ~isempty(opts.instanceWeights) % important: this code needs to broadcast opts.instanceWeights to % an array of the same size as c if isempty(instanceWeights) instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ; else instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights); end end % -------------------------------------------------------------------- % Do the work % -------------------------------------------------------------------- switch lower(opts.loss) case {'log', 'softmaxlog', 'mhinge', 'mshinge'} % from category labels to indexes numPixelsPerImage = prod(inputSize(1:2)) ; numPixels = numPixelsPerImage * inputSize(4) ; imageVolume = numPixelsPerImage * inputSize(3) ; n = reshape(0:numPixels-1,labelSize) ; offset = 1 + mod(n, numPixelsPerImage) + ... imageVolume * fix(n / numPixelsPerImage) ; ci = offset + numPixelsPerImage * max(c - 1,0) ; end if nargin <= 2 || isempty(dzdy) switch lower(opts.loss) case 'classerror' [~,chat] = max(X,[],3) ; t = cast(c ~= chat, 'like', c) ; case 'topkerror' [~,predictions] = sort(X,3,'descend') ; t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ; case 'log' t = - log(X(ci)) ; case 'softmaxlog' Xmax = max(X,[],3) ; ex = exp(bsxfun(@minus, X, Xmax)) ; t = Xmax + log(sum(ex,3)) - X(ci) ; case 'mhinge' t = max(0, 1 - X(ci)) ; case 'mshinge' Q = X ; Q(ci) = -inf ; t = max(0, 1 - X(ci) + max(Q,[],3)) ; case 'binaryerror' t = cast(sign(X - opts.threshold) ~= c, 'like', c) ; case 'binarylog' t = -log(c.*(X-0.5) + 0.5) ; case 'logistic' %t = log(1 + exp(-c.*X)) ; a = -c.*X ; b = max(0, a) ; t = b + log(exp(-b) + exp(a-b)) ; case 'hinge' t = max(0, 1 - c.*X) ; end if ~isempty(instanceWeights) Y = instanceWeights(:)' * t(:) ; else Y = sum(t(:)); end else if ~isempty(instanceWeights) dzdy = dzdy * instanceWeights ; end switch lower(opts.loss) case {'classerror', 'topkerror'} Y = zerosLike(X) ; case 'log' Y = zerosLike(X) ; Y(ci) = - dzdy ./ max(X(ci), 1e-8) ; case 'softmaxlog' Xmax = max(X,[],3) ; ex = exp(bsxfun(@minus, X, Xmax)) ; Y = bsxfun(@rdivide, ex, sum(ex,3)) ; Y(ci) = Y(ci) - 1 ; Y = bsxfun(@times, dzdy, Y) ; case 'mhinge' Y = zerosLike(X) ; Y(ci) = - dzdy .* (X(ci) < 1) ; case 'mshinge' Q = X ; Q(ci) = -inf ; [~, q] = max(Q,[],3) ; qi = offset + numPixelsPerImage * (q - 1) ; W = dzdy .* (X(ci) - X(qi) < 1) ; Y = zerosLike(X) ; Y(ci) = - W ; Y(qi) = + W ; case 'binaryerror' Y = zerosLike(X) ; case 'binarylog' Y = - dzdy ./ (X + (c-1)*0.5) ; case 'logistic' % t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y) % t = 1 / (1 + exp(Y.*X)) .* (-Y) Y = - dzdy .* c ./ (1 + exp(c.*X)) ; case 'hinge' Y = - dzdy .* c .* (c.*X < 1) ; end end % -------------------------------------------------------------------- function y = zerosLike(x) % -------------------------------------------------------------------- if isa(x,'gpuArray') y = gpuArray.zeros(size(x),classUnderlying(x)) ; else y = zeros(size(x),'like',x) ; end % -------------------------------------------------------------------- function y = onesLike(x) % -------------------------------------------------------------------- if isa(x,'gpuArray') y = gpuArray.ones(size(x),classUnderlying(x)) ; else y = ones(size(x),'like',x) ; end
github
cssjcai/hihca-master
vl_compilenn.m
.m
hihca-master/codes/matconvnet/matlab/vl_compilenn.m
28,777
utf_8
9752bfab3ea0e3dc4ac81b8e8fca75e6
function vl_compilenn(varargin) %VL_COMPILENN Compile the MatConvNet toolbox. % The `vl_compilenn()` function compiles the MEX files in the % MatConvNet toolbox. See below for the requirements for compiling % CPU and GPU code, respectively. % % `vl_compilenn('OPTION', ARG, ...)` accepts the following options: % % `EnableGpu`:: `false` % Set to true in order to enable GPU support. % % `Verbose`:: 0 % Set the verbosity level (0, 1 or 2). % % `Debug`:: `false` % Set to true to compile the binaries with debugging % information. % % `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc` % Choose the method used to compile the CUDA code. There are two % methods: % % * The **`mex`** method uses the MATLAB MEX command with the % configuration file % `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]` % This configuration file is in XML format since MATLAB 8.3 % (R2014a) and is a Shell script for earlier versions. This % is, principle, the preferred method as it uses the % MATLAB-sanctioned compiler options. % % * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc` % directly to compile CUDA source code into object files. % % This method allows to use a CUDA toolkit version that is not % the one that officially supported by a particular MATALB % version (see below). It is also the default method for % compilation under Windows and with CuDNN. % % `CudaRoot`:: guessed automatically % This option specifies the path to the CUDA toolkit to use for % compilation. % % `EnableImreadJpeg`:: `true` % Set this option to `true` to compile `vl_imreadjpeg`. % % `EnableDouble`:: `true` % Set this optino to `true` to compile the support for DOUBLE % data types. % % `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac) % The image library to use for `vl_impreadjpeg`. % % `ImageLibraryCompileFlags`:: platform dependent % A cell-array of additional flags to use when compiling % `vl_imreadjpeg`. % % `ImageLibraryLinkFlags`:: platform dependent % A cell-array of additional flags to use when linking % `vl_imreadjpeg`. % % `EnableCudnn`:: `false` % Set to `true` to compile CuDNN support. See CuDNN % documentation for the Hardware/CUDA version requirements. % % `CudnnRoot`:: `'local/'` % Directory containing the unpacked binaries and header files of % the CuDNN library. % % ## Compiling the CPU code % % By default, the `EnableGpu` option is switched to off, such that % the GPU code support is not compiled in. % % Generally, you only need a 64bit C/C++ compiler (usually Xcode, GCC or % Visual Studio for Mac, Linux, and Windows respectively). The % compiler can be setup in MATLAB using the % % mex -setup % % command. % % ## Compiling the GPU code % % In order to compile the GPU code, set the `EnableGpu` option to % `true`. For this to work you will need: % % * To satisfy all the requirement to compile the CPU code (see % above). % % * A NVIDIA GPU with at least *compute capability 2.0*. % % * The *MATALB Parallel Computing Toolbox*. This can be purchased % from Mathworks (type `ver` in MATLAB to see if this toolbox is % already comprised in your MATLAB installation; it often is). % % * A copy of the *CUDA Devkit*, which can be downloaded for free % from NVIDIA. Note that each MATLAB version requires a % particular CUDA Devkit version: % % | MATLAB version | Release | CUDA Devkit | % |----------------|---------|--------------| % | 8.2 | 2013b | 5.5 | % | 8.3 | 2014a | 5.5 | % | 8.4 | 2014b | 6.0 | % | 8.6 | 2015b | Latest(>7.0) | % % A different versions of CUDA may work using the hack described % above (i.e. setting the `CudaMethod` to `nvcc`). % % The following configurations have been tested successfully: % % * Windows 7 x64, MATLAB R2014a, Visual C++ 2010, 2013 and CUDA Toolkit % 6.5. VS 2015 CPU version only (not supported by CUDA Toolkit yet). % * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA % Toolkit 6.5. % * Mac OS X 10.9 and 10.10, MATLAB R2013a and R2013b, Xcode, CUDA % Toolkit 5.5. % * GNU/Linux, MATALB R2014a/R2015a/R2015b, gcc/g++, CUDA Toolkit 5.5/6.5/7.5. % % Compilation on Windows with MinGW compiler (the default mex compiler in % Matlab) is not supported. For Windows, please reconfigure mex to use % Visual Studio C/C++ compiler. % Furthermore your GPU card must have ComputeCapability >= 2.0 (see % output of `gpuDevice()`) in order to be able to run the GPU code. % To change the compute capabilities, for `mex` `CudaMethod` edit % the particular config file. For the 'nvcc' method, compute % capability is guessed based on the GPUDEVICE output. You can % override it by setting the 'CudaArch' parameter (e.g. in case of % multiple GPUs with various architectures). % % See also: [Compliling MatConvNet](../install.md#compiling), % [Compiling MEX files containing CUDA % code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html), % `vl_setup()`, `vl_imreadjpeg()`. % Copyright (C) 2014-16 Karel Lenc and Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). % Get MatConvNet root directory root = fileparts(fileparts(mfilename('fullpath'))) ; addpath(fullfile(root, 'matlab')) ; % -------------------------------------------------------------------- % Parse options % -------------------------------------------------------------------- opts.enableGpu = false; opts.enableImreadJpeg = true; opts.enableCudnn = false; opts.enableDouble = true; opts.imageLibrary = [] ; opts.imageLibraryCompileFlags = {} ; opts.imageLibraryLinkFlags = [] ; opts.verbose = 0; opts.debug = false; opts.cudaMethod = [] ; opts.cudaRoot = [] ; opts.cudaArch = [] ; opts.defCudaArch = [... '-gencode=arch=compute_20,code=\"sm_20,compute_20\" '... '-gencode=arch=compute_30,code=\"sm_30,compute_30\"']; opts.cudnnRoot = 'local/cudnn' ; opts = vl_argparse(opts, varargin); % -------------------------------------------------------------------- % Files to compile % -------------------------------------------------------------------- arch = computer('arch') ; if isempty(opts.imageLibrary) switch arch case 'glnxa64', opts.imageLibrary = 'libjpeg' ; case 'maci64', opts.imageLibrary = 'quartz' ; case 'win64', opts.imageLibrary = 'gdiplus' ; end end if isempty(opts.imageLibraryLinkFlags) switch opts.imageLibrary case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ; case 'quartz', opts.imageLibraryLinkFlags = {'-framework Cocoa -framework ImageIO'} ; case 'gdiplus', opts.imageLibraryLinkFlags = {'gdiplus.lib'} ; end end lib_src = {} ; mex_src = {} ; % Files that are compiled as CPP or CU depending on whether GPU support % is enabled. if opts.enableGpu, ext = 'cu' ; else ext='cpp' ; end lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbilinearsampler.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbilinearsampler.' ext]) ; % CPU-specific files lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','imread.cpp') ; % GPU-specific files if opts.enableGpu lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ; end % cuDNN-specific files if opts.enableCudnn lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbilinearsampler_cudnn.cu') ; end % Other files if opts.enableImreadJpeg mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ; end % -------------------------------------------------------------------- % Setup CUDA toolkit % -------------------------------------------------------------------- if opts.enableGpu opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ; % Find the CUDA Devkit if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts) ; end opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ... mfilename, opts.cudaRoot) ; opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ; switch arch case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ; case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ; case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ; otherwise, error('Unsupported architecture ''%s''.', arch) ; end % Set the nvcc method as default for Win platforms if strcmp(arch, 'win64') && isempty(opts.cudaMethod) opts.cudaMethod = 'nvcc'; end % Activate the CUDA Devkit cuver = activate_nvcc(opts.nvccPath) ; opts.verbose && fprintf('%s:\tCUDA: using NVCC ''%s'' (%d).\n', ... mfilename, opts.nvccPath, cuver) ; % Set the CUDA arch string (select GPU architecture) if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ... mfilename, opts.cudaArch) ; end if opts.enableCudnn opts.cudnnIncludeDir = fullfile(opts.cudnnRoot, 'include') ; switch arch case 'win64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib', 'x64') ; case 'maci64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib') ; case 'glnxa64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib64') ; otherwise, error('Unsupported architecture ''%s''.', arch) ; end end % -------------------------------------------------------------------- % Compiler options % -------------------------------------------------------------------- % Build directories mex_dir = fullfile(root, 'matlab', 'mex') ; bld_dir = fullfile(mex_dir, '.build'); if ~exist(fullfile(bld_dir,'bits','impl'), 'dir') mkdir(fullfile(bld_dir,'bits','impl')) ; end % Compiler flags flags.cc = {} ; flags.ccpass = {} ; flags.ccoptim = {} ; flags.link = {} ; flags.linklibs = {} ; flags.linkpass = {} ; flags.nvccpass = {char(opts.cudaArch)} ; if opts.verbose > 1 flags.cc{end+1} = '-v' ; end if opts.debug flags.cc{end+1} = '-g' ; flags.nvccpass{end+1} = '-O0' ; else flags.cc{end+1} = '-DNDEBUG' ; end if opts.enableGpu flags.cc{end+1} = '-DENABLE_GPU' ; end if opts.enableCudnn flags.cc{end+1} = '-DENABLE_CUDNN' ; flags.cc{end+1} = ['-I' opts.cudnnIncludeDir] ; end if opts.enableDouble flags.cc{end+1} = '-DENABLE_DOUBLE' ; end flags.link{end+1} = '-lmwblas' ; switch arch case {'maci64', 'glnxa64'} case {'win64'} % VisualC does not pass this even if available in the CPU architecture flags.cc{end+1} = '-D__SSSE3__' ; end if opts.enableImreadJpeg flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ; flags.linklibs = horzcat(flags.linklibs, opts.imageLibraryLinkFlags) ; end if opts.enableGpu flags.link = horzcat(flags.link, {['-L' opts.cudaLibDir], '-lcudart', '-lcublas'}) ; switch arch case {'maci64', 'glnxa64'} flags.link{end+1} = '-lmwgpu' ; case 'win64' flags.link{end+1} = '-lgpu' ; end if opts.enableCudnn flags.link{end+1} = ['-L' opts.cudnnLibDir] ; flags.link{end+1} = '-lcudnn' ; end end switch arch case {'maci64'} flags.ccpass{end+1} = '-mmacosx-version-min=10.9' ; flags.linkpass{end+1} = '-mmacosx-version-min=10.9' ; flags.ccoptim{end+1} = '-mssse3 -ffast-math' ; flags.nvccpass{end+1} = '-Xcompiler -fPIC' ; if opts.enableGpu flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ; end if opts.enableGpu && opts.enableCudnn flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ; end if opts.enableGpu && cuver < 70000 % CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native % clang libc++. This should go away in the future. flags.ccpass{end+1} = '-stdlib=libstdc++' ; flags.linkpass{end+1} = '-stdlib=libstdc++' ; if ~verLessThan('matlab', '8.5.0') % Complicating matters, MATLAB 8.5.0 links to clang's libc++ by % default when linking MEX files overriding the option above. We % force it to use GCC libstdc++ flags.linkpass{end+1} = '-L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ; end end case {'glnxa64'} flags.ccoptim{end+1} = '-mssse3 -ftree-vect-loop-version -ffast-math -funroll-all-loops' ; flags.nvccpass{end+1} = '-Xcompiler -fPIC' ; if opts.enableGpu flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ; end if opts.enableGpu && opts.enableCudnn flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ; end case {'win64'} flags.nvccpass{end+1} = '-Xcompiler /MD' ; check_clpath(); % check whether cl.exe in path end % -------------------------------------------------------------------- % Command flags % -------------------------------------------------------------------- flags.mexcc = horzcat(flags.cc, ... {'-largeArrayDims'}, ... {['CXXFLAGS=$CXXFLAGS ' strjoin(flags.ccpass)]}, ... {['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' strjoin(flags.ccoptim)]}) ; if ~ispc, flags.mexcc{end+1} = '-cxx'; end % mex: compile GPU flags.mexcu= horzcat({'-f' mex_cuda_config(root)}, ... flags.cc, ... {'-largeArrayDims'}, ... {['CXXFLAGS=$CXXFLAGS ' quote_nvcc(flags.ccpass) ' ' strjoin(flags.nvccpass)]}, ... {['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' quote_nvcc(flags.ccoptim)]}) ; % mex: link flags.mexlink = horzcat(flags.cc, flags.link, ... {'-largeArrayDims'}, ... {['LDFLAGS=$LDFLAGS ', strjoin(flags.linkpass)]}, ... {['LINKLIBS=$LINKLIBS ', strjoin(flags.linklibs)]}) ; % nvcc: compile GPU flags.nvcc = horzcat(flags.cc, ... {opts.cudaArch}, ... {sprintf('-I"%s"', fullfile(matlabroot, 'extern', 'include'))}, ... {sprintf('-I"%s"', fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include'))}, ... { quote_nvcc(flags.ccpass)}, ... flags.nvccpass) ; if opts.verbose fprintf('%s: * Compiler and linker configurations *\n', mfilename) ; fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ; fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ; fprintf('%s: \tMEX options [CC CPU]: %s\n', mfilename, strjoin(flags.mexcc)) ; fprintf('%s: \tMEX options [LINK]: %s\n', mfilename, strjoin(flags.mexlink)) ; end if opts.verbose && opts.enableGpu fprintf('%s: \tMEX options [CC GPU]: %s\n', mfilename, strjoin(flags.mexcu)) ; end if opts.verbose && opts.enableGpu && strcmp(opts.cudaMethod,'nvcc') fprintf('%s: \tNVCC options [CC GPU]: %s\n', mfilename, strjoin(flags.nvcc)) ; end if opts.verbose && opts.enableImreadJpeg fprintf('%s: * Reading images *\n', mfilename) ; fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ; fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ; fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ; fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ; end % -------------------------------------------------------------------- % Compile % -------------------------------------------------------------------- % Intermediate object files srcs = horzcat(lib_src,mex_src) ; for i = 1:numel(horzcat(lib_src, mex_src)) [~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ; objfile = toobj(bld_dir,srcs{i}); if strcmp(ext,'cu') if strcmp(opts.cudaMethod,'nvcc') nvcc_compile(opts, srcs{i}, objfile, flags.nvcc) ; else mex_compile(opts, srcs{i}, objfile, flags.mexcu) ; end else mex_compile(opts, srcs{i}, objfile, flags.mexcc) ; end assert(exist(objfile, 'file') ~= 0, 'Compilation of %s failed.', objfile); end % Link into MEX files for i = 1:numel(mex_src) objs = toobj(bld_dir, [mex_src(i), lib_src]) ; mex_link(opts, objs, mex_dir, flags.mexlink) ; end % Reset path adding the mex subdirectory just created vl_setupnn() ; % -------------------------------------------------------------------- % Utility functions % -------------------------------------------------------------------- % -------------------------------------------------------------------- function objs = toobj(bld_dir,srcs) % -------------------------------------------------------------------- str = fullfile('matlab','src') ; multiple = iscell(srcs) ; if ~multiple, srcs = {srcs} ; end objs = cell(1, numel(srcs)); for t = 1:numel(srcs) i = strfind(srcs{t},str); objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ; end if ~multiple, objs = objs{1} ; end objs = regexprep(objs,'.cpp$',['.' objext]) ; objs = regexprep(objs,'.cu$',['.' objext]) ; objs = regexprep(objs,'.c$',['.' objext]) ; % -------------------------------------------------------------------- function mex_compile(opts, src, tgt, mex_opts) % -------------------------------------------------------------------- mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ; opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ; mex(mopts{:}) ; % -------------------------------------------------------------------- function nvcc_compile(opts, src, tgt, nvcc_opts) % -------------------------------------------------------------------- nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc'); nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ... nvcc_path, src, ... strjoin(nvcc_opts), tgt); opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ; status = system(nvcc_cmd); if status, error('Command %s failed.', nvcc_cmd); end; % -------------------------------------------------------------------- function mex_link(opts, objs, mex_dir, mex_flags) % -------------------------------------------------------------------- mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ; opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ; mex(mopts{:}) ; % -------------------------------------------------------------------- function ext = objext() % -------------------------------------------------------------------- % Get the extension for an 'object' file for the current computer % architecture switch computer('arch') case 'win64', ext = 'obj'; case {'maci64', 'glnxa64'}, ext = 'o' ; otherwise, error('Unsupported architecture %s.', computer) ; end % -------------------------------------------------------------------- function conf_file = mex_cuda_config(root) % -------------------------------------------------------------------- % Get mex CUDA config file mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ; if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end arch = computer('arch') ; switch arch case {'win64'} config_dir = fullfile(matlabroot, 'toolbox', ... 'distcomp', 'gpu', 'extern', ... 'src', 'mex', arch) ; case {'maci64', 'glnxa64'} config_dir = fullfile(root, 'matlab', 'src', 'config') ; end conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]); fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file); % -------------------------------------------------------------------- function check_clpath() % -------------------------------------------------------------------- % Checks whether the cl.exe is in the path (needed for the nvcc). If % not, tries to guess the location out of mex configuration. [status, ~] = system('cl.exe -help'); if status == 1 warning('CL.EXE not found in PATH. Trying to guess out of mex setup.'); cc = mex.getCompilerConfigurations('c++'); if isempty(cc) error('Mex is not configured. Run "mex -setup".'); end prev_path = getenv('PATH'); cl_path = fullfile(cc.Location, 'VC','bin','amd64'); setenv('PATH', [prev_path ';' cl_path]); status = system('cl.exe'); if status == 1 setenv('PATH', prev_path); error('Unable to find cl.exe'); else fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ... cl_path); end end % ------------------------------------------------------------------------- function paths = which_nvcc() % ------------------------------------------------------------------------- switch computer('arch') case 'win64' [~, paths] = system('where nvcc.exe'); paths = strtrim(paths); paths = paths(strfind(paths, '.exe')); case {'maci64', 'glnxa64'} [~, paths] = system('which nvcc'); paths = strtrim(paths) ; end % ------------------------------------------------------------------------- function cuda_root = search_cuda_devkit(opts) % ------------------------------------------------------------------------- % This function tries to to locate a working copy of the CUDA Devkit. opts.verbose && fprintf(['%s:\tCUDA: searching for the CUDA Devkit' ... ' (use the option ''CudaRoot'' to override):\n'], mfilename); % Propose a number of candidate paths for NVCC paths = {getenv('MW_NVCC_PATH')} ; paths = [paths, which_nvcc()] ; for v = {'5.5', '6.0', '6.5', '7.0', '7.5'} switch computer('arch') case 'glnxa64' paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ; case 'maci64' paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ; case 'win64' paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ; end end paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ; % Validate each candidate NVCC path for i=1:numel(paths) nvcc(i).path = paths{i} ; [nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(paths{i}) ; end if opts.verbose fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ; for i=1:numel(paths) fprintf('\t| %5d | %5d | %-70s |\n', ... nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ; end end % Pick an entry index = find([nvcc.isvalid]) ; if isempty(index) error('Could not find a valid NVCC executable\n') ; end [~, newest] = max([nvcc(index).version]); nvcc = nvcc(index(newest)) ; cuda_root = fileparts(fileparts(nvcc.path)) ; if opts.verbose fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ... mfilename, nvcc.path, nvcc.version) ; end % ------------------------------------------------------------------------- function [valid, cuver] = validate_nvcc(nvccPath) % ------------------------------------------------------------------------- [status, output] = system(sprintf('"%s" --version', nvccPath)) ; valid = (status == 0) ; if ~valid cuver = 0 ; return ; end match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ; if isempty(match), valid = false ; return ; end cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ; % -------------------------------------------------------------------- function cuver = activate_nvcc(nvccPath) % -------------------------------------------------------------------- % Validate the NVCC compiler installation [valid, cuver] = validate_nvcc(nvccPath) ; if ~valid error('The NVCC compiler ''%s'' does not appear to be valid.', nvccPath) ; end % Make sure that NVCC is visible by MEX by setting the MW_NVCC_PATH % environment variable to the NVCC compiler path if ~strcmp(getenv('MW_NVCC_PATH'), nvccPath) warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', nvccPath) ; setenv('MW_NVCC_PATH', nvccPath) ; end % In some operating systems and MATLAB versions, NVCC must also be % available in the command line search path. Make sure that this is% % the case. [valid_, cuver_] = validate_nvcc('nvcc') ; if ~valid_ || cuver_ ~= cuver warning('NVCC not found in the command line path or the one found does not matches ''%s''.', nvccPath); nvccDir = fileparts(nvccPath) ; prevPath = getenv('PATH') ; switch computer case 'PCWIN64', separator = ';' ; case {'GLNXA64', 'MACI64'}, separator = ':' ; end setenv('PATH', [nvccDir separator prevPath]) ; [valid_, cuver_] = validate_nvcc('nvcc') ; if ~valid_ || cuver_ ~= cuver setenv('PATH', prevPath) ; error('Unable to set the command line path to point to ''%s'' correctly.', nvccPath) ; else fprintf('Location of NVCC (%s) added to your command search PATH.\n', nvccDir) ; end end % ------------------------------------------------------------------------- function str = quote_nvcc(str) % ------------------------------------------------------------------------- if iscell(str), str = strjoin(str) ; end str = strrep(strtrim(str), ' ', ',') ; if ~isempty(str), str = ['-Xcompiler ' str] ; end % -------------------------------------------------------------------- function cudaArch = get_cuda_arch(opts) % -------------------------------------------------------------------- opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename); try gpu_device = gpuDevice(); arch_code = strrep(gpu_device.ComputeCapability, '.', ''); cudaArch = ... sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ... arch_code, arch_code, arch_code) ; catch opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU;' ... 'falling back to default\n'], mfilename); cudaArch = opts.defCudaArch; end
github
cssjcai/hihca-master
getVarReceptiveFields.m
.m
hihca-master/codes/matconvnet/matlab/+dagnn/@DagNN/getVarReceptiveFields.m
3,549
utf_8
ca843d13890184e1451248f43f7d4011
function rfs = getVarReceptiveFields(obj, var) %GETVARRECEPTIVEFIELDS Get the receptive field of a variable % RFS = GETVARRECEPTIVEFIELDS(OBJ, VAR) gets the receptivie fields RFS of % all the variables of the DagNN OBJ into variable VAR. VAR is a variable % name or index. % % RFS has one entry for each variable in the DagNN following the same % format as has DAGNN.GETRECEPTIVEFIELDS(). For example, RFS(i) is the % receptive field of the i-th variable in the DagNN into variable VAR. If % the i-th variable is not a descendent of VAR in the DAG, then there is % no receptive field, indicated by `rfs(i).size == []`. If the receptive % field cannot be computed (e.g. because it depends on the values of % variables and not just on the network topology, or if it cannot be % expressed as a sliding window), then `rfs(i).size = [NaN NaN]`. % Copyright (C) 2015 Karel Lenc and Andrea Vedaldi. All rights reserved. % % This file is part of the VLFeat library and is made available under the % terms of the BSD license (see the COPYING file). if ~isnumeric(var), var = obj.getVarIndex(var) ; end nv = numel(obj.vars) ; nw = numel(var) ; rfs = struct('size', cell(nw, nv), 'stride', cell(nw, nv), 'offset', cell(nw,nv)) ; for w = 1:numel(var) rfs(w,var(w)).size = [1 1] ; rfs(w,var(w)).stride = [1 1] ; rfs(w,var(w)).offset = [1 1] ; end for l = obj.executionOrder % visit all blocks and get their receptive fields in = obj.layers(l).inputIndexes ; out = obj.layers(l).outputIndexes ; blockRfs = obj.layers(l).block.getReceptiveFields() ; for w = 1:numel(var) % find the receptive fields in each of the inputs of the block for i = 1:numel(in) for j = 1:numel(out) rf = composeReceptiveFields(rfs(w, in(i)), blockRfs(i,j)) ; rfs(w, out(j)) = resolveReceptiveFields([rfs(w, out(j)), rf]) ; end end end end end % ------------------------------------------------------------------------- function rf = composeReceptiveFields(rf1, rf2) % ------------------------------------------------------------------------- if isempty(rf1.size) || isempty(rf2.size) rf.size = [] ; rf.stride = [] ; rf.offset = [] ; return ; end rf.size = rf1.stride .* (rf2.size - 1) + rf1.size ; rf.stride = rf1.stride .* rf2.stride ; rf.offset = rf1.stride .* (rf2.offset - 1) + rf1.offset ; end % ------------------------------------------------------------------------- function rf = resolveReceptiveFields(rfs) % ------------------------------------------------------------------------- rf.size = [] ; rf.stride = [] ; rf.offset = [] ; for i = 1:numel(rfs) if isempty(rfs(i).size), continue ; end if isnan(rfs(i).size) rf.size = [NaN NaN] ; rf.stride = [NaN NaN] ; rf.offset = [NaN NaN] ; break ; end if isempty(rf.size) rf = rfs(i) ; else if ~isequal(rf.stride,rfs(i).stride) % incompatible geometry; this cannot be represented by a sliding % window RF field and may denotes an error in the network structure rf.size = [NaN NaN] ; rf.stride = [NaN NaN] ; rf.offset = [NaN NaN] ; break; else % the two RFs have the same stride, so they can be recombined % the new RF is just large enough to contain both of them a = rf.offset - (rf.size-1)/2 ; b = rf.offset + (rf.size-1)/2 ; c = rfs(i).offset - (rfs(i).size-1)/2 ; d = rfs(i).offset + (rfs(i).size-1)/2 ; e = min(a,c) ; f = max(b,d) ; rf.offset = (e+f)/2 ; rf.size = f-e+1 ; end end end end
github
cssjcai/hihca-master
rebuild.m
.m
hihca-master/codes/matconvnet/matlab/+dagnn/@DagNN/rebuild.m
3,103
utf_8
2051dfdfff3e31e12ab7ac483c251515
function rebuild(obj) %REBUILD Rebuild the internal data structures of a DagNN object % REBUILD(obj) rebuilds the internal data structures % of the DagNN obj. It is an helper function used internally % to update the network when layers are added or removed. varFanIn = zeros(1, numel(obj.vars)) ; varFanOut = zeros(1, numel(obj.vars)) ; parFanOut = zeros(1, numel(obj.params)) ; for l = 1:numel(obj.layers) ii = obj.getVarIndex(obj.layers(l).inputs) ; oi = obj.getVarIndex(obj.layers(l).outputs) ; pi = obj.getParamIndex(obj.layers(l).params) ; obj.layers(l).inputIndexes = ii ; obj.layers(l).outputIndexes = oi ; obj.layers(l).paramIndexes = pi ; varFanOut(ii) = varFanOut(ii) + 1 ; varFanIn(oi) = varFanIn(oi) + 1 ; parFanOut(pi) = parFanOut(pi) + 1 ; end [obj.vars.fanin] = tolist(num2cell(varFanIn)) ; [obj.vars.fanout] = tolist(num2cell(varFanOut)) ; if ~isempty(parFanOut), [obj.params.fanout] = tolist(num2cell(parFanOut)) ; end % dump unused variables keep = (varFanIn + varFanOut) > 0 ; obj.vars = obj.vars(keep) ; varRemap = cumsum(keep) ; % dump unused parameters keep = parFanOut > 0 ; obj.params = obj.params(keep) ; parRemap = cumsum(keep) ; % update the indexes to account for removed layers, variables and parameters for l = 1:numel(obj.layers) obj.layers(l).inputIndexes = varRemap(obj.layers(l).inputIndexes) ; obj.layers(l).outputIndexes = varRemap(obj.layers(l).outputIndexes) ; obj.layers(l).paramIndexes = parRemap(obj.layers(l).paramIndexes) ; obj.layers(l).block.layerIndex = l ; end % update the variable and parameter names hash maps obj.varNames = cell2struct(num2cell(1:numel(obj.vars)), {obj.vars.name}, 2) ; obj.paramNames = cell2struct(num2cell(1:numel(obj.params)), {obj.params.name}, 2) ; obj.layerNames = cell2struct(num2cell(1:numel(obj.layers)), {obj.layers.name}, 2) ; % determine the execution order again (and check for consistency) obj.executionOrder = getOrder(obj) ; % -------------------------------------------------------------------- function order = getOrder(obj) % -------------------------------------------------------------------- hops = cell(1, numel(obj.vars)) ; for l = 1:numel(obj.layers) for v = obj.layers(l).inputIndexes hops{v}(end+1) = l ; end end order = zeros(1, numel(obj.layers)) ; for l = 1:numel(obj.layers) if order(l) == 0 order = dagSort(obj, hops, order, l) ; end end if any(order == -1) warning('The network graph contains a cycle') ; end [~,order] = sort(order, 'descend') ; % -------------------------------------------------------------------- function order = dagSort(obj, hops, order, layer) % -------------------------------------------------------------------- if order(layer) > 0, return ; end order(layer) = -1 ; % mark as open n = 0 ; for o = obj.layers(layer).outputIndexes ; for child = hops{o} if order(child) == -1 return ; end if order(child) == 0 order = dagSort(obj, hops, order, child) ; end n = max(n, order(child)) ; end end order(layer) = n + 1 ; function varargout = tolist(x) [varargout{1:numel(x)}] = x{:} ;
github
cssjcai/hihca-master
print.m
.m
hihca-master/codes/matconvnet/matlab/+dagnn/@DagNN/print.m
13,352
utf_8
074f69a09b01cfea5703e435b2bfc22d
function str = print(obj, inputSizes, varargin) %PRINT Print information about the DagNN object % PRINT(OBJ) displays a summary of the functions and parameters in the network. % STR = PRINT(OBJ) returns the summary as a string instead of printing it. % % PRINT(OBJ, INPUTSIZES) where INPUTSIZES is a cell array of the type % {'input1nam', input1size, 'input2name', input2size, ...} prints % information using the specified size for each of the listed inputs. % % PRINT(___, 'OPT', VAL, ...) accepts the following options: % % `All`:: false % Display all the information below. % % `Layers`:: '*' % Specify which layers to print. This can be either a list of % indexes, a cell array of array names, or the string '*', meaning % all layers. % % `Parameters`:: '*' % Specify which parameters to print, similar to the option above. % % `Variables`:: [] % Specify which variables to print, similar to the option above. % % `Dependencies`:: false % Whether to display the dependency (geometric transformation) % of each variables from each input. % % `Format`:: 'ascii' % Choose between `ascii`, `latex`, `csv`, 'digraph', and `dot`. % The first three format print tables; `digraph` uses the plot function % for a `digraph` (supported in MATLAB>=R2015b) and the last one % prints a graph in `dot` format. In case of zero outputs, it % attmepts to compile and visualise the dot graph using `dot` command % and `display` (Linux) or `open` (Mac OSX) on your system. % In the latter case, all variables and layers are included in the % graph, regardless of the other parameters. % % `MaxNumColumns`:: 18 % Maximum number of columns in each table. % % See also: DAGNN, DAGNN.GETVARSIZES(). if nargin > 1 && isstr(inputSizes) % called directly with options, skipping second argument varargin = {inputSizes, varargin{:}} ; inputSizes = {} ; end opts.all = false ; opts.format = 'ascii' ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.layers = '*' ; opts.parameters = [] ; opts.variables = [] ; if opts.all || nargin > 1 opts.variables = '*' ; end if opts.all opts.parameters = '*' ; end opts.memory = true ; opts.dependencies = opts.all ; opts.maxNumColumns = 18 ; opts = vl_argparse(opts, varargin) ; if nargin == 1, inputSizes = {} ; end varSizes = obj.getVarSizes(inputSizes) ; paramSizes = cellfun(@size, {obj.params.value}, 'UniformOutput', false) ; str = {''} ; if strcmpi(opts.format,'dot') str = printDot(obj, varSizes, paramSizes, opts) ; if nargout == 0 displayDot(str) ; end return ; end if strcmpi(opts.format,'digraph') str = printdigraph(obj, varSizes) ; return ; end if ~isempty(opts.layers) table = {'func', '-', 'type', 'inputs', 'outputs', 'params', 'pad', 'stride'} ; for l = select(obj, 'layers', opts.layers) layer = obj.layers(l) ; table{l+1,1} = layer.name ; table{l+1,2} = '-' ; table{l+1,3} = player(class(layer.block)) ; table{l+1,4} = strtrim(sprintf('%s ', layer.inputs{:})) ; table{l+1,5} = strtrim(sprintf('%s ', layer.outputs{:})) ; table{l+1,6} = strtrim(sprintf('%s ', layer.params{:})) ; if isprop(layer.block, 'pad') table{l+1,7} = pdims(layer.block.pad) ; else table{l+1,7} = 'n/a' ; end if isprop(layer.block, 'stride') table{l+1,8} = pdims(layer.block.stride) ; else table{l+1,8} = 'n/a' ; end end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if ~isempty(opts.parameters) table = {'param', '-', 'dims', 'mem', 'fanout'} ; for v = select(obj, 'params', opts.parameters) table{v+1,1} = obj.params(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(paramSizes{v}) ; table{v+1,4} = pmem(prod(paramSizes{v}) * 4) ; table{v+1,5} = sprintf('%d',obj.params(v).fanout) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if ~isempty(opts.variables) table = {'var', '-', 'dims', 'mem', 'fanin', 'fanout'} ; for v = select(obj, 'vars', opts.variables) table{v+1,1} = obj.vars(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(varSizes{v}) ; table{v+1,4} = pmem(prod(varSizes{v}) * 4) ; table{v+1,5} = sprintf('%d',obj.vars(v).fanin) ; table{v+1,6} = sprintf('%d',obj.vars(v).fanout) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if opts.memory paramMem = sum(cellfun(@getMem, paramSizes)) ; varMem = sum(cellfun(@getMem, varSizes)) ; table = {'params', 'vars', 'total'} ; table{2,1} = pmem(paramMem) ; table{2,2} = pmem(varMem) ; table{2,3} = pmem(paramMem + varMem) ; str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if opts.dependencies % print variable to input dependencies inputs = obj.getInputs() ; rfs = obj.getVarReceptiveFields(inputs) ; for i = 1:size(rfs,1) table = {sprintf('rf in ''%s''', inputs{i}), '-', 'size', 'stride', 'offset'} ; for v = 1:size(rfs,2) table{v+1,1} = obj.vars(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(rfs(i,v).size) ; table{v+1,4} = pdims(rfs(i,v).stride) ; table{v+1,5} = pdims(rfs(i,v).offset) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end end % finish str = horzcat(str{:}) ; if nargout == 0, fprintf('%s',str) ; clear str ; end end % ------------------------------------------------------------------------- function str = printtable(opts, table) % ------------------------------------------------------------------------- str = {''} ; for i=2:opts.maxNumColumns:size(table,2) sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ; str{end+1} = printtablechunk(opts, table(:, [1 sel])) ; str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; end % ------------------------------------------------------------------------- function str = printtablechunk(opts, table) % ------------------------------------------------------------------------- str = {''} ; switch opts.format case 'ascii' sizes = max(cellfun(@(x) numel(x), table),[],1) ; for i=1:size(table,1) for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds|', sizes(j)) ; if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end str{end+1} = sprintf(fmt, s) ; end str{end+1} = sprintf('\n') ; end case 'latex' sizes = max(cellfun(@(x) numel(x), table),[],1) ; str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ; for i=1:size(table,1) if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds', sizes(j)) ; str{end+1} = sprintf(fmt, latexesc(s)) ; if j<size(table,2), str{end+1} = sprintf('&') ; end end str{end+1} = sprintf('\\\\\n') ; end str{end+1}= sprintf('\\end{tabular}\n') ; case 'csv' sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ; for i=1:size(table,1) if isequal(table{i,1},'-'), continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds,', sizes(j)) ; str{end+1} = sprintf(fmt, ['"' s '"']) ; end str{end+1} = sprintf('\n') ; end otherwise error('Uknown format %s', opts.format) ; end str = horzcat(str{:}) ; end % ------------------------------------------------------------------------- function s = latexesc(s) % ------------------------------------------------------------------------- s = strrep(s,'\','\\') ; s = strrep(s,'_','\char`_') ; end % ------------------------------------------------------------------------- function s = pmem(x) % ------------------------------------------------------------------------- if isnan(x), s = 'NaN' ; elseif x < 1024^1, s = sprintf('%.0fB', x) ; elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ; elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ; else s = sprintf('%.0fGB', x / 1024^3) ; end end % ------------------------------------------------------------------------- function s = pdims(x) % ------------------------------------------------------------------------- if all(isnan(x)) s = 'n/a' ; return ; end if all(x==x(1)) s = sprintf('%.4g', x(1)) ; else s = sprintf('%.4gx', x(:)) ; s(end) = [] ; end end % ------------------------------------------------------------------------- function x = player(x) % ------------------------------------------------------------------------- if numel(x) < 7, return ; end if x(1:6) == 'dagnn.', x = x(7:end) ; end end % ------------------------------------------------------------------------- function m = getMem(sz) % ------------------------------------------------------------------------- m = prod(sz) * 4 ; if isnan(m), m = 0 ; end end % ------------------------------------------------------------------------- function sel = select(obj, type, pattern) % ------------------------------------------------------------------------- if isnumeric(pattern) sel = pattern ; else if isstr(pattern) if strcmp(pattern, '*') sel = 1:numel(obj.(type)) ; return ; else pattern = {pattern} ; end end sel = find(cellfun(@(x) any(strcmp(x, pattern)), {obj.(type).name})) ; end end % ------------------------------------------------------------------------- function h = printdigraph(net, varSizes) % ------------------------------------------------------------------------- if exist('digraph') ~= 2 error('MATLAB graph support not present.'); end s = []; t = []; w = []; varsNames = {net.vars.name}; layerNames = {net.layers.name}; numVars = numel(varsNames); spatSize = cellfun(@(vs) vs(1), varSizes); spatSize(isnan(spatSize)) = 1; varChannels = cellfun(@(vs) vs(3), varSizes); varChannels(isnan(varChannels)) = 0; for li = 1:numel(layerNames) l = net.layers(li); lidx = numVars + li; s = [s l.inputIndexes]; t = [t lidx*ones(1, numel(l.inputIndexes))]; w = [w spatSize(l.inputIndexes)]; s = [s lidx*ones(1, numel(l.outputIndexes))]; t = [t l.outputIndexes]; w = [w spatSize(l.outputIndexes)]; end nodeNames = [varsNames, layerNames]; g = digraph(s, t, w); lw = 5*g.Edges.Weight/max([g.Edges.Weight; 5]); h = plot(g, 'NodeLabel', nodeNames, 'LineWidth', lw); highlight(h, numVars+1:numVars+numel(layerNames), 'MarkerSize', 8, 'Marker', 's'); highlight(h, 1:numVars, 'MarkerSize', 5, 'Marker', 's'); cmap = copper; varNvalRel = varChannels./max(varChannels); for vi = 1:numel(varChannels) highlight(h, vi, 'NodeColor', cmap(max(round(varNvalRel(vi)*64), 1),:)); end axis off; layout(h, 'force'); end % ------------------------------------------------------------------------- function str = printDot(net, varSizes, paramSizes, otps) % ------------------------------------------------------------------------- str = {} ; str{end+1} = sprintf('digraph DagNN {\n\tfontsize=12\n') ; font_style = 'fontsize=12 fontname="helvetica"'; for v = 1:numel(net.vars) label=sprintf('{{%s} | {%s | %s }}', net.vars(v).name, pdims(varSizes{v}), pmem(4*prod(varSizes{v}))) ; str{end+1} = sprintf('\tvar_%s [label="%s" shape=record style="solid,rounded,filled" color=cornsilk4 fillcolor=beige %s ]\n', ... net.vars(v).name, label, font_style) ; end for p = 1:numel(net.params) label=sprintf('{{%s} | {%s | %s }}', net.params(p).name, pdims(paramSizes{p}), pmem(4*prod(paramSizes{p}))) ; str{end+1} = sprintf('\tpar_%s [label="%s" shape=record style="solid,rounded,filled" color=lightsteelblue4 fillcolor=lightsteelblue %s ]\n', ... net.params(p).name, label, font_style) ; end for l = 1:numel(net.layers) label = sprintf('{ %s | %s }', net.layers(l).name, class(net.layers(l).block)) ; str{end+1} = sprintf('\t%s [label="%s" shape=record style="bold,filled" color="tomato4" fillcolor="tomato" %s ]\n', ... net.layers(l).name, label, font_style) ; for i = 1:numel(net.layers(l).inputs) str{end+1} = sprintf('\tvar_%s->%s [weight=10]\n', ... net.layers(l).inputs{i}, ... net.layers(l).name) ; end for o = 1:numel(net.layers(l).outputs) str{end+1} = sprintf('\t%s->var_%s [weight=10]\n', ... net.layers(l).name, ... net.layers(l).outputs{o}) ; end for p = 1:numel(net.layers(l).params) str{end+1} = sprintf('\tpar_%s->%s [weight=1]\n', ... net.layers(l).params{p}, ... net.layers(l).name) ; end end str{end+1} = sprintf('}\n') ; str = cat(2,str{:}) ; end % ------------------------------------------------------------------------- function displayDot(str) % ------------------------------------------------------------------------- %mwdot = fullfile(matlabroot, 'bin', computer('arch'), 'mwdot') ; dotexe = 'dot' ; in=[tempname '.dot']; out=[tempname '.pdf']; f = fopen(in,'w') ; fwrite(f, str) ; fclose(f) ; cmd = sprintf('"%s" -Tpdf -o "%s" "%s"', dotexe, out, in) ; [status, result] = system(cmd) ; if status ~= 0 error('Unable to run %s\n%s', cmd, result); end fprintf('Dot output:\n%s\n', result); %f = fopen(out,'r') ; file=fread(f, 'char=>char')' ; fclose(f) ; switch computer case 'MACI64' system(sprintf('open "%s"', out)) ; case 'GLNXA64' system(sprintf('display "%s"', out)) ; otherwise fprintf('PDF figure saved at "%s"\n', out) ; end end
github
cssjcai/hihca-master
fromSimpleNN.m
.m
hihca-master/codes/matconvnet/matlab/+dagnn/@DagNN/fromSimpleNN.m
7,120
utf_8
38d26e77f162ec60724dc4cb765e3a99
function obj = fromSimpleNN(net, varargin) % FROMSIMPLENN Initialize a DagNN object from a SimpleNN network % FROMSIMPLENN(NET) initializes the DagNN object from the % specified CNN using the SimpleNN format. % % SimpleNN objects are linear chains of computational layers. These % layers exchange information through variables and parameters that % are not explicitly named. Hence, FROMSIMPLENN() uses a number of % rules to assign such names automatically: % % * From the input to the output of the CNN, variables are called % `x0` (input of the first layer), `x1`, `x2`, .... In this % manner `xi` is the output of the i-th layer. % % * Any loss layer requires two inputs, the second being a label. % These are called `label` (for the first such layers), and then % `label2`, `label3`,... for any other similar layer. % % Additionally, given the option `CanonicalNames` the function can % change the names of some variables to make them more convenient to % use. With this option turned on: % % * The network input is called `input` instead of `x0`. % % * The output of each SoftMax layer is called `prob` (or `prob2`, % ...). % % * The output of each Loss layer is called `objective` (or ` % objective2`, ...). % % * The input of each SoftMax or Loss layer of type *softmax log % loss* is called `prediction` (or `prediction2`, ...). If a Loss % layer immediately follows a SoftMax layer, then the rule above % takes precendence and the input name is not changed. % % FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options: % % `CanonicalNames`:: false % If `true` use the rules above to assign more meaningful % names to some of the variables. % Copyright (C) 2015 Karel Lenc and Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.canonicalNames = false ; opts = vl_argparse(opts, varargin) ; import dagnn.* obj = DagNN() ; net = vl_simplenn_move(net, 'cpu') ; net = vl_simplenn_tidy(net) ; % copy meta-information as is obj.meta = net.meta ; for l = 1:numel(net.layers) inputs = {sprintf('x%d',l-1)} ; outputs = {sprintf('x%d',l)} ; params = struct(... 'name', {}, ... 'value', {}, ... 'learningRate', [], ... 'weightDecay', []) ; if isfield(net.layers{l}, 'name') name = net.layers{l}.name ; else name = sprintf('layer%d',l) ; end switch net.layers{l}.type case {'conv', 'convt'} sz = size(net.layers{l}.weights{1}) ; hasBias = ~isempty(net.layers{l}.weights{2}) ; params(1).name = sprintf('%sf',name) ; params(1).value = net.layers{l}.weights{1} ; if hasBias params(2).name = sprintf('%sb',name) ; params(2).value = net.layers{l}.weights{2} ; end if isfield(net.layers{l},'learningRate') params(1).learningRate = net.layers{l}.learningRate(1) ; if hasBias params(2).learningRate = net.layers{l}.learningRate(2) ; end end if isfield(net.layers{l},'weightDecay') params(1).weightDecay = net.layers{l}.weightDecay(1) ; if hasBias params(2).weightDecay = net.layers{l}.weightDecay(2) ; end end switch net.layers{l}.type case 'conv' block = Conv() ; block.size = sz ; block.pad = net.layers{l}.pad ; block.stride = net.layers{l}.stride ; case 'convt' block = ConvTranspose() ; block.size = sz ; block.upsample = net.layers{l}.upsample ; block.crop = net.layers{l}.crop ; block.numGroups = net.layers{l}.numGroups ; end block.hasBias = hasBias ; block.opts = net.layers{l}.opts ; case 'pool' block = Pooling() ; block.method = net.layers{l}.method ; block.poolSize = net.layers{l}.pool ; block.pad = net.layers{l}.pad ; block.stride = net.layers{l}.stride ; block.opts = net.layers{l}.opts ; case {'normalize', 'lrn'} block = LRN() ; block.param = net.layers{l}.param ; case {'dropout'} block = DropOut() ; block.rate = net.layers{l}.rate ; case {'relu'} block = ReLU() ; block.leak = net.layers{l}.leak ; case {'sigmoid'} block = Sigmoid() ; case {'softmax'} block = SoftMax() ; case {'softmaxloss'} block = Loss('loss', 'softmaxlog') ; % The loss has two inputs inputs{2} = getNewVarName(obj, 'label') ; case {'bnorm'} block = BatchNorm() ; params(1).name = sprintf('%sm',name) ; params(1).value = net.layers{l}.weights{1} ; params(2).name = sprintf('%sb',name) ; params(2).value = net.layers{l}.weights{2} ; params(3).name = sprintf('%sx',name) ; params(3).value = net.layers{l}.weights{3} ; if isfield(net.layers{l},'learningRate') params(1).learningRate = net.layers{l}.learningRate(1) ; params(2).learningRate = net.layers{l}.learningRate(2) ; params(3).learningRate = net.layers{l}.learningRate(3) ; end if isfield(net.layers{l},'weightDecay') params(1).weightDecay = net.layers{l}.weightDecay(1) ; params(2).weightDecay = net.layers{l}.weightDecay(2) ; params(3).weightDecay = 0 ; end otherwise error([net.layers{l}.type ' is unsupported']) ; end obj.addLayer(... name, ... block, ... inputs, ... outputs, ... {params.name}) ; for p = 1:numel(params) pindex = obj.getParamIndex(params(p).name) ; if ~isempty(params(p).value) obj.params(pindex).value = params(p).value ; end if ~isempty(params(p).learningRate) obj.params(pindex).learningRate = params(p).learningRate ; end if ~isempty(params(p).weightDecay) obj.params(pindex).weightDecay = params(p).weightDecay ; end end end % -------------------------------------------------------------------- % Rename variables to canonical names % -------------------------------------------------------------------- if opts.canonicalNames for l = 1:numel(obj.layers) if l == 1 obj.renameVar(obj.layers(l).inputs{1}, 'input') ; end if isa(obj.layers(l).block, 'dagnn.SoftMax') obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ; obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ; end if isa(obj.layers(l).block, 'dagnn.Loss') obj.renameVar(obj.layers(l).outputs{1}, 'objective') ; if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*')) obj.renameVar(obj.layers(l).inputs{1}, ... getNewVarName(obj, 'prediction')) ; end end end end % -------------------------------------------------------------------- function name = getNewVarName(obj, prefix) % -------------------------------------------------------------------- t = 0 ; name = prefix ; while any(strcmp(name, {obj.vars.name})) t = t + 1 ; name = sprintf('%s%d', prefix, t) ; end
github
cssjcai/hihca-master
vl_simplenn_display.m
.m
hihca-master/codes/matconvnet/matlab/simplenn/vl_simplenn_display.m
12,389
utf_8
bd99c027519a637b853c5a096f1a79b1
function [info, str] = vl_simplenn_display(net, varargin) %VL_SIMPLENN_DISPLAY Display the structure of a SimpleNN network. % VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET. % % INFO = VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO % with several statistics for each layer of the network NET. % % [INFO, STR] = VL_SIMPLENN_DISPLAY(...) returns also a string STR % with the text that would otherwise be printed. % % The function accepts the following options: % % `inputSize`:: auto % Specifies the size of the input tensor X that will be passed to % the network as input. This information is used in order to % estiamte the memory required to process the network. When this % option is not used, VL_SIMPLENN_DISPLAY() tires to use values % in the NET structure to guess the input size: % NET.META.INPUTSIZE and NET.META.NORMALIZATION.IMAGESIZE % (assuming a batch size of one image, unless otherwise specified % by the `batchSize` option). % % `batchSize`:: [] % Specifies the number of data points in a batch in estimating % the memory consumption, overriding the last dimension of % `inputSize`. % % `maxNumColumns`:: 18 % Maximum number of columns in a table. Wider tables are broken % into multiple smaller ones. % % `format`:: `'ascii'` % One of `'ascii'`, `'latex'`, or `'csv'`. % % See also: VL_SIMPLENN(). % Copyright (C) 2014-15 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.inputSize = [] ; opts.batchSize = [] ; opts.maxNumColumns = 18 ; opts.format = 'ascii' ; opts = vl_argparse(opts, varargin) ; % determine input size, using first the option, then net.meta.inputSize, % and eventually net.meta.normalization.imageSize, if any if isempty(opts.inputSize) tmp = [] ; opts.inputSize = [NaN;NaN;NaN;1] ; if isfield(net, 'meta') if isfield(net.meta, 'inputSize') tmp = net.meta.inputSize(:) ; elseif isfield(net.meta, 'normalization') && ... isfield(net.meta.normalization, 'imageSize') tmp = net.meta.normalization.imageSize ; end opts.inputSize(1:numel(tmp)) = tmp(:) ; end end if ~isempty(opts.batchSize) opts.inputSize(4) = opts.batchSize ; end fields={'layer', 'type', 'name', '-', ... 'support', 'filtd', 'nfilt', 'stride', 'pad', '-', ... 'rfsize', 'rfoffset', 'rfstride', '-', ... 'dsize', 'ddepth', 'dnum', '-', ... 'xmem', 'wmem'}; % get the support, stride, and padding of the operators for l = 1:numel(net.layers) ly = net.layers{l} ; switch ly.type case 'conv' if isfield(ly, 'weights') info.support(1:2,l) = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ; else info.support(1:2,l) = max([size(ly.filters,1) ; size(ly.filters,2)],1) ; end case 'pool' info.support(1:2,l) = ly.pool(:) ; otherwise info.support(1:2,l) = [1;1] ; end if isfield(ly, 'stride') info.stride(1:2,l) = ly.stride(:) ; else info.stride(1:2,l) = 1 ; end if isfield(ly, 'pad') info.pad(1:4,l) = ly.pad(:) ; else info.pad(1:4,l) = 0 ; end % operator applied to the input image info.receptiveFieldSize(1:2,l) = 1 + ... sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ... (info.support(1:2,1:l)-1),2) ; info.receptiveFieldOffset(1:2,l) = 1 + ... sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ... ((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ; info.receptiveFieldStride = cumprod(info.stride,2) ; end % get the dimensions of the data info.dataSize(1:4,1) = opts.inputSize(:) ; for l = 1:numel(net.layers) ly = net.layers{l} ; if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize') sz = ly.getForwardSize(ly, info.dataSize(:,l)) ; info.dataSize(:,l+1) = sz(:) ; continue ; end info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ... sum(info.pad(1:2,l)) - ... info.support(1,l)) / info.stride(1,l)) + 1 ; info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ... sum(info.pad(3:4,l)) - ... info.support(2,l)) / info.stride(2,l)) + 1 ; info.dataSize(3, l+1) = info.dataSize(3,l) ; info.dataSize(4, l+1) = info.dataSize(4,l) ; switch ly.type case 'conv' if isfield(ly, 'weights') f = ly.weights{1} ; else f = ly.filters ; end if size(f, 3) ~= 0 info.dataSize(3, l+1) = size(f,4) ; end case {'loss', 'softmaxloss'} info.dataSize(3:4, l+1) = 1 ; case 'custom' info.dataSize(3,l+1) = NaN ; end end if nargout == 1, return ; end % print table table = {} ; wmem = 0 ; xmem = 0 ; for wi=1:numel(fields) w = fields{wi} ; switch w case 'type', s = 'type' ; case 'stride', s = 'stride' ; case 'rfsize', s = 'rf size' ; case 'rfstride', s = 'rf stride' ; case 'rfoffset', s = 'rf offset' ; case 'dsize', s = 'data size' ; case 'ddepth', s = 'data depth' ; case 'dnum', s = 'data num' ; case 'nfilt', s = 'num filts' ; case 'filtd', s = 'filt dim' ; case 'wmem', s = 'param mem' ; case 'xmem', s = 'data mem' ; otherwise, s = char(w) ; end table{wi,1} = s ; % do input pseudo-layer for l=0:numel(net.layers) switch char(w) case '-', s='-' ; case 'layer', s=sprintf('%d', l) ; case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ; case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ; case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ; case 'xmem' a = prod(info.dataSize(:,l+1)) * 4 ; s = pmem(a) ; xmem = xmem + a ; otherwise if l == 0 if strcmp(char(w),'type'), s = 'input'; else s = 'n/a' ; end else ly=net.layers{l} ; switch char(w) case 'name' if isfield(ly, 'name') s=ly.name ; else s='' ; end case 'type' switch ly.type case 'normalize', s='norm'; case 'pool' if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end case 'softmax', s='softmx' ; case 'softmaxloss', s='softmxl' ; otherwise s=ly.type ; end case 'nfilt' switch ly.type case 'conv' if isfield(ly, 'weights'), a = size(ly.weights{1},4) ; else, a = size(ly.filters,4) ; end s=sprintf('%d',a) ; otherwise s='n/a' ; end case 'filtd' switch ly.type case 'conv' if isfield(ly, 'weights'), a = size(ly.weights{1},3) ; else, a = size(ly.filters,3) ; end s=sprintf('%d',a) ; otherwise s='n/a' ; end case 'support' s = pdims(info.support(:,l)) ; case 'stride' s = pdims(info.stride(:,l)) ; case 'pad' s = pdims(info.pad(:,l)) ; case 'rfsize' s = pdims(info.receptiveFieldSize(:,l)) ; case 'rfoffset' s = pdims(info.receptiveFieldOffset(:,l)) ; case 'rfstride' s = pdims(info.receptiveFieldStride(:,l)) ; case 'wmem' a = 0 ; if isfield(ly, 'weights') ; for j=1:numel(ly.weights) a = a + numel(ly.weights{j}) * 4 ; end end % Legacy code to be removed if isfield(ly, 'filters') ; a = a + numel(ly.filters) * 4 ; end if isfield(ly, 'biases') ; a = a + numel(ly.biases) * 4 ; end s = pmem(a) ; wmem = wmem + a ; end end end table{wi,l+2} = s ; end end str = {} ; for i=2:opts.maxNumColumns:size(table,2) sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ; str{end+1} = ptable(opts, table(:,[1 sel])) ; end table = {... 'parameter memory', sprintf('%s (%.2g parameters)', pmem(wmem), wmem/4); 'data memory', sprintf('%s (for batch size %d)', pmem(xmem), info.dataSize(4,1))} ; str{end+1} = ptable(opts, table) ; str = horzcat(str{:}) ; if nargout == 0 fprintf('%s', str) ; clear info str ; end % ------------------------------------------------------------------------- function str = ptable(opts, table) % ------------------------------------------------------------------------- switch opts.format case 'ascii', str = pascii(table) ; case 'latex', str = platex(table) ; case 'csv', str = pcsv(table) ; end str = horzcat(str,sprintf('\n')) ; % ------------------------------------------------------------------------- function s = pmem(x) % ------------------------------------------------------------------------- if isnan(x), s = 'NaN' ; elseif x < 1024^1, s = sprintf('%.0fB', x) ; elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ; elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ; else s = sprintf('%.0fGB', x / 1024^3) ; end % ------------------------------------------------------------------------- function s = pdims(x) % ------------------------------------------------------------------------- if all(x==x(1)) s = sprintf('%.4g', x(1)) ; else s = sprintf('%.4gx', x(:)) ; s(end) = [] ; end % ------------------------------------------------------------------------- function str = pascii(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) ; for i=1:size(table,1) for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds|', sizes(j)) ; if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end str{end+1} = sprintf(fmt, s) ; end str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function str = pcsv(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ; for i=1:size(table,1) if isequal(table{i,1},'-'), continue ; end for j=1:size(table,2) s = table{i,j} ; str{end+1} = sprintf('%s,', ['"' s '"']) ; end str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function str = platex(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) ; str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ; for i=1:size(table,1) if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds', sizes(j)) ; str{end+1} = sprintf(fmt, latexesc(s)) ; if j<size(table,2), str{end+1} = sprintf('&') ; end end str{end+1} = sprintf('\\\\\n') ; end str{end+1} = sprintf('\\end{tabular}\n') ; str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function s = latexesc(s) % ------------------------------------------------------------------------- s = strrep(s,'\','\\') ; s = strrep(s,'_','\char`_') ; % ------------------------------------------------------------------------- function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem) % ------------------------------------------------------------------------- if nargin <= 1 cpuMem = 0 ; gpuMem = 0 ; end if isstruct(s) for f=fieldnames(s)' f = char(f) ; for i=1:numel(s) [cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ; end end elseif iscell(s) for i=1:numel(s) [cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ; end elseif isnumeric(s) if isa(s, 'single') mult = 4 ; else mult = 8 ; end if isa(s,'gpuArray') gpuMem = gpuMem + mult * numel(s) ; else cpuMem = cpuMem + mult * numel(s) ; end end
github
cssjcai/hihca-master
vl_test_economic_relu.m
.m
hihca-master/codes/matconvnet/matlab/xtest/vl_test_economic_relu.m
790
utf_8
35a3dbe98b9a2f080ee5f911630ab6f3
% VL_TEST_ECONOMIC_RELU function vl_test_economic_relu() x = randn(11,12,8,'single'); w = randn(5,6,8,9,'single'); b = randn(1,9,'single') ; net.layers{1} = struct('type', 'conv', ... 'filters', w, ... 'biases', b, ... 'stride', 1, ... 'pad', 0); net.layers{2} = struct('type', 'relu') ; res = vl_simplenn(net, x) ; dzdy = randn(size(res(end).x), 'like', res(end).x) ; clear res ; res_ = vl_simplenn(net, x, dzdy) ; res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ; a=whos('res_') ; b=whos('res__') ; assert(a.bytes > b.bytes) ; vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ; vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ; vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
github
NRottmann/Toolbox-GP-GMRF-master
setargs.m
.m
Toolbox-GP-GMRF-master/subfunctions/setargs.m
4,118
utf_8
797de70bb444b013b0844b47d6bda423
function argstruct = setargs(defaultargs, varargs) % SETARGS Name/value parsing and assignment of varargin with default values % % This is a utility for setting the value of optional arguments to a % function. The first argument is required and should be a cell array of % "name, default value" pairs for all optional arguments. The second % argument is optional and should be a cell array of "name, custom value" % pairs for at least one of the optional arguments. % % USAGE: argstruct = setargs(defaultargs, varargs) % __________________________________________________________________________ % OUTPUT % % ARGSTRUCT % structure containing the final argument values % __________________________________________________________________________ % INPUTS % % DEFAULTARGS % cell array of "'Name', value" pairs for all variables with default % values % % VARARGS [optional] % cell array of user-specified "'Name', value" pairs for one or more of % the variables with default values. this will typically be the % "varargin" cell array. for each pair, SETARGS determines if the % specified variable name can be uniquely matched to one of the default % variable names specified in DEFAULTARGS. matching uses STRNCMPI and % thus is case-insensitive and open to partial name matches (e.g., % default variable name 'FontWeight' would be matched by 'fontweight', % 'Fontw', etc.). if a match is found, the user-specified value is then % used in place of the default value. if no match is found or if % multiple matches are found, SETARGS returns an error and displays in % the command window information about the argument that caused the % problem. % __________________________________________________________________________ % USAGE EXAMPLE (TO BE USED AT TOP OF FUNCTION WITH VARARGIN) % % defaultargs = {'arg1', 0, 'arg2', 'words', 'arg3', rand}; % argstruct = setargs(defaultargs, varargin) % % ---------------------- Copyright (C) 2015 Bob Spunt ----------------------- % Created: 2015-03-11 % Email: [email protected] % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or (at % your option) any later version. % This program is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % You should have received a copy of the GNU General Public License % along with this program. If not, see: http://www.gnu.org/licenses/. % if nargin < 1, mfile_showhelp; return; end if nargin < 2, varargs = []; end defaultargs = reshape(defaultargs, 2, length(defaultargs)/2)'; if ~isempty(varargs) if mod(length(varargs), 2) error('Optional inputs must be entered as "''Name'', Value" pairs, e.g., myfunction(''arg1'', val1, ''arg2'', val2)'); end arg = reshape(varargs, 2, length(varargs)/2)'; for i = 1:size(arg,1) idx = strncmpi(defaultargs(:,1), arg{i,1}, length(arg{i,1})); if sum(idx) > 1 error(['Input "%s" matches multiple valid inputs:' repmat(' %s', 1, sum(idx))], arg{i,1}, defaultargs{idx, 1}); elseif ~any(idx) error('Input "%s" does not match a valid input.', arg{i,1}); else defaultargs{idx,2} = arg{i,2}; end end end for i = 1:size(defaultargs,1), assignin('caller', defaultargs{i,1}, defaultargs{i,2}); end if nargout>0, argstruct = cell2struct(defaultargs(:,2), defaultargs(:,1)); end end % ========================================================================= % * SUBFUNCTIONS % ========================================================================= function mfile_showhelp(varargin) % MFILE_SHOWHELP ST = dbstack('-completenames'); if isempty(ST), fprintf('\nYou must call this within a function\n\n'); return; end eval(sprintf('help %s', ST(2).file)); end
github
NRottmann/Toolbox-GP-GMRF-master
gridfit.m
.m
Toolbox-GP-GMRF-master/others/gridfit.m
34,995
utf_8
e58c0dba921cb156ee39a27dd18a4d1c
function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin) % gridfit: estimates a surface on a 2d grid, based on scattered data % Replicates are allowed. All methods extrapolate to the grid % boundaries. Gridfit uses a modified ridge estimator to % generate the surface, where the bias is toward smoothness. % % Gridfit is not an interpolant. Its goal is a smooth surface % that approximates your data, but allows you to control the % amount of smoothing. % % usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes); % usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes); % usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...); % % Arguments: (input) % x,y,z - vectors of equal lengths, containing arbitrary scattered data % The only constraint on x and y is they cannot ALL fall on a % single line in the x-y plane. Replicate points will be treated % in a least squares sense. % % ANY points containing a NaN are ignored in the estimation % % xnodes - vector defining the nodes in the grid in the independent % variable (x). xnodes need not be equally spaced. xnodes % must completely span the data. If they do not, then the % 'extend' property is applied, adjusting the first and last % nodes to be extended as necessary. See below for a complete % description of the 'extend' property. % % If xnodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % ynodes - vector defining the nodes in the grid in the independent % variable (y). ynodes need not be equally spaced. % % If ynodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % Also see the extend property. % % Additional arguments follow in the form of property/value pairs. % Valid properties are: % 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter' % 'extend', 'tilesize', 'overlap' % % Any UNAMBIGUOUS shortening (even down to a single letter) is % valid for property names. All properties have default values, % chosen (I hope) to give a reasonable result out of the box. % % 'smoothness' - scalar or vector of length 2 - determines the % eventual smoothness of the estimated surface. A larger % value here means the surface will be smoother. Smoothness % must be a non-negative real number. % % If this parameter is a vector of length 2, then it defines % the relative smoothing to be associated with the x and y % variables. This allows the user to apply a different amount % of smoothing in the x dimension compared to the y dimension. % % Note: the problem is normalized in advance so that a % smoothness of 1 MAY generate reasonable results. If you % find the result is too smooth, then use a smaller value % for this parameter. Likewise, bumpy surfaces suggest use % of a larger value. (Sometimes, use of an iterative solver % with too small a limit on the maximum number of iterations % will result in non-convergence.) % % DEFAULT: 1 % % % 'interp' - character, denotes the interpolation scheme used % to interpolate the data. % % DEFAULT: 'triangle' % % 'bilinear' - use bilinear interpolation within the grid % (also known as tensor product linear interpolation) % % 'triangle' - split each cell in the grid into a triangle, % then linear interpolation inside each triangle % % 'nearest' - nearest neighbor interpolation. This will % rarely be a good choice, but I included it % as an option for completeness. % % % 'regularizer' - character flag, denotes the regularization % paradignm to be used. There are currently three options. % % DEFAULT: 'gradient' % % 'diffusion' or 'laplacian' - uses a finite difference % approximation to the Laplacian operator (i.e, del^2). % % We can think of the surface as a plate, wherein the % bending rigidity of the plate is specified by the user % as a number relative to the importance of fidelity to % the data. A stiffer plate will result in a smoother % surface overall, but fit the data less well. I've % modeled a simple plate using the Laplacian, del^2. (A % projected enhancement is to do a better job with the % plate equations.) % % We can also view the regularizer as a diffusion problem, % where the relative thermal conductivity is supplied. % Here interpolation is seen as a problem of finding the % steady temperature profile in an object, given a set of % points held at a fixed temperature. Extrapolation will % be linear. Both paradigms are appropriate for a Laplacian % regularizer. % % 'gradient' - attempts to ensure the gradient is as smooth % as possible everywhere. Its subtly different from the % 'diffusion' option, in that here the directional % derivatives are biased to be smooth across cell % boundaries in the grid. % % The gradient option uncouples the terms in the Laplacian. % Think of it as two coupled PDEs instead of one PDE. Why % are they different at all? The terms in the Laplacian % can balance each other. % % 'springs' - uses a spring model connecting nodes to each % other, as well as connecting data points to the nodes % in the grid. This choice will cause any extrapolation % to be as constant as possible. % % Here the smoothing parameter is the relative stiffness % of the springs connecting the nodes to each other compared % to the stiffness of a spting connecting the lattice to % each data point. Since all springs have a rest length % (length at which the spring has zero potential energy) % of zero, any extrapolation will be minimized. % % Note: The 'springs' regularizer tends to drag the surface % towards the mean of all the data, so too large a smoothing % parameter may be a problem. % % % 'solver' - character flag - denotes the solver used for the % resulting linear system. Different solvers will have % different solution times depending upon the specific % problem to be solved. Up to a certain size grid, the % direct \ solver will often be speedy, until memory % swaps causes problems. % % What solver should you use? Problems with a significant % amount of extrapolation should avoid lsqr. \ may be % best numerically for small smoothnesss parameters and % high extents of extrapolation. % % Large numbers of points will slow down the direct % \, but when applied to the normal equations, \ can be % quite fast. Since the equations generated by these % methods will tend to be well conditioned, the normal % equations are not a bad choice of method to use. Beware % when a small smoothing parameter is used, since this will % make the equations less well conditioned. % % DEFAULT: 'normal' % % '\' - uses matlab's backslash operator to solve the sparse % system. 'backslash' is an alternate name. % % 'symmlq' - uses matlab's iterative symmlq solver % % 'lsqr' - uses matlab's iterative lsqr solver % % 'normal' - uses \ to solve the normal equations. % % % 'maxiter' - only applies to iterative solvers - defines the % maximum number of iterations for an iterative solver % % DEFAULT: min(10000,length(xnodes)*length(ynodes)) % % % 'extend' - character flag - controls whether the first and last % nodes in each dimension are allowed to be adjusted to % bound the data, and whether the user will be warned if % this was deemed necessary to happen. % % DEFAULT: 'warning' % % 'warning' - Adjust the first and/or last node in % x or y if the nodes do not FULLY contain % the data. Issue a warning message to this % effect, telling the amount of adjustment % applied. % % 'never' - Issue an error message when the nodes do % not absolutely contain the data. % % 'always' - automatically adjust the first and last % nodes in each dimension if necessary. % No warning is given when this option is set. % % % 'tilesize' - grids which are simply too large to solve for % in one single estimation step can be built as a set % of tiles. For example, a 1000x1000 grid will require % the estimation of 1e6 unknowns. This is likely to % require more memory (and time) than you have available. % But if your data is dense enough, then you can model % it locally using smaller tiles of the grid. % % My recommendation for a reasonable tilesize is % roughly 100 to 200. Tiles of this size take only % a few seconds to solve normally, so the entire grid % can be modeled in a finite amount of time. The minimum % tilesize can never be less than 3, although even this % size tile is so small as to be ridiculous. % % If your data is so sparse than some tiles contain % insufficient data to model, then those tiles will % be left as NaNs. % % DEFAULT: inf % % % 'overlap' - Tiles in a grid have some overlap, so they % can minimize any problems along the edge of a tile. % In this overlapped region, the grid is built using a % bi-linear combination of the overlapping tiles. % % The overlap is specified as a fraction of the tile % size, so an overlap of 0.20 means there will be a 20% % overlap of successive tiles. I do allow a zero overlap, % but it must be no more than 1/2. % % 0 <= overlap <= 0.5 % % Overlap is ignored if the tilesize is greater than the % number of nodes in both directions. % % DEFAULT: 0.20 % % % 'autoscale' - Some data may have widely different scales on % the respective x and y axes. If this happens, then % the regularization may experience difficulties. % % autoscale = 'on' will cause gridfit to scale the x % and y node intervals to a unit length. This should % improve the regularization procedure. The scaling is % purely internal. % % autoscale = 'off' will disable automatic scaling % % DEFAULT: 'on' % % % Arguments: (output) % zgrid - (nx,ny) array containing the fitted surface % % xgrid, ygrid - as returned by meshgrid(xnodes,ynodes) % % % Speed considerations: % Remember that gridfit must solve a LARGE system of linear % equations. There will be as many unknowns as the total % number of nodes in the final lattice. While these equations % may be sparse, solving a system of 10000 equations may take % a second or so. Very large problems may benefit from the % iterative solvers or from tiling. % % % Example usage: % % x = rand(100,1); % y = rand(100,1); % z = exp(x+2*y); % xnodes = 0:.1:1; % ynodes = 0:.1:1; % % g = gridfit(x,y,z,xnodes,ynodes); % % Note: this is equivalent to the following call: % % g = gridfit(x,y,z,xnodes,ynodes, ... % 'smooth',1, ... % 'interp','triangle', ... % 'solver','normal', ... % 'regularizer','gradient', ... % 'extend','warning', ... % 'tilesize',inf); % % % Author: John D'Errico % e-mail address: [email protected] % Release: 2.0 % Release date: 5/23/06 % set defaults params.smoothness = 1; params.interp = 'triangle'; params.regularizer = 'gradient'; params.solver = 'backslash'; params.maxiter = []; params.extend = 'warning'; params.tilesize = inf; params.overlap = 0.20; params.mask = []; params.autoscale = 'on'; params.xscale = 1; params.yscale = 1; % was the params struct supplied? if ~isempty(varargin) if isstruct(varargin{1}) % params is only supplied if its a call from tiled_gridfit params = varargin{1}; if length(varargin)>1 % check for any overrides params = parse_pv_pairs(params,varargin{2:end}); end else % check for any overrides of the defaults params = parse_pv_pairs(params,varargin); end end % check the parameters for acceptability params = check_params(params); % ensure all of x,y,z,xnodes,ynodes are column vectors, % also drop any NaN data x=x(:); y=y(:); z=z(:); k = isnan(x) | isnan(y) | isnan(z); if any(k) x(k)=[]; y(k)=[]; z(k)=[]; end xmin = min(x); xmax = max(x); ymin = min(y); ymax = max(y); % did they supply a scalar for the nodes? if length(xnodes)==1 xnodes = linspace(xmin,xmax,xnodes)'; xnodes(end) = xmax; % make sure it hits the max end if length(ynodes)==1 ynodes = linspace(ymin,ymax,ynodes)'; ynodes(end) = ymax; % make sure it hits the max end xnodes=xnodes(:); ynodes=ynodes(:); dx = diff(xnodes); dy = diff(ynodes); nx = length(xnodes); ny = length(ynodes); ngrid = nx*ny; % set the scaling if autoscale was on if strcmpi(params.autoscale,'on') params.xscale = mean(dx); params.yscale = mean(dy); params.autoscale = 'off'; end % check to see if any tiling is necessary if (params.tilesize < max(nx,ny)) % split it into smaller tiles. compute zgrid and ygrid % at the very end if requested zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params); else % its a single tile. % mask must be either an empty array, or a boolean % aray of the same size as the final grid. nmask = size(params.mask); if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny)) if ((nmask(2)==ny) || (nmask(1)==nx)) error 'Mask array is probably transposed from proper orientation.' else error 'Mask array must be the same size as the final grid.' end end if ~isempty(params.mask) params.maskflag = 1; else params.maskflag = 0; end % default for maxiter? if isempty(params.maxiter) params.maxiter = min(10000,nx*ny); end % check lengths of the data n = length(x); if (length(y)~=n) || (length(z)~=n) error 'Data vectors are incompatible in size.' end if n<3 error 'Insufficient data for surface estimation.' end % verify the nodes are distinct if any(diff(xnodes)<=0) || any(diff(ynodes)<=0) error 'xnodes and ynodes must be monotone increasing' end % do we need to tweak the first or last node in x or y? if xmin<xnodes(1) switch params.extend case 'always' xnodes(1) = xmin; case 'warning' warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)]) xnodes(1) = xmin; case 'never' error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)]) end end if xmax>xnodes(end) switch params.extend case 'always' xnodes(end) = xmax; case 'warning' warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)]) xnodes(end) = xmax; case 'never' error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))]) end end if ymin<ynodes(1) switch params.extend case 'always' ynodes(1) = ymin; case 'warning' warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)]) ynodes(1) = ymin; case 'never' error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)]) end end if ymax>ynodes(end) switch params.extend case 'always' ynodes(end) = ymax; case 'warning' warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)]) ynodes(end) = ymax; case 'never' error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))]) end end % determine which cell in the array each point lies in [junk,indx] = histc(x,xnodes); %#ok [junk,indy] = histc(y,ynodes); %#ok % any point falling at the last node is taken to be % inside the last cell in x or y. k=(indx==nx); indx(k)=indx(k)-1; k=(indy==ny); indy(k)=indy(k)-1; ind = indy + ny*(indx-1); % Do we have a mask to apply? if params.maskflag % if we do, then we need to ensure that every % cell with at least one data point also has at % least all of its corners unmasked. params.mask(ind) = 1; params.mask(ind+1) = 1; params.mask(ind+ny) = 1; params.mask(ind+ny+1) = 1; end % interpolation equations for each point tx = min(1,max(0,(x - xnodes(indx))./dx(indx))); ty = min(1,max(0,(y - ynodes(indy))./dy(indy))); % Future enhancement: add cubic interpolant switch params.interp case 'triangle' % linear interpolation inside each triangle k = (tx > ty); L = ones(n,1); L(k) = ny; t1 = min(tx,ty); t2 = max(tx,ty); A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ... [1-t2,t1,t2-t1],n,ngrid); case 'nearest' % nearest neighbor interpolation in a cell k = round(1-ty) + round(1-tx)*ny; A = sparse((1:n)',ind+k,ones(n,1),n,ngrid); case 'bilinear' % bilinear interpolation in a cell A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ... [(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ... n,ngrid); end rhs = z; % do we have relative smoothing parameters? if numel(params.smoothness) == 1 % it was scalar, so treat both dimensions equally smoothparam = params.smoothness; xyRelativeStiffness = [1;1]; else % It was a vector, so anisotropy reigns. % I've already checked that the vector was of length 2 smoothparam = sqrt(prod(params.smoothness)); xyRelativeStiffness = params.smoothness(:)./smoothparam; end % Build regularizer. Add del^4 regularizer one day. switch params.regularizer case 'springs' % zero "rest length" springs [i,j] = meshgrid(1:nx,1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = nx*(ny-1); stiffness = 1./(dy/params.yscale); Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ... xyRelativeStiffness(2)*stiffness(j(:))*[-1 1], ... m,ngrid); [i,j] = meshgrid(1:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); m = (nx-1)*ny; stiffness = 1./(dx/params.xscale); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ... xyRelativeStiffness(1)*stiffness(i(:))*[-1 1],m,ngrid)]; [i,j] = meshgrid(1:(nx-1),1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = (nx-1)*(ny-1); stiffness = 1./sqrt((dx(i(:))/params.xscale/xyRelativeStiffness(1)).^2 + ... (dy(j(:))/params.yscale/xyRelativeStiffness(2)).^2); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ... stiffness*[-1 1],m,ngrid)]; Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ... stiffness*[-1 1],m,ngrid)]; case {'diffusion' 'laplacian'} % thermal diffusion using Laplacian (del^2) [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ... 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ... 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid); case 'gradient' % Subtly different from the Laplacian. A point for future % enhancement is to do it better for the triangle interpolation % case. [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ... 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ... 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)]; end nreg = size(Areg,1); % Append the regularizer to the interpolation equations, % scaling the problem first. Use the 1-norm for speed. NA = norm(A,1); NR = norm(Areg,1); A = [A;Areg*(smoothparam*NA/NR)]; rhs = [rhs;zeros(nreg,1)]; % do we have a mask to apply? if params.maskflag unmasked = find(params.mask); end % solve the full system, with regularizer attached switch params.solver case {'\' 'backslash'} if params.maskflag % there is a mask to use zgrid=nan(ny,nx); zgrid(unmasked) = A(:,unmasked)\rhs; else % no mask zgrid = reshape(A\rhs,ny,nx); end case 'normal' % The normal equations, solved with \. Can be faster % for huge numbers of data points, but reasonably % sized grids. The regularizer makes A well conditioned % so the normal equations are not a terribly bad thing % here. if params.maskflag % there is a mask to use Aunmasked = A(:,unmasked); zgrid=nan(ny,nx); zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs); else zgrid = reshape((A'*A)\(A'*rhs),ny,nx); end case 'symmlq' % iterative solver - symmlq - requires a symmetric matrix, % so use it to solve the normal equations. No preconditioner. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ... A(:,unmasked)'*rhs,tol,params.maxiter); else [zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % SYMMLQ iterated MAXIT times but did not converge. warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ... ' iterations but did not converge.']) case 3 % SYMMLQ stagnated, successive iterates were the same warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.') otherwise warning('GRIDFIT:solver',['One of the scalar quantities calculated in',... ' symmlq was too small or too large to continue computing.']) end case 'lsqr' % iterative solver - lsqr. No preconditioner here. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter); else [zgrid,flag] = lsqr(A,rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % lsqr iterated MAXIT times but did not converge. warning('GRIDFIT:solver',['Lsqr performed ', ... num2str(params.maxiter),' iterations but did not converge.']) case 3 % lsqr stagnated, successive iterates were the same warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.') case 4 warning('GRIDFIT:solver',['One of the scalar quantities calculated in',... ' LSQR was too small or too large to continue computing.']) end end % switch params.solver end % if params.tilesize... % only generate xgrid and ygrid if requested. if nargout>1 [xgrid,ygrid]=meshgrid(xnodes,ynodes); end % ============================================ % End of main function - gridfit % ============================================ % ============================================ % subfunction - parse_pv_pairs % ============================================ function params=parse_pv_pairs(params,pv_pairs) % parse_pv_pairs: parses sets of property value pairs, allows defaults % usage: params=parse_pv_pairs(default_params,pv_pairs) % % arguments: (input) % default_params - structure, with one field for every potential % property/value pair. Each field will contain the default % value for that property. If no default is supplied for a % given property, then that field must be empty. % % pv_array - cell array of property/value pairs. % Case is ignored when comparing properties to the list % of field names. Also, any unambiguous shortening of a % field/property name is allowed. % % arguments: (output) % params - parameter struct that reflects any updated property/value % pairs in the pv_array. % % Example usage: % First, set default values for the parameters. Assume we % have four parameters that we wish to use optionally in % the function examplefun. % % - 'viscosity', which will have a default value of 1 % - 'volume', which will default to 1 % - 'pie' - which will have default value 3.141592653589793 % - 'description' - a text field, left empty by default % % The first argument to examplefun is one which will always be % supplied. % % function examplefun(dummyarg1,varargin) % params.Viscosity = 1; % params.Volume = 1; % params.Pie = 3.141592653589793 % % params.Description = ''; % params=parse_pv_pairs(params,varargin); % params % % Use examplefun, overriding the defaults for 'pie', 'viscosity' % and 'description'. The 'volume' parameter is left at its default. % % examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world') % % params = % Viscosity: 10 % Volume: 1 % Pie: 3 % Description: 'Hello world' % % Note that capitalization was ignored, and the property 'viscosity' % was truncated as supplied. Also note that the order the pairs were % supplied was arbitrary. npv = length(pv_pairs); n = npv/2; if n~=floor(n) error 'Property/value pairs must come in PAIRS.' end if n<=0 % just return the defaults return end if ~isstruct(params) error 'No structure for defaults was supplied' end % there was at least one pv pair. process any supplied propnames = fieldnames(params); lpropnames = lower(propnames); for i=1:n p_i = lower(pv_pairs{2*i-1}); v_i = pv_pairs{2*i}; ind = strmatch(p_i,lpropnames,'exact'); if isempty(ind) ind = find(strncmp(p_i,lpropnames,length(p_i))); if isempty(ind) error(['No matching property found for: ',pv_pairs{2*i-1}]) elseif length(ind)>1 error(['Ambiguous property name: ',pv_pairs{2*i-1}]) end end p_i = propnames{ind}; % override the corresponding default in params params = setfield(params,p_i,v_i); %#ok end % ============================================ % subfunction - check_params % ============================================ function params = check_params(params) % check the parameters for acceptability % smoothness == 1 by default if isempty(params.smoothness) params.smoothness = 1; else if (numel(params.smoothness)>2) || any(params.smoothness<=0) error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.' end end % regularizer - must be one of 4 options - the second and % third are actually synonyms. valid = {'springs', 'diffusion', 'laplacian', 'gradient'}; if isempty(params.regularizer) params.regularizer = 'diffusion'; end ind = find(strncmpi(params.regularizer,valid,length(params.regularizer))); if (length(ind)==1) params.regularizer = valid{ind}; else error(['Invalid regularization method: ',params.regularizer]) end % interp must be one of: % 'bilinear', 'nearest', or 'triangle' % but accept any shortening thereof. valid = {'bilinear', 'nearest', 'triangle'}; if isempty(params.interp) params.interp = 'triangle'; end ind = find(strncmpi(params.interp,valid,length(params.interp))); if (length(ind)==1) params.interp = valid{ind}; else error(['Invalid interpolation method: ',params.interp]) end % solver must be one of: % 'backslash', '\', 'symmlq', 'lsqr', or 'normal' % but accept any shortening thereof. valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'}; if isempty(params.solver) params.solver = '\'; end ind = find(strncmpi(params.solver,valid,length(params.solver))); if (length(ind)==1) params.solver = valid{ind}; else error(['Invalid solver option: ',params.solver]) end % extend must be one of: % 'never', 'warning', 'always' % but accept any shortening thereof. valid = {'never', 'warning', 'always'}; if isempty(params.extend) params.extend = 'warning'; end ind = find(strncmpi(params.extend,valid,length(params.extend))); if (length(ind)==1) params.extend = valid{ind}; else error(['Invalid extend option: ',params.extend]) end % tilesize == inf by default if isempty(params.tilesize) params.tilesize = inf; elseif (length(params.tilesize)>1) || (params.tilesize<3) error 'Tilesize must be scalar and > 0.' end % overlap == 0.20 by default if isempty(params.overlap) params.overlap = 0.20; elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5) error 'Overlap must be scalar and 0 < overlap < 1.' end % ============================================ % subfunction - tiled_gridfit % ============================================ function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params) % tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries % usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params) % % Tiled_gridfit is used when the total grid is far too large % to model using a single call to gridfit. While gridfit may take % only a second or so to build a 100x100 grid, a 2000x2000 grid % will probably not run at all due to memory problems. % % Tiles in the grid with insufficient data (<4 points) will be % filled with NaNs. Avoid use of too small tiles, especially % if your data has holes in it that may encompass an entire tile. % % A mask may also be applied, in which case tiled_gridfit will % subdivide the mask into tiles. Note that any boolean mask % provided is assumed to be the size of the complete grid. % % Tiled_gridfit may not be fast on huge grids, but it should run % as long as you use a reasonable tilesize. 8-) % Note that we have already verified all parameters in check_params % Matrix elements in a square tile tilesize = params.tilesize; % Size of overlap in terms of matrix elements. Overlaps % of purely zero cause problems, so force at least two % elements to overlap. overlap = max(2,floor(tilesize*params.overlap)); % reset the tilesize for each particular tile to be inf, so % we will never see a recursive call to tiled_gridfit Tparams = params; Tparams.tilesize = inf; nx = length(xnodes); ny = length(ynodes); zgrid = zeros(ny,nx); % linear ramp for the bilinear interpolation rampfun = inline('(t-t(1))/(t(end)-t(1))','t'); % loop over each tile in the grid h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.'); warncount = 0; xtind = 1:min(nx,tilesize); while ~isempty(xtind) && (xtind(1)<=nx) xinterp = ones(1,length(xtind)); if (xtind(1) ~= 1) xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap))); end if (xtind(end) ~= nx) xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end))); end ytind = 1:min(ny,tilesize); while ~isempty(ytind) && (ytind(1)<=ny) % update the waitbar waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx) yinterp = ones(length(ytind),1); if (ytind(1) ~= 1) yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap))); end if (ytind(end) ~= ny) yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end))); end % was a mask supplied? if ~isempty(params.mask) submask = params.mask(ytind,xtind); Tparams.mask = submask; end % extract data that lies in this grid tile k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ... (y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end))); k = find(k); if length(k)<4 if warncount == 0 warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.') end warncount = warncount + 1; % fill this part of the grid with NaNs zgrid(ytind,xtind) = NaN; else % build this tile zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams); % bilinear interpolation (using an outer product) interp_coef = yinterp*xinterp; % accumulate the tile into the complete grid zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef; end % step to the next tile in y if ytind(end)<ny ytind = ytind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (ytind(end)+max(3,overlap))>=ny % extend this tile to the edge ytind = ytind(1):ny; end else ytind = ny+1; end end % while loop over y % step to the next tile in x if xtind(end)<nx xtind = xtind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (xtind(end)+max(3,overlap))>=nx % extend this tile to the edge xtind = xtind(1):nx; end else xtind = nx+1; end end % while loop over x % close down the waitbar close(h) if warncount>0 warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs']) end
github
Lilin2015/MSRCR-master
MSRCR.m
.m
MSRCR-master/MSRCR.m
1,085
utf_8
76d9cb94096855fb2d08728fd700b5b0
% sigma, stds of gaussian filters in different scales, m*1 % w, weight of each scales, m*1 function img_out = MSRCR( img_in, sigma, w, alpha, d ) e = 0.004; img_in = img_in + e; if ~exist('sigma','var') || isempty(sigma) sigma = [2 90 180]; end if ~exist('w','var') || isempty(w) w = [1 1 1]/3; end if ~exist('alpha','var') || isempty(alpha) alpha = 128; end if ~exist('d','var') || isempty(d) d = 1.2; end % multi-scale Retinex, color restore scale = max(size(sigma,1),size(sigma,2)); S = log(img_in); R = cell(scale,1); for is = 1 : scale R{is} = S - imgaussfilt(S,sigma(is)); end R_sum = w(1)*R{1}; for is = 2 : scale R_sum = R_sum + w(is)*R{is}; end % dynamics of the colors C = log(alpha*img_in) - repmat(log(sum(img_in,3)),[1,1,3]); Rcr = C.*R_sum; meani = mean(Rcr(:)); vari = var(Rcr(:)); mini = meani - d*vari; maxi = meani + d*vari; range = maxi - mini; img_out = (Rcr - mini)/range; end
github
SJTU-IPADS/powerlyra-master
gibbs_sampler.m
.m
powerlyra-master/toolkits/graphical_models/deprecated/gibbs_sampling/matlab/gibbs_sampler.m
7,881
utf_8
b30a403ab91276aaddafbcc244c31a05
%% Parallel Gibbs sampler % The parallel gibbs sampler is an optimized a c++ implementation of % the discrete Gibbs samplers which uses multiple threads to % accelerate the generation of a single sampling chain. The parallel % Gibbs sampler implements two algorithms described in the paper: % % Parallel Gibbs Sampling: From Colored Fields to Think Junction Trees % by Joseph Gonzalez, Yucheng Low, Arthur Gretton, and Carlos Guestrin % % The first algorithm is the Chromatic sampler which is a direct % parallelization of the classic Gibbs sampler. The second algorithm % is the Splash Gibbs sampler which incrementally builds thin junction % trees. % % To use this function you must first construct a discrete factor % graph which is simply a cell array of table factors: % % factor{1} = table_factor( [1,2], log(rand(3,4)) ); % factor{2} = table_factor( [2,3], log(rand(4,2)) ); % % This creates a factorized model (with random tables) over the % variables 1, 2, and 3. We can then run the CHROMATIC sampler by % calling: % % options.alg_type = 'CHROMATIC'; % options.nsamples = 100; % options.nskip = 10; % [samples, nupdates, nchanges, marginals] = ... % gibbs_sampler(factors, options); % % % % Arguments: % factors: a cell array of factors constructed using the table_factor % function. % options: a struct with the following fields: % * alg_type: [Default: 'CHROMATIC'] A string either 'CHROMATIC' or % 'SPLASH'. For relatively fast mixing models the 'CHORMATIC' % algorithm is simpler and faster. For slowly mixing models % use the 'SPLASH' algorithm. In this case additional options % will need to be set. % * nsamples: [Default: 10] The number of joint samples to collect. % * nskip: [Default: 10] The number of samples to skip between % joint samples. Because of the asynchronous nature of the % algorithms more or than nskip samples may actually be skipped % in practice. In the 'SPLASH' algorithm nskip * nvariables % single variable updates are computed before the next joint % sample is constructed. % * ncpus: [Default: 2] The number of threads to use when running % the inference algorithm. The number of cpus should be less % than the number of variables and ideally not much larger than % the number of processors. % * treewidth: [Default: 3] The treewidth of the junction trees % constructed using the Splash sampler. % * treeheight: [Default: maxint] The largest height of a tree % * treesize: [Default: maxint] The largest possible size of a % tree % * priorities: [Default: false] Use priorities when % constructing the splash trees % * checkargs: [Default: True] Determines if the arguments are % checked before calling the C++ code. While we do additional % argument checking withing the C++ code it is often easier to % debug broken factors from within the matlab code. However % for the fastest performance disable checkargs (set to false). % % Return Arguments: % samples: nvars * nsamples matrix of joint assingments % nupdates: nvars * nsamples number of times each variable was updated. % nchanges: nvars * nsamples the number of times the variable's % assignment changed values % beliefs: nvars * nsamples cell array of vectors represent the % Rao-Blackwellized marginal estimates for each variable. % % See Also: table_factor % % This actual c++ mex function is provided in gibbs_sampler_impl.cpp % which can be compiled by running compile_gibbs_sampler.m. % function [samples, nupdates, nchanges, marginals] = ... gibbs_sampler(factors, options) %% Check the arguments if(~iscell(factors)) error('The factors argument must be a cell array of table_factors'); end % Define default options if(~exist('options', 'var')) options.alg_type = 'CHROMATIC'; end if(~isfield(options, 'alg_type')) options.alg_type = 'CHROMATIC'; end if(~isfield(options, 'nsamples')) options.nsamples = 10; end if(~isfield(options, 'nskip')) options.nskip = 10; end if(~isfield(options, 'ncpus')) options.ncpus = 2; end if(~isfield(options, 'treewidth')) options.treewidth = 3; end if(~isfield(options, 'treeheight')) options.treeheight = double(intmax()); end if(~isfield(options, 'treesize')) options.treesize = double(intmax()); end if(~isfield(options, 'priorities')) options.priorities = false; end if(~isfield(options, 'vanish')) options.vanish = 10; end if(~isfield(options, 'checkargs')) options.checkargs = true; end if(~isfield(options, 'save_alchemy')) options.save_alchemy = false; end options.treewidth = double(options.treewidth); if(options.treewidth > 32) error('Treewidth must be less than 32'); end if(options.treewidth < 1) error('Treewidth must be at least 1'); end if(options.checkargs) max_var = 0; %% Check the factors data structure for i = 1:length(factors) if(~isfield(factors{i}, 'vars')) disp(factors{i}); error('Factor %d does not contain the field vars', i); end if(~strcmp(class(factors{i}.vars), 'uint32')) disp(factors{i}); error(['Factor ', num2str(i), ... ' has variables of type ', ... class(factors{i}.vars), ... ' when they should be of type uint32.']); end if(~isfield(factors{i}, 'logP')) disp(factors{i}); error('Factor %d does not contain the field logP', i); end if(~strcmp(class(factors{i}.logP), 'double')) disp(factors{i}); error(['Factor ', num2str(i), ... ' has logP of type ', ... class(factors{i}.logP), ... ' when they should be of type double.']); end % Get the maximum variables max_var = max(max(factors{i}.vars(:)), max_var); if(min(factors{i}.vars) <= 0) disp(factors{i}); error('Factor %d has 0 valued variables', i); end end %% check all the variables have consistent sizes; vars = 1:max_var; var_sizes = zeros(max_var, 1); for i = 1:length(factors) current_sizes = var_sizes(factors{i}.vars); dims = size(factors{i}.logP)'; dims = dims(dims > 1); if(length(dims) ~= length(current_sizes)) error(['The number of variables %d in factor %d does not match ' ... 'the number of dimensions %d.'], ... length(current_sizes), i, length(dims)); end ind = current_sizes > 0; % all elements in ind have been set and should just match if( ~isempty(find(current_sizes(ind) ~= dims(ind), 1)) ) errorind = find(current_sizes(ind) ~= dims(ind), 1); error(['Variable %d has already been seen having size %d ', ... 'but was just now observed to have size %d in factor %d.'], ... factors{i}.variables(ind(errorind)), ... current_sizes(ind(errorind)), ... dims(ind(errorind)), ... i); end var_sizes(factors{i}.vars(~ind)) = dims(~ind); end unset_vars = find(var_sizes(:) == 0); if(~isempty(unset_vars)) error(['The following variables were not set correctly: ', ... mat2str(unset_vars)]); end end %% Call the sampler if(nargout() <= 1) samples = gibbs_sampler_impl(factors, options); elseif(nargout() == 2) [samples, nupdates] = gibbs_sampler_impl(factors, options); elseif(nargout() == 3) [samples, nupdates, nchanges] = ... gibbs_sampler_impl(factors, options); elseif(nargout() == 4) [samples, nupdates, nchanges, marginals] = ... gibbs_sampler_impl(factors, options); end end
github
SJTU-IPADS/powerlyra-master
table_factor.m
.m
powerlyra-master/toolkits/graphical_models/deprecated/gibbs_sampling/matlab/table_factor.m
1,525
utf_8
594788b85d9bb283d16d642095087db6
%% Construct a discrete table factor % % factor = table_factor(vars, logP) % % vars: array of variable ids (e.g., [1,2,4] ) % logP: tensor representing the log potential values (e.g., ones(3,7,2) % where variable 1 takes on 3 states variable 2 takes on 7 states and % variable 4 takes on 2 states. % % A table factor represents a factor or potential over a small set of % discrete variables. Forexample if we wanted to encode a similarity % funciton over a pair of variables x1 and x2 we could define the table % factor: % % psi(x1,x2) = exp( |x1 - x2| ) % % Assuming x1 and x2 take on 4 and 3 values respectively we could define % the matrix (table) representation of psi: % % 0 1 2 % tbl = exp( 1 0 1 ) % 2 1 0 % 3 2 1 % % We can build a table factor representing this as: % % factor = table_factor([1, 2], tbl); % function factor = table_factor(vars, data) factor.vars = sort(uint32(vars)); factor.logP = double(data); end %% % Originally I had hoped to used a matlab class but unfortunatley mex % support for classes is limited resulting in substantial performance % penalties when accessing fields. % classdef table_factor % properties (SetAccess = private) % variables; % end % properties % logP; % end % methods % %% the variables should be a d dimensional array % function obj = table_factor(vars, data) % obj.variables = uint32(vars); % obj.logP = double(data); % end % % end % % end
github
SJTU-IPADS/powerlyra-master
make_grid_model.m
.m
powerlyra-master/toolkits/graphical_models/deprecated/gibbs_sampling/matlab/tests/make_grid_model.m
1,737
utf_8
9310c056cecd8ce7e9e221ebe8730252
%% This code generates a grid model function [factors, img, noisy_img] = make_grid_model(rows, cols, states, ... lambdaSmooth, noiseP) % Create a virtual image [u,v] = meshgrid(linspace(0,1,rows), linspace(0,1,cols)); img = (1 + cos(1./sqrt((u-.5).^2 + (v-.5).^2)) )/2 + u.^2; img = (img - min(img(:)))/(max(img(:)) - min(img(:))); img = (states - 1) * img; img = round(img) + 1; figure(1); clf();subplot(1,3,1); colormap('gray'); imagesc(img); title('Original Image'); % add noise mask = rand(rows,cols) < noiseP; noise = ceil(states*rand(rows,cols)); noisy_img = mask .* noise + ~mask .* img; figure(1); subplot(1,3,2); colormap('gray'); imagesc(noisy_img); title('Noisy Image'); % Build the edge factor table (in log form) [u,v] = meshgrid(1:states, 1:states); edgetbl = -lambdaSmooth * abs(u - v); % Build the node factor tableS based on the noise model nodetbls = zeros(rows*cols, states) + ... noiseP/(states - 1); ind = sub2ind([rows * cols, states], (1:(rows*cols))', noisy_img(:)); nodetbls(ind) = 1-noiseP; nodetbls = log(nodetbls); % Get all the edges and variables vars = 1:(rows*cols); gridvars = reshape(vars, rows, cols); edges = ... [reshape(gridvars(1:(end-1),:), (rows-1) * cols,1), ... reshape(gridvars(2:end,:), (rows-1) * cols,1); ... reshape(gridvars(:,1:(end-1)), rows * (cols-1), 1), ... reshape(gridvars(:,2:end), rows * (cols-1),1)]; % construct the actual factors factors = cell(length(vars) + length(edges), 1); index = 1; for i = 1:length(vars) factors{index} = table_factor(vars(i), nodetbls(vars(i),:)); index = index + 1; end index = length(vars)+1; for i = 1:length(edges) factors{index} = table_factor(sort(edges(i,:)), edgetbl); index = index + 1; end end
github
scanUCLA/MRtools_Hoffman2-master
pdftops.m
.m
MRtools_Hoffman2-master/export_fig/pdftops.m
3,068
utf_8
7a40ce10e58d68cd7eeda67992b993f3
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); return function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.')) end base = uigetdir('/', 'Pdftops not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.'); return end return function good = check_xpdf_path(path_) % Check the path is valid [good message] = system(sprintf('"%s" -h', path_)); % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); return
github
scanUCLA/MRtools_Hoffman2-master
isolate_axes.m
.m
MRtools_Hoffman2-master/export_fig/isolate_axes.m
3,794
utf_8
b104d66dd4d36f35d275c4ef3d2f41cd
%ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m. % 12/12/12 - Add support for isolating uipanels. Thanks to michael for % suggesting it. % 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!). % 05/12/13 - Bug fix to axes having different units. Thanks to Remington % Reid for reporting the issue. function fh = isolate_axes(ah, vis) % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'}); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); ax_pos = get(ah, 'OuterPosition'); if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); leg_pos = get(lh, 'OuterPosition'); if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); return function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); return function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end return
github
scanUCLA/MRtools_Hoffman2-master
pdf2eps.m
.m
MRtools_Hoffman2-master/export_fig/pdf2eps.m
1,524
utf_8
037f9109e96ab4385d13019a29db4639
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); return
github
scanUCLA/MRtools_Hoffman2-master
print2array.m
.m
MRtools_Hoffman2-master/export_fig/print2array.m
6,474
utf_8
4ead930267fe61c9b2a87139ee559dc8
%PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2012 % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the % issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting % the issue. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure % size and erasemode settings. Makes it a bit slower, but more % reliable. Thanks to Phil Trinh and Meelis Lootus for reporting % the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting % it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. function [A, bcol] = print2array(fig, res, renderer) % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file tmp_eps = [tempname '.eps']; print2eps(tmp_eps, fig, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"']; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = [px([4 3])*res 3]; if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
scanUCLA/MRtools_Hoffman2-master
eps2pdf.m
.m
MRtools_Hoffman2-master/export_fig/eps2pdf.m
5,151
utf_8
b356d73460fdebe8ef6fa428d5b2c125
%EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % %IN: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed to % already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale or % not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % Copyright (C) Oliver Woodford 2009-2011 % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. function eps2pdf(source, dest, crop, append, gray, quality) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status message] = ghostscript(options); catch % Delete the intermediate file delete(tmp_nam); rethrow(lasterror); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status message] = ghostscript(options); end % Check for error if status % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); else error(message); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
scanUCLA/MRtools_Hoffman2-master
copyfig.m
.m
MRtools_Hoffman2-master/export_fig/copyfig.m
846
utf_8
8f479727f76b878a077b76ca7afed48e
%COPYFIG Create a copy of a figure, without changing the figure % % Examples: % fh_new = copyfig(fh_old) % % This function will create a copy of a figure, but not change the figure, % as copyobj sometimes does, e.g. by changing legends. % % IN: % fh_old - The handle of the figure to be copied. Default: gcf. % % OUT: % fh_new - The handle of the created figure. % Copyright (C) Oliver Woodford 2012 function fh = copyfig(fh) % Set the default if nargin == 0 fh = gcf; end % Is there a legend? if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend')) % Safe to copy using copyobj fh = copyobj(fh, 0); else % copyobj will change the figure, so save and then load it instead tmp_nam = [tempname '.fig']; hgsave(fh, tmp_nam); fh = hgload(tmp_nam); delete(tmp_nam); end return
github
scanUCLA/MRtools_Hoffman2-master
user_string.m
.m
MRtools_Hoffman2-master/export_fig/user_string.m
2,462
utf_8
dd1a7fa5b4f2be6320fc2538737a2f3e
%USER_STRING Get/set a user specific string % % Examples: % string = user_string(string_name) % saved = user_string(string_name, new_string) % % Function to get and set a string in a system or user specific file. This % enables, for example, system specific paths to binaries to be saved. % % IN: % string_name - String containing the name of the string required. The % string is extracted from a file called (string_name).txt, % stored in the same directory as user_string.m. % new_string - The new string to be saved under the name given by % string_name. % % OUT: % string - The currently saved string. Default: ''. % saved - Boolean indicating whether the save was succesful % Copyright (C) Oliver Woodford 2011-2013 % This method of saving paths avoids changing .m files which might be in a % version control system. Instead it saves the user dependent paths in % separate files with a .txt extension, which need not be checked in to % the version control system. Thank you to Jonas Dorn for suggesting this % approach. % 10/01/2013 - Access files in text, not binary mode, as latter can cause % errors. Thanks to Christian for pointing this out. function string = user_string(string_name, string) if ~ischar(string_name) error('string_name must be a string.'); end % Create the full filename string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']); if nargin > 1 % Set string if ~ischar(string) error('new_string must be a string.'); end % Make sure the save directory exists dname = fileparts(string_name); if ~exist(dname, 'dir') % Create the directory try if ~mkdir(dname) string = false; return end catch string = false; return end % Make it hidden try fileattrib(dname, '+h'); catch end end % Write the file fid = fopen(string_name, 'wt'); if fid == -1 string = false; return end try fprintf(fid, '%s', string); catch fclose(fid); string = false; return end fclose(fid); string = true; else % Get string fid = fopen(string_name, 'rt'); if fid == -1 string = ''; return end string = fgetl(fid); fclose(fid); end return
github
scanUCLA/MRtools_Hoffman2-master
export_fig.m
.m
MRtools_Hoffman2-master/export_fig/export_fig.m
30,376
utf_8
7dab6f956d238b4a8bd6770e3fa948ec
%EXPORT_FIG Exports figures suitable for publication % % Examples: % im = export_fig % [im alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the % workspace, with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png) % - Semi-transparent patch objects supported (png only) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. Pdf, eps and png are the only file formats to support a % transparent background, whilst the png format alone supports transparency % of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. Whilst the default value (opengl for bitmaps, % painters for vector formats) generally gives good results, if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (eps, % pdf), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (pdf & eps) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % %IN: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure pixel dimensions by when generating bitmap % outputs. Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap and vector outputs at, keeping the dimensions % of the on-screen figure. Default: '-r864' (for vector output % only). Note that the -m option overides the -r option for % bitmap outputs only. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl % or zbuffer) to be used over the default: opengl for % bitmaps; painters for vector formats. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % handle - The handle of the figure, axes or uipanels (can be an array of % handles, but the objects must be in the same figure) to be % saved. Default: gcf. % %OUT: % im - MxNxC uint8 image array of the figure. % alpha - MxN single array of alphamatte values in range [0,1], for the % case when the background is transparent. % % Some helpful examples and tips can be found at: % http://sites.google.com/site/oliverwoodford/software/export_fig % % See also PRINT, SAVEAS. % Copyright (C) Oliver Woodford 2008-2012 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for % reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling % bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep % tick marks fixed. % 12/12/12: Add support for isolating uipanels. Thanks to michael for % suggesting it. % 25/09/13: Add support for changing resolution in vector formats. Thanks % to Jan Jaap Meijer for suggesting it. function [im, alpha] = export_fig(varargin) % Make sure the figure is rendered correctly _now_ so that properties like % axes limits are up-to-date. drawnow; % Parse the input arguments [fig, options] = parse_args(nargout, varargin{:}); % Isolate the subplot, if it is one cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else % Check we have a figure if ~isequal(get(fig, 'Type'), 'figure'); error('Handle must be that of a figure, axes or uipanel'); end % Get the old InvertHardcopy mode old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in % print?). This may not work perfectly in all cases. Also it can change the % figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findobj(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findobj(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end % MATLAB "feature": axes limits and tick marks can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual'); % Set to print exactly what is there set(fig, 'InvertHardcopy', 'off'); % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end % Do the bitmap formats first if isbitmap(options) % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop [alpha, v] = crop_background(alpha, 0); A = A(v(1):v(2),v(3):v(4),:); end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image im = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image im = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A, tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_background(A, tcol); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im im = A; end if options.alpha im = A; alpha = zeros(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer renderer = '-painters'; end % Generate some filenames tmp_nam = [tempname '.eps']; if options.pdf pdf_nam = [options.name '.pdf']; else pdf_nam = [tempname '.pdf']; end % Generate the options for print p2eArgs = {renderer, sprintf('-r%d', options.resolution)}; if options.colourspace == 1 p2eArgs = [p2eArgs {'-cmyk'}]; end if ~options.crop p2eArgs = [p2eArgs {'-loose'}]; end try % Generate an eps print2eps(tmp_nam, fig, p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality); catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps try % Generate an eps from the pdf pdf2eps(pdf_nam, [options.name '.eps']); catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end if cls % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a}); end end return function [fig, options] = parse_args(nout, varargin) % Parse the input arguments % Set the defaults fig = get(0, 'CurrentFigure'); options = struct('name', 'export_fig_out', ... 'crop', true, ... 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', nout == 1, ... 'alpha', nout == 2, ... 'aa_factor', 3, ... 'magnify', [], ... 'resolution', [], ... 'bookmark', false, ... 'quality', []); native = false; % Set resolution to native of an image % Go through the other arguments for a = 1:nargin-1 if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; otherwise val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match')); if ~isscalar(val) error('option %s not recognised', varargin{a}); end switch lower(varargin{a}(2)) case 'm' options.magnify = val; case 'r' options.resolution = val; case 'q' options.quality = max(val, 0); end end else [p, options.name, ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; otherwise options.name = varargin{a}; end end end end % Compute the magnification and resolution if isempty(options.magnify) if isempty(options.resolution) options.magnify = 1; options.resolution = 864; else options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch'); end elseif isempty(options.resolution) options.resolution = 864; end % Check we have a figure handle if isempty(fig) error('No figure found'); end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native'); if isempty(list) list = findobj(fig, 'Type', 'image', 'Visible', 'on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice % versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = (height * diff(yl2)) / (pos * diff(yl)); break end end return function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end return function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); return function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end return function [A, v] = crop_background(A, bcol) % Map the foreground pixels [h, w, c] = size(A); if isscalar(bcol) && c > 1 bcol = bcol(ones(1, c)); end bail = false; for l = 1:w for a = 1:c if ~all(A(:,l,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for r = w:-1:l for a = 1:c if ~all(A(:,r,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for t = 1:h for a = 1:c if ~all(A(t,:,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for b = h:-1:t for a = 1:c if ~all(A(b,:,a) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on % resize v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)]; A = A(v(1):v(2),v(3):v(4),:); return function eps_remove_background(fname) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while true % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); break; end end % Close the file fclose(fh); return function b = isvector(options) b = options.pdf || options.eps; return function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; return % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end return function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); return
github
scanUCLA/MRtools_Hoffman2-master
ghostscript.m
.m
MRtools_Hoffman2-master/export_fig/ghostscript.m
4,650
utf_8
db7a65458702e2333638288011dc0d7e
%GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2013 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Nathan Childress for the fix to the default location on 64-bit % Windows systems. % 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 4/5/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. function varargout = ghostscript(cmd) % Initialize any required system calls before calling ghostscript shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end % Call ghostscript [varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd)); return function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else bin = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while 1 if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.'); return end return function good = check_gs_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); good = good == 0; return