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
khanhnamle1994/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
khanhnamle1994/machine-learning-master
savejson.m
.m
machine-learning-master/machine-learning-ex5/ex5/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
khanhnamle1994/machine-learning-master
loadjson.m
.m
machine-learning-master/machine-learning-ex5/ex5/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
loadubjson.m
.m
machine-learning-master/machine-learning-ex5/ex5/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
saveubjson.m
.m
machine-learning-master/machine-learning-ex5/ex5/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
khanhnamle1994/machine-learning-master
submit.m
.m
machine-learning-master/machine-learning-ex3/ex3/submit.m
1,567
utf_8
1dba733a05282b2db9f2284548483b81
function submit() addpath('./lib'); conf.assignmentSlug = 'multi-class-classification-and-neural-networks'; conf.itemName = 'Multi-class Classification and Neural Networks'; conf.partArrays = { ... { ... '1', ... { 'lrCostFunction.m' }, ... 'Regularized Logistic Regression', ... }, ... { ... '2', ... { 'oneVsAll.m' }, ... 'One-vs-All Classifier Training', ... }, ... { ... '3', ... { 'predictOneVsAll.m' }, ... 'One-vs-All Classifier Prediction', ... }, ... { ... '4', ... { 'predict.m' }, ... 'Neural Network Prediction Function' ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxdata) % Random Test Cases X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))']; y = sin(X(:,1) + X(:,2)) > 0; Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ... 1 1 ; 1 2 ; 2 1 ; 2 2 ; ... -1 1 ; -1 2 ; -2 1 ; -2 2 ; ... 1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ]; ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); if partId == '1' [J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '2' out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1)); elseif partId == '3' out = sprintf('%0.5f ', predictOneVsAll(t1, Xm)); elseif partId == '4' out = sprintf('%0.5f ', predict(t1, t2, Xm)); end end
github
khanhnamle1994/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
khanhnamle1994/machine-learning-master
savejson.m
.m
machine-learning-master/machine-learning-ex3/ex3/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
khanhnamle1994/machine-learning-master
loadjson.m
.m
machine-learning-master/machine-learning-ex3/ex3/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
loadubjson.m
.m
machine-learning-master/machine-learning-ex3/ex3/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
saveubjson.m
.m
machine-learning-master/machine-learning-ex3/ex3/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
khanhnamle1994/machine-learning-master
submit.m
.m
machine-learning-master/machine-learning-ex8/ex8/submit.m
2,135
utf_8
eebb8c0a1db5a4df20b4c858603efad6
function submit() addpath('./lib'); conf.assignmentSlug = 'anomaly-detection-and-recommender-systems'; conf.itemName = 'Anomaly Detection and Recommender Systems'; conf.partArrays = { ... { ... '1', ... { 'estimateGaussian.m' }, ... 'Estimate Gaussian Parameters', ... }, ... { ... '2', ... { 'selectThreshold.m' }, ... 'Select Threshold', ... }, ... { ... '3', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Cost', ... }, ... { ... '4', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Gradient', ... }, ... { ... '5', ... { 'cofiCostFunc.m' }, ... 'Regularized Cost', ... }, ... { ... '6', ... { 'cofiCostFunc.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases n_u = 3; n_m = 4; n = 5; X = reshape(sin(1:n_m*n), n_m, n); Theta = reshape(cos(1:n_u*n), n_u, n); Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u); R = Y > 0.5; pval = [abs(Y(:)) ; 0.001; 1]; Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed yval = [R(:) ; 1; 0]; params = [X(:); Theta(:)]; if partId == '1' [mu sigma2] = estimateGaussian(X); out = sprintf('%0.5f ', [mu(:); sigma2(:)]); elseif partId == '2' [bestEpsilon bestF1] = selectThreshold(yval, pval); out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]); elseif partId == '3' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', J(:)); elseif partId == '4' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', grad(:)); elseif partId == '5' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', J(:)); elseif partId == '6' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', grad(:)); end end
github
khanhnamle1994/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/machine-learning-ex8/ex8/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
khanhnamle1994/machine-learning-master
savejson.m
.m
machine-learning-master/machine-learning-ex8/ex8/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
khanhnamle1994/machine-learning-master
loadjson.m
.m
machine-learning-master/machine-learning-ex8/ex8/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
loadubjson.m
.m
machine-learning-master/machine-learning-ex8/ex8/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
saveubjson.m
.m
machine-learning-master/machine-learning-ex8/ex8/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
khanhnamle1994/machine-learning-master
submit.m
.m
machine-learning-master/machine-learning-ex1/ex1/submit.m
1,876
utf_8
8d1c467b830a89c187c05b121cb8fbfd
function submit() addpath('./lib'); conf.assignmentSlug = 'linear-regression'; conf.itemName = 'Linear Regression with Multiple Variables'; conf.partArrays = { ... { ... '1', ... { 'warmUpExercise.m' }, ... 'Warm-up Exercise', ... }, ... { ... '2', ... { 'computeCost.m' }, ... 'Computing Cost (for One Variable)', ... }, ... { ... '3', ... { 'gradientDescent.m' }, ... 'Gradient Descent (for One Variable)', ... }, ... { ... '4', ... { 'featureNormalize.m' }, ... 'Feature Normalization', ... }, ... { ... '5', ... { 'computeCostMulti.m' }, ... 'Computing Cost (for Multiple Variables)', ... }, ... { ... '6', ... { 'gradientDescentMulti.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '7', ... { 'normalEqn.m' }, ... 'Normal Equations', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId) % Random Test Cases X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))']; Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2)); X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25]; Y2 = Y1.^0.5 + Y1; if partId == '1' out = sprintf('%0.5f ', warmUpExercise()); elseif partId == '2' out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]')); elseif partId == '3' out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10)); elseif partId == '4' out = sprintf('%0.5f ', featureNormalize(X2(:,2:4))); elseif partId == '5' out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]')); elseif partId == '6' out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10)); elseif partId == '7' out = sprintf('%0.5f ', normalEqn(X2, Y2)); end end
github
khanhnamle1994/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
khanhnamle1994/machine-learning-master
savejson.m
.m
machine-learning-master/machine-learning-ex1/ex1/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
khanhnamle1994/machine-learning-master
loadjson.m
.m
machine-learning-master/machine-learning-ex1/ex1/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
loadubjson.m
.m
machine-learning-master/machine-learning-ex1/ex1/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
khanhnamle1994/machine-learning-master
saveubjson.m
.m
machine-learning-master/machine-learning-ex1/ex1/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
JoseBarreiros/CellDecomposition-master
Cell_Decomposition_v2.m
.m
CellDecomposition-master/Cell_Decomposition_v2.m
11,970
utf_8
3e144c774b1c2719cdd0f1b246d5b744
%Exact Cell Decomposition [ECD]% %Implementation of Path Planning Algorith using ECD% %The algorithm identify the cells and C-objects from an XML file that include a C-workspace (.cmap), then find %the distance between the centroids of each cell and calculate the shortest %path. The actual trajectory for the robot is a set of lines from the midpoint of %every cell included in the path. %Created by Jose Barreiros, Oct. 2017. %PhD student. %Cornell University. %The XML script and GUI structure are based on the work of Ahmad Abbadi, Brno University of Technology (VUT), Czech Republic function varargout = Cell_Decomposition_v2(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Cell_Decomposition_v2_OpeningFcn, ... 'gui_OutputFcn', @Cell_Decomposition_v2_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT end function Cell_Decomposition_v2_OpeningFcn(hObject, eventdata, handles, varargin) handles.drawingFigHandle=handles.axes1; handles.obstacles=[]; handles.cells=[]; handles.pois=[]; handles.currentobstacleIndex=[]; handles.file.FileName=[]; handles.file.PathName=[]; handles.changesaved=1; handles.axesAttribute.xlim=[0 10]; handles.axesAttribute.ylim=[0 10]; adjacent=[]; w_adj=[]; coord=[]; path_vertex=[]; handles.SPosition.center=[]; handles.SPosition.radius=[]; handles.SPosition.h=[]; handles.SPosition.type=[]; handles.GPosition.center=[]; handles.GPosition.radius=[]; handles.GPosition.h=[]; handles.GPosition.type=[]; handles.cellDecom.graph=[]; handles.cellDecom.cells=[]; set(handles.drawingFigHandle,'xlim',handles.axesAttribute.xlim,'ylim',handles.axesAttribute.ylim); hold on; % Choose default command line output for planner_GUI handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes planner_GUI wait for user response (see UIRESUME) % uiwait(handles.figure1); end function LoadCSpace_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to LoadCSpace_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [FileName,PathName,FilterIndex] = uigetfile('*.cmap','Open File'); if (FileName~=0) handles.file.FileName=FileName; handles.file.PathName=PathName; if size(handles.obstacles,1) >0 delete(handles.obstacles(:).linehandles); handles.obstacles=[]; handles.currentobstacleIndex=[]; end ObstacleXML=xmlread(strcat(PathName,FileName)); scpaceNode=ObstacleXML.getDocumentElement; dimension= str2double(scpaceNode.getAttribute('dim')); if dimension~=2 h=warndlg('Can not open dimention oher than 2'); uiwait(h); else % retrieve obstacles obstacles=scpaceNode.getElementsByTagName('obstacle'); cells=scpaceNode.getElementsByTagName('cell'); pois=scpaceNode.getElementsByTagName('poi'); obsLength=obstacles.getLength - 1; cellLength=cells.getLength - 1; poiLength=pois.getLength - 1; for i= 0 : obsLength obs=obstacles.item(i); newobstacle=[]; newobstacle.type=char(obs.getAttribute('type')); vertices=obs.getElementsByTagName('vertex'); verLength=vertices.getLength-1; for j=0:verLength newobstacle.vertex(j+1,1)=str2double(vertices.item(j).getAttribute('x')); newobstacle.vertex(j+1,2)=str2double(vertices.item(j).getAttribute('y')); end newobstacle.ID=i+1; handles.obstacles=[handles.obstacles;newobstacle]; end % retrieve cells for i= 0 : cellLength cel=cells.item(i); newcell=[]; newcell.type=char(cel.getAttribute('type')); vertices=cel.getElementsByTagName('vertex'); verLength=vertices.getLength-1; for j=0:verLength newcell.vertex(j+1,1)=str2double(vertices.item(j).getAttribute('x')); newcell.vertex(j+1,2)=str2double(vertices.item(j).getAttribute('y')); end newcell.ID=i+1; handles.cells=[handles.cells;newcell]; end % retrieve points of interest POI: start and end condition for i= 0 : poiLength poi=pois.item(i); newpoi=[]; newpoi.type=char(poi.getAttribute('type')); vertices=poi.getElementsByTagName('point'); verLength=vertices.getLength-1; for j=0:verLength newpoi.vertex(j+1,1)=str2double(vertices.item(j).getAttribute('x')); newpoi.vertex(j+1,2)=str2double(vertices.item(j).getAttribute('y')); end newpoi.ID=i+1; handles.pois=[handles.pois;newpoi]; end % retrieve Axes sitting AxesNode=scpaceNode.getElementsByTagName('Axes'); handles.axesAttribute.xlim = str2num(AxesNode.item(0).getAttribute('xlim')); handles.axesAttribute.ylim = str2num(AxesNode.item(0).getAttribute('xlim')); set(handles.drawingFigHandle,'xlim',handles.axesAttribute.xlim,'ylim',handles.axesAttribute.ylim); hold on; %draw obstacle for i=1:size(handles.obstacles,1) handles.obstacles(i).linehandles=fill([handles.obstacles(i).vertex(:,1);handles.obstacles(i).vertex(1,1)],[handles.obstacles(i).vertex(:,2);handles.obstacles(i).vertex(1,2)],'b'); alpha(handles.obstacles(i).linehandles,0.3);% color transparency set(handles.obstacles(i).linehandles,'EdgeColor','none');% edge color of obstacle end %draw cells for i=1:size(handles.cells,1) handles.cells(i).linehandles=fill([handles.cells(i).vertex(:,1);handles.cells(i).vertex(1,1)],[handles.cells(i).vertex(:,2);handles.cells(i).vertex(1,2)],'g'); alpha(handles.cells(i).linehandles,0.2);% color transparency set(handles.cells(i).linehandles,'EdgeColor','r');% edge color of obstacle [ geom, iner, cpmo ] = polygeom([handles.cells(i).vertex(:,1);handles.cells(i).vertex(1,1)],[handles.cells(i).vertex(:,2);handles.cells(i).vertex(1,2)]); area = geom(1); handles.cells(i).centroid(1) = geom(2); handles.cells(i).centroid(2) = geom(3); x_cen=handles.cells(i).centroid(1) y_cen=handles.cells(i).centroid(2) txt=int2str(i); % text(x_cen,y_cen,txt); coord(i,:)=[x_cen y_cen]; %create coordinates for connectivity graph handles.coord(i,:)=[x_cen y_cen]; end tic; end end hObject.UserData = handles; end function Path_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to LoadCSpace_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) h = findobj('Tag','LoadCSpace_pushbutton'); handles = h.UserData coord = handles.coord %test for adjacency adjacent=zeros(size(handles.cells,1)); w_adj=zeros(size(handles.cells,1)); x=zeros(size(handles.cells,1),1) y=zeros(size(handles.cells,1),1) v_count=0; for i=1:size(handles.cells,1) for j=1:size(handles.cells,1) v_count=0; for k=1:subsref(size(handles.cells(i).vertex),struct('type','()','subs',{{1,1}})) for m=1:subsref(size(handles.cells(j).vertex),struct('type','()','subs',{{1,1}})) if isequal(handles.cells(i).vertex(k,:),handles.cells(j).vertex(m,:))==1 v_count=v_count+1; %count common vertices if v_count>1 %if cells share at least 2 common vertices then the cells are adjacent adjacent(i,j)=1; end end end end end end adjacent; %plot adjacent matrix gplot(adjacent,coord,'-*') %build connectivity graph and find shortest path for i=1:size(handles.cells,1) xi=handles.cells(i).centroid(1) x(i)=xi yi=handles.cells(i).centroid(2) y(i)=yi for j=i+1:size(handles.cells,1) xj=handles.cells(j).centroid(1) yj=handles.cells(j).centroid(2) if adjacent(i,j)==1 distance=pdist([xi,yi;xj,yj],'euclidean') w_adj(i,j)=distance; %build a weighted adjacency matrix mid_x=(xi+xj)/2 mid_y=(yi+yj)/2 txt=num2str(distance,4); text(mid_x,mid_y,txt); end end end w_adj G=graph(w_adj,'upper') plot(G, 'XData', x, 'YData', y,'LineWidth',2, 'EdgeColor',[0,0.7,0.9]) P = shortestpath(G,3,8) %draw POIs for i=1:size(handles.pois,1) %handles.pois(i).linehandles=fill([handles.pois(i).vertex(:,1);handles.pois(i).vertex(1,1)],[handles.pois(i).vertex(:,2);handles.pois(i).vertex(1,2)],'c'); plot(handles.pois(i).vertex(1,1),handles.pois(i).vertex(1,2),'ks') txt=handles.pois(i).type tex=text(handles.pois(i).vertex(1,1),handles.pois(i).vertex(1,2),txt) tex.FontSize=11 tex.FontWeight = 'bold' % alpha(handles.pois(i).linehandles,0.4);% color transparency % set(handles.pois(i).linehandles,'EdgeColor','k');% edge color of obstacle end %find the matrix of the shortest path line using the midpoints of the edges for i=1:size(P,2) i for j=1:subsref(size(handles.cells(P(i)).vertex),struct('type','()','subs',{{1,1}})) j if j==subsref(size(handles.cells(P(i)).vertex),struct('type','()','subs',{{1,1}})) k=1 else k=j+1 end lx=[handles.cells(P(i)).centroid(1) handles.cells(P(i)+1).centroid(1) handles.cells(P(i)).vertex(j,1) handles.cells(P(i)).vertex(k,1)] ly=[handles.cells(P(i)).centroid(2) handles.cells(P(i)+1).centroid(2) handles.cells(P(i)).vertex(j,2) handles.cells(P(i)).vertex(k,2)] dt1=det([1,1,1;lx(1),lx(2),lx(3);ly(1),ly(2),ly(3)])*det([1,1,1;lx(1),lx(2),lx(4);ly(1),ly(2),ly(4)]) dt2=det([1,1,1;lx(1),lx(3),lx(4);ly(1),ly(3),ly(4)])*det([1,1,1;lx(2),lx(3),lx(4);ly(2),ly(3),ly(4)]) if(dt1<=0 & dt2<=0) path_vertex(i,:)=[(lx(3)+lx(4))/2 (ly(3)+ly(4))/2] end end end path_vertex path_vertex=cat(1,handles.pois(1).vertex,path_vertex) path_vertex(i+1,:)=handles.pois(2).vertex %plot minimum path from start to end point plot(path_vertex(:,1),path_vertex(:,2),'k','LineWidth',3) toc % new load; no change handles.changesaved=1; % update handles data guidata(hObject, handles); end
github
Steganalysis-CNN/CNN-without-BN-master
test_model.m
.m
CNN-without-BN-master/test_model.m
13,664
utf_8
886d977fcccf7561fd2cfb2ae616eb21
function [net,stats] = test_model(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.checkpointFn = []; % will be called after every epoch opts.plotStatistics = false; 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.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 if ~isempty(opts.checkpointFn), opts.checkpointFn(); 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, payload) ; 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) ; % we do not report the top-5 error here count = 0; for f = setdiff(fieldnames(stats)', {'num', 'time'}) count = count + 1; if count ~= 2 f = char(f) ; fprintf(' %s:', f) ; fprintf(' %.3f', stats.(f)) ; end 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
Steganalysis-CNN/CNN-without-BN-master
vl_compile.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_noprefix.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_pegasos.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_svmpegasos.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_override.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_quickvis.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_demo_aib.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_demo_alldist.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_demo_ikmeans.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_demo_svm.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_demo_kdtree_sift.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_impattern.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_tpsu.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_xyz2lab.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_gmm.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_twister.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_kdtree.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_imwbackward.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_alphanum.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_printsize.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_cummax.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_imintegral.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_sift.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_binsum.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_lbp.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_colsubset.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_alldist.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_ihashsum.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_grad.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_whistc.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_roc.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_dsift.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_alldist2.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_fisher.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_imsmooth.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_svmtrain.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_phow.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_kmeans.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_hikmeans.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_aib.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_plotbox.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_imarray.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_homkermap.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_slic.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_ikmeans.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_mser.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_inthist.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_imdisttf.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_vlad.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_pr.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_hog.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_argparse.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_liop.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_test_binsearch.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_roc.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_click.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_pr.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_ubcread.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_frame2oell.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_plotsiftdescriptor.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
phow_caltech101.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
sift_mosaic.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
encodeImage.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
experiments.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
getDenseSIFT.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
test_examples.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
simplenn_caffe_compare.m
.m
CNN-without-BN-master/dependencies/matconvnet/utils/simplenn_caffe_compare.m
5,638
utf_8
8e9862ffbf247836e6ff7579d1e6dc85
function diffStats = simplenn_caffe_compare( net, caffeModelBaseName, testData, varargin) % SIMPLENN_CAFFE_COMPARE compare the simplenn network and caffe models % SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME) Evaluates a forward % pass of a simplenn network NET and caffe models stored in % CAFFE_BASE_MODELNAME and numerically compares the network outputs using % a random input data. % % SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME, TEST_DATA) Evaluates % the simplenn network and Caffe model on a given data. If TEST_DATA is % an empty array, uses a random input. % % RES = SIMPLENN_CAFFE_COMPARE(...) returns a structure with the % statistics of the differences where each field of a structure RES is % named after a blob and contains basic statistics: % `[MIN_DIFF, MEAN_DIFF, MAX_DIFF]` % % This script attempts to match the NET layer names and caffe blob names % and shows the MIN, MEAN and MAX difference between the outputs. For % caffe model, the mean image stored with the caffe model is used (see % `simplenn_caffe_deploy` for details). Furthermore the script compares % the execution time of both networks. % % Compiled MatCaffe (usually located in `<caffe_dir>/matlab`, built % with the `matcaffe` target) must be in path. % % SIMPLENN_CAFFE_COMPARE(..., 'OPT', VAL, ...) takes the following % options: % % `numRepetitions`:: `1` % Evaluate the network multiple times. Useful to compare the execution % time. % % `device`:: `cpu` % Evaluate the network on the specified device (CPU or GPU). For GPU % evaluation, the current GPU is used for both Caffe and simplenn. % % `silent`:: `false` % When true, supress all outputs to stdin. % % See Also: simplenn_caffe_deploy % Copyright (C) 2016 Karel Lenc, Zohar Bar-Yehuda % 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.numRepetitions = 1; opts.randScale = 100; opts.device = 'cpu'; opts.silent = false; opts = vl_argparse(opts, varargin); info = @(varargin) fprintf(1, varargin{:}); if opts.silent, info = @(varargin) []; end; if ~exist('caffe.Net', 'class'), error('MatCaffe not in path.'); end prototxtFilename = [caffeModelBaseName '.prototxt']; if ~exist(prototxtFilename, 'file') error('Caffe net definition `%s` not found', prototxtFilename); end; modelFilename = [caffeModelBaseName '.caffemodel']; if ~exist(prototxtFilename, 'file') error('Caffe net model `%s` not found', modelFilename); end; meanFilename = [caffeModelBaseName, '_mean_image.binaryproto']; net = vl_simplenn_tidy(net); net = vl_simplenn_move(net, opts.device); netBlobNames = [{'data'}, cellfun(@(l) l.name, net.layers, ... 'UniformOutput', false)]; % Load the Caffe model caffeNet = caffe.Net(prototxtFilename, modelFilename, 'test'); switch opts.device case 'cpu' caffe.set_mode_cpu(); case 'gpu' caffe.set_mode_gpu(); gpuDev = gpuDevice(); caffe.set_device(gpuDev.Index - 1); end caffeBlobNames = caffeNet.blob_names'; [caffeLayerFound, caffe2netres] = ismember(caffeBlobNames, netBlobNames); info('Found %d matches between simplenn layers and caffe blob names.\n',... sum(caffeLayerFound)); % If testData not supplied, use random input imSize = net.meta.normalization.imageSize; if ~exist('testData', 'var') || isempty(testData) testData = rand(imSize, 'single') * opts.randScale; end if ischar(testData), testData = imread(testData); end testDataSize = [size(testData), 1, 1]; assert(all(testDataSize(1:3) == imSize(1:3)), 'Invalid test data size.'); testData = single(testData); dataCaffe = matlab_img_to_caffe(testData); if isfield(net.meta.normalization, 'averageImage') && ... ~isempty(net.meta.normalization.averageImage) avImage = net.meta.normalization.averageImage; if numel(avImage) == imSize(3) avImage = reshape(avImage, 1, 1, imSize(3)); end testData = bsxfun(@minus, testData, avImage); end % Test MatConvNet model stime = tic; for rep = 1:opts.numRepetitions res = vl_simplenn(net, testData, [], [], 'ConserveMemory', false); end info('MatConvNet %s time: %.1f ms.\n', opts.device, ... toc(stime)/opts.numRepetitions*1000); if ~isempty(meanFilename) && exist(meanFilename, 'file') mean_img_caffe = caffe.io.read_mean(meanFilename); dataCaffe = bsxfun(@minus, dataCaffe, mean_img_caffe); end % Test Caffe model stime = tic; for rep = 1:opts.numRepetitions caffeNet.forward({dataCaffe}); end info('Caffe %s time: %.1f ms.\n', opts.device, ... toc(stime)/opts.numRepetitions*1000); diffStats = struct(); for li = 1:numel(caffeBlobNames) blob = caffeNet.blobs(caffeBlobNames{li}); caffeData = permute(blob.get_data(), [2, 1, 3, 4]); if li == 1 && size(caffeData, 3) == 3 caffeData = caffeData(:, :, [3, 2, 1]); end mcnData = gather(res(caffe2netres(li)).x); diff = abs(caffeData(:) - mcnData(:)); diffStats.(caffeBlobNames{li}) = [min(diff), mean(diff), max(diff)]'; end if ~opts.silent pp = '% 10s % 10s % 10s % 10s\n'; precp = '% 10.2e'; fprintf(pp, 'Layer name', 'Min', 'Mean', 'Max'); for li = 1:numel(caffeBlobNames) lstats = diffStats.(caffeBlobNames{li}); fprintf(pp, caffeBlobNames{li}, sprintf(precp, lstats(1)), ... sprintf(precp, lstats(2)), sprintf(precp, lstats(3))); end fprintf('\n'); end end function img = matlab_img_to_caffe(img) img = single(img); % Convert from HxWxCxN to WxHxCxN per Caffe's convention img = permute(img, [2 1 3 4]); if size(img,3) == 3 % Convert from RGB to BGR channel order per Caffe's convention img = img(:,:, [3 2 1], :); end end
github
Steganalysis-CNN/CNN-without-BN-master
cnn_train_dag.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/cnn_train_dag.m
13,639
utf_8
d07b353a98ae0de8b5ee7be804801741
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.saveMomentum = true ; opts.nesterovUpdate = false ; opts.randomSeed = 0 ; opts.profile = false ; opts.parameterServer.method = 'mmap' ; opts.parameterServer.prefix = 'mcn' ; 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.imdb.images.set==1) ; end if isempty(opts.val), opts.val = find(imdb.imdb.images.set==2) ; end if isnan(opts.train), opts.train = [] ; end if isnan(opts.val), opts.val = [] ; end % ------------------------------------------------------------------------- % Initialization % ------------------------------------------------------------------------- evaluateMode = isempty(opts.train) ; if ~evaluateMode if isempty(opts.derOutputs) error('DEROUTPUTS must be specified when training.\n') ; end end % ------------------------------------------------------------------------- % 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, state, stats] = loadState(modelPath(start)) ; else state = [] ; 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. params = opts ; params.epoch = epoch ; params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ; params.train = opts.train(randperm(numel(opts.train))) ; % shuffle params.val = opts.val(randperm(numel(opts.val))) ; params.imdb = imdb ; params.getBatch = getBatch ; if numel(opts.gpus) <= 1 [net, state] = processEpoch(net, state, params, 'train') ; [net, state] = processEpoch(net, state, params, 'val') ; if ~evaluateMode saveState(modelPath(epoch), net, state) ; end lastStats = state.stats ; else spmd [net, state] = processEpoch(net, state, params, 'train') ; [net, state] = processEpoch(net, state, params, 'val') ; if labindex == 1 && ~evaluateMode saveState(modelPath(epoch), net, state) ; end lastStats = state.stats ; end lastStats = accumulateStats(lastStats) ; end stats.train(epoch) = lastStats.train ; stats.val(epoch) = lastStats.val ; clear lastStats ; saveStats(modelPath(epoch), stats) ; 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 % With multiple GPUs, return one copy if isa(net, 'Composite'), net = net{1} ; end % ------------------------------------------------------------------------- function [net, state] = processEpoch(net, state, params, mode) % ------------------------------------------------------------------------- % Note that net is not strictly needed as an output argument as net % is a handle class. However, this fixes some aliasing issue in the % spmd caller. % initialize with momentum 0 if isempty(state) || isempty(state.momentum) state.momentum = num2cell(zeros(1, numel(net.params))) ; end % move CNN to GPU as needed numGpus = numel(params.gpus) ; if numGpus >= 1 net.move('gpu') ; state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ; end if numGpus > 1 parserv = ParameterServer(params.parameterServer) ; net.setParameterServer(parserv) ; else parserv = [] ; end % profile if params.profile if numGpus <= 1 profile clear ; profile on ; else mpiprofile reset ; mpiprofile on ; end end num = 0 ; epoch = params.epoch ; subset = params.(mode) ; adjustTime = 0 ; stats.num = 0 ; % return something even if subset = [] stats.time = 0 ; start = tic ; for t=1:params.batchSize:numel(subset) fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ... fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ; batchSize = min(params.batchSize, numel(subset) - t + 1) ; for s=1:params.numSubBatches % get this image batch and prefetch the next batchStart = t + (labindex-1) + (s-1) * numlabs ; batchEnd = min(t+params.batchSize-1, numel(subset)) ; batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ; num = num + numel(batch) ; if numel(batch) == 0, continue ; end inputs = params.getBatch(params.imdb, batch) ; if params.prefetch if s == params.numSubBatches batchStart = t + (labindex-1) + params.batchSize ; batchEnd = min(t+2*params.batchSize-1, numel(subset)) ; else batchStart = batchStart + numlabs ; end nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ; params.getBatch(params.imdb, nextBatch) ; end if strcmp(mode, 'train') net.mode = 'normal' ; net.accumulateParamDers = (s ~= 1) ; net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ; else net.mode = 'test' ; net.eval(inputs) ; end end % Accumulate gradient. if strcmp(mode, 'train') if ~isempty(parserv), parserv.sync() ; end state = accumulateGradients(net, state, params, batchSize, parserv) ; end % Get statistics. time = toc(start) + adjustTime ; batchTime = time - stats.time ; stats.num = num ; stats.time = time ; stats = params.extractStatsFn(stats,net) ; currentSpeed = batchSize / batchTime ; averageSpeed = (t + batchSize - 1) / time ; if t == 3*params.batchSize + 1 % compensate for the first three iterations, which are outliers adjustTime = 4*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: %.3f', f, stats.(f)) ; end fprintf('\n') ; end % Save back to state. state.stats.(mode) = stats ; if params.profile if numGpus <= 1 state.prof.(mode) = profile('info') ; profile off ; else state.prof.(mode) = mpiprofile('info'); mpiprofile off ; end end if ~params.saveMomentum state.momentum = [] ; else state.momentum = cellfun(@gather, state.momentum, 'uniformoutput', false) ; end net.reset() ; net.move('cpu') ; % ------------------------------------------------------------------------- function state = accumulateGradients(net, state, params, batchSize, parserv) % ------------------------------------------------------------------------- numGpus = numel(params.gpus) ; otherGpus = setdiff(1:numGpus, labindex) ; for p=1:numel(net.params) if ~isempty(parserv) parDer = parserv.pullWithIndex(p) ; else parDer = net.params(p).der ; end switch net.params(p).trainMethod case 'average' % mainly for batch normalization thisLR = net.params(p).learningRate ; net.params(p).value = vl_taccum(... 1 - thisLR, net.params(p).value, ... (thisLR/batchSize/net.params(p).fanout), parDer) ; case 'gradient' thisDecay = params.weightDecay * net.params(p).weightDecay ; thisLR = params.learningRate * net.params(p).learningRate ; if thisLR>0 || thisDecay>0 % Normalize gradient and incorporate weight decay. parDer = vl_taccum(1/batchSize, parDer, ... thisDecay, net.params(p).value) ; % Update momentum. state.momentum{p} = vl_taccum(... params.momentum, state.momentum{p}, ... -1, parDer) ; % Nesterov update (aka one step ahead). if params.nesterovUpdate delta = vl_taccum(... params.momentum, state.momentum{p}, ... -1, parDer) ; else delta = state.momentum{p} ; end % Update parameters. net.params(p).value = vl_taccum(... 1, net.params(p).value, thisLR, delta) ; end otherwise error('Unknown training method ''%s'' for parameter ''%s''.', ... net.params(p).trainMethod, ... net.params(p).name) ; end end % ------------------------------------------------------------------------- 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(stats, net) % ------------------------------------------------------------------------- sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ; for i = 1:numel(sel) stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ; end % ------------------------------------------------------------------------- function saveState(fileName, net_, state) % ------------------------------------------------------------------------- net = net_.saveobj() ; save(fileName, 'net', 'state') ; % ------------------------------------------------------------------------- function saveStats(fileName, stats) % ------------------------------------------------------------------------- if exist(fileName) save(fileName, 'stats', '-append') ; else save(fileName, 'stats') ; end % ------------------------------------------------------------------------- function [net, state, stats] = loadState(fileName) % ------------------------------------------------------------------------- load(fileName, 'net', 'state', 'stats') ; net = dagnn.DagNN.loadobj(net) ; if isempty(whos('stats')) error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ... fileName) ; end % ------------------------------------------------------------------------- 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 clearMex() % ------------------------------------------------------------------------- clear vl_tmove vl_imreadjpeg ; % ------------------------------------------------------------------------- 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 end if numGpus >= 1 && cold fprintf('%s: resetting GPU\n', mfilename) clearMex() ; if numGpus == 1 gpuDevice(opts.gpus) else spmd clearMex() ; gpuDevice(opts.gpus(labindex)) end end end
github
Steganalysis-CNN/CNN-without-BN-master
cnn_train.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/cnn_train.m
19,153
utf_8
c6c0c0c8532f9c3653af4410497f80c3
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.saveMomentum = true ; opts.nesterovUpdate = false ; opts.randomSeed = 0 ; opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ; opts.profile = false ; opts.parameterServer.method = 'mmap' ; opts.parameterServer.prefix = 'mcn' ; 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) J = numel(net.layers{i}.weights) ; if ~isfield(net.layers{i}, 'learningRate') net.layers{i}.learningRate = ones(1, J) ; end if ~isfield(net.layers{i}, 'weightDecay') net.layers{i}.weightDecay = ones(1, J) ; 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, state, stats] = loadState(modelPath(start)) ; else state = [] ; 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. params = opts ; params.epoch = epoch ; params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ; params.train = opts.train(randperm(numel(opts.train))) ; % shuffle params.val = opts.val(randperm(numel(opts.val))) ; params.imdb = imdb ; params.getBatch = getBatch ; if numel(params.gpus) <= 1 [net, state] = processEpoch(net, state, params, 'train') ; [net, state] = processEpoch(net, state, params, 'val') ; if ~evaluateMode saveState(modelPath(epoch), net, state) ; end lastStats = state.stats ; else spmd [net, state] = processEpoch(net, state, params, 'train') ; [net, state] = processEpoch(net, state, params, 'val') ; if labindex == 1 && ~evaluateMode saveState(modelPath(epoch), net, state) ; end lastStats = state.stats ; end lastStats = accumulateStats(lastStats) ; end stats.train(epoch) = lastStats.train ; stats.val(epoch) = lastStats.val ; clear lastStats ; saveStats(modelPath(epoch), stats) ; if params.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 % With multiple GPUs, return one copy if isa(net, 'Composite'), net = net{1} ; end % ------------------------------------------------------------------------- function err = error_multiclass(params, 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(params, labels, res) % ------------------------------------------------------------------------- predictions = gather(res(end-1).x) ; error = bsxfun(@times, predictions, labels) < 0 ; err = sum(error(:)) ; % ------------------------------------------------------------------------- function err = error_none(params, labels, res) % ------------------------------------------------------------------------- err = zeros(0,1) ; % ------------------------------------------------------------------------- function [net, state] = processEpoch(net, state, params, mode) % ------------------------------------------------------------------------- % Note that net is not strictly needed as an output argument as net % is a handle class. However, this fixes some aliasing issue in the % spmd caller. % initialize with momentum 0 if isempty(state) || isempty(state.momentum) for i = 1:numel(net.layers) for j = 1:numel(net.layers{i}.weights) state.momentum{i}{j} = 0 ; end end end % move CNN to GPU as needed numGpus = numel(params.gpus) ; if numGpus >= 1 net = vl_simplenn_move(net, 'gpu') ; for i = 1:numel(state.momentum) for j = 1:numel(state.momentum{i}) state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ; end end end if numGpus > 1 parserv = ParameterServer(params.parameterServer) ; vl_simplenn_start_parserv(net, parserv) ; else parserv = [] ; end % profile if params.profile if numGpus <= 1 profile clear ; profile on ; else mpiprofile reset ; mpiprofile on ; end end subset = params.(mode) ; num = 0 ; stats.num = 0 ; % return something even if subset = [] stats.time = 0 ; adjustTime = 0 ; res = [] ; error = [] ; start = tic ; for t=1:params.batchSize:numel(subset) fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ... fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ; batchSize = min(params.batchSize, numel(subset) - t + 1) ; for s=1:params.numSubBatches % get this image batch and prefetch the next batchStart = t + (labindex-1) + (s-1) * numlabs ; batchEnd = min(t+params.batchSize-1, numel(subset)) ; batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ; num = num + numel(batch) ; if numel(batch) == 0, continue ; end [im, labels] = params.getBatch(params.imdb, batch) ; if params.prefetch if s == params.numSubBatches batchStart = t + (labindex-1) + params.batchSize ; batchEnd = min(t+2*params.batchSize-1, numel(subset)) ; else batchStart = batchStart + numlabs ; end nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ; params.getBatch(params.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', params.conserveMemory, ... 'backPropDepth', params.backPropDepth, ... 'sync', params.sync, ... 'cudnn', params.cudnn, ... 'parameterServer', parserv, ... 'holdOn', s < params.numSubBatches) ; % accumulate errors error = sum([error, [... sum(double(gather(res(end).x))) ; reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ; end % accumulate gradient if strcmp(mode, 'train') if ~isempty(parserv), parserv.sync() ; end [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ; end % get statistics time = toc(start) + adjustTime ; batchTime = time - stats.time ; stats = extractStats(net, params, error / num) ; stats.num = num ; stats.time = time ; currentSpeed = batchSize / batchTime ; averageSpeed = (t + batchSize - 1) / time ; if t == 3*params.batchSize + 1 % compensate for the first three iterations, which are outliers adjustTime = 4*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: %.3f', f, stats.(f)) ; end fprintf('\n') ; % collect diagnostic statistics if strcmp(mode, 'train') && params.plotDiagnostics switchFigure(2) ; clf ; diagn = [res.stats] ; diagnvar = horzcat(diagn.variation) ; diagnpow = horzcat(diagn.power) ; subplot(2,2,1) ; barh(diagnvar) ; set(gca,'TickLabelInterpreter', 'none', ... 'YTick', 1:numel(diagnvar), ... 'YTickLabel',horzcat(diagn.label), ... 'YDir', 'reverse', ... 'XScale', 'log', ... 'XLim', [1e-5 1], ... 'XTick', 10.^(-5:1)) ; grid on ; subplot(2,2,2) ; barh(sqrt(diagnpow)) ; set(gca,'TickLabelInterpreter', 'none', ... 'YTick', 1:numel(diagnpow), ... 'YTickLabel',{diagn.powerLabel}, ... 'YDir', 'reverse', ... 'XScale', 'log', ... 'XLim', [1e-5 1e5], ... 'XTick', 10.^(-5:5)) ; grid on ; subplot(2,2,3); plot(squeeze(res(end-1).x)) ; drawnow ; end end % Save back to state. state.stats.(mode) = stats ; if params.profile if numGpus <= 1 state.prof.(mode) = profile('info') ; profile off ; else state.prof.(mode) = mpiprofile('info'); mpiprofile off ; end end if ~params.saveMomentum state.momentum = [] ; else for i = 1:numel(state.momentum) for j = 1:numel(state.momentum{i}) state.momentum{i}{j} = gather(state.momentum{i}{j}) ; end end end net = vl_simplenn_move(net, 'cpu') ; % ------------------------------------------------------------------------- function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) % ------------------------------------------------------------------------- numGpus = numel(params.gpus) ; otherGpus = setdiff(1:numGpus, labindex) ; for l=numel(net.layers):-1:1 for j=numel(res(l).dzdw):-1:1 if ~isempty(parserv) tag = sprintf('l%d_%d',l,j) ; parDer = parserv.pull(tag) ; else parDer = res(l).dzdw{j} ; 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} = vl_taccum(... 1 - thisLR, ... net.layers{l}.weights{j}, ... thisLR / batchSize, ... parDer) ; else % Standard gradient training. thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ; thisLR = params.learningRate * net.layers{l}.learningRate(j) ; if thisLR>0 || thisDecay>0 % Normalize gradient and incorporate weight decay. parDer = vl_taccum(1/batchSize, parDer, ... thisDecay, net.layers{l}.weights{j}) ; % Update momentum. state.momentum{l}{j} = vl_taccum(... params.momentum, state.momentum{l}{j}, ... -1, parDer) ; % Nesterov update (aka one step ahead). if params.nesterovUpdate delta = vl_taccum(... params.momentum, state.momentum{l}{j}, ... -1, parDer) ; else delta = state.momentum{l}{j} ; end % Update parameters. net.layers{l}.weights{j} = vl_taccum(... 1, net.layers{l}.weights{j}, ... thisLR, delta) ; end end % if requested, collect some useful stats for debugging if params.plotDiagnostics variation = [] ; label = '' ; switch net.layers{l}.type case {'conv','convt'} variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ; power = mean(res(l+1).x(:).^2) ; if j == 1 % fiters base = mean(net.layers{l}.weights{j}(:).^2) ; label = 'filters' ; else % biases base = sqrt(power) ;%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.power = power ; res(l).stats.powerLabel = net.layers{l}.name ; res(l).stats.label{j} = label ; end end end % ------------------------------------------------------------------------- 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, params, errors) % ------------------------------------------------------------------------- stats.objective = errors(1) ; for i = 1:numel(params.errorLabels) stats.(params.errorLabels{i}) = errors(i+1) ; end % ------------------------------------------------------------------------- function saveState(fileName, net, state) % ------------------------------------------------------------------------- save(fileName, 'net', 'state') ; % ------------------------------------------------------------------------- function saveStats(fileName, stats) % ------------------------------------------------------------------------- if exist(fileName) save(fileName, 'stats', '-append') ; else save(fileName, 'stats') ; end % ------------------------------------------------------------------------- function [net, state, stats] = loadState(fileName) % ------------------------------------------------------------------------- load(fileName, 'net', 'state', 'stats') ; net = vl_simplenn_tidy(net) ; if isempty(whos('stats')) error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ... fileName) ; end % ------------------------------------------------------------------------- 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 clearMex() % ------------------------------------------------------------------------- %clear vl_tmove vl_imreadjpeg ; disp('Clearing mex files') ; clear mex ; clear vl_tmove vl_imreadjpeg ; % ------------------------------------------------------------------------- function prepareGPUs(params, cold) % ------------------------------------------------------------------------- numGpus = numel(params.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 end if numGpus >= 1 && cold fprintf('%s: resetting GPU\n', mfilename) ; clearMex() ; if numGpus == 1 disp(gpuDevice(params.gpus)) ; else spmd clearMex() ; disp(gpuDevice(params.gpus(labindex))) ; end end end
github
Steganalysis-CNN/CNN-without-BN-master
cnn_stn_cluttered_mnist.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
fast_rcnn_train.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/fast_rcnn/fast_rcnn_train.m
6,399
utf_8
54b0bc7fa26d672ed6673d3f1832944e
function [net, info] = fast_rcnn_train(varargin) %FAST_RCNN_TRAIN Demonstrates training a Fast-RCNN detector % Copyright (C) 2016 Hakan Bilen. % 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). run(fullfile(fileparts(mfilename('fullpath')), ... '..', '..', 'matlab', 'vl_setupnn.m')) ; addpath(fullfile(vl_rootnn,'examples','fast_rcnn','bbox_functions')); addpath(fullfile(vl_rootnn,'examples','fast_rcnn','datasets')); opts.dataDir = fullfile(vl_rootnn, 'data') ; opts.sswDir = fullfile(vl_rootnn, 'data', 'SSW'); opts.expDir = fullfile(vl_rootnn, 'data', 'fast-rcnn-vgg16-pascal07') ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.modelPath = fullfile(opts.dataDir, 'models', ... 'imagenet-vgg-verydeep-16.mat') ; opts.piecewise = true; % piecewise training (+bbox regression) opts.train.gpus = [] ; opts.train.batchSize = 2 ; opts.train.numSubBatches = 1 ; opts.train.continue = true ; opts.train.prefetch = false ; % does not help for two images in a batch opts.train.learningRate = 1e-3 / 64 * [ones(1,6) 0.1*ones(1,6)]; opts.train.weightDecay = 0.0005 ; opts.train.numEpochs = 12 ; opts.train.derOutputs = {'losscls', 1, 'lossbbox', 1} ; opts.lite = false ; opts.numFetchThreads = 2 ; opts = vl_argparse(opts, varargin) ; display(opts); opts.train.expDir = opts.expDir ; opts.train.numEpochs = numel(opts.train.learningRate) ; % ------------------------------------------------------------------------- % Network initialization % ------------------------------------------------------------------------- net = fast_rcnn_init(... 'piecewise',opts.piecewise,... 'modelPath',opts.modelPath); % ------------------------------------------------------------------------- % Database initialization % ------------------------------------------------------------------------- if exist(opts.imdbPath,'file') == 2 fprintf('Loading imdb...'); imdb = load(opts.imdbPath) ; else if ~exist(opts.expDir,'dir') mkdir(opts.expDir); end fprintf('Setting VOC2007 up, this may take a few minutes\n'); imdb = cnn_setup_data_voc07_ssw(... 'dataDir', opts.dataDir, ... 'sswDir', opts.sswDir, ... 'addFlipped', true, ... 'useDifficult', true) ; save(opts.imdbPath,'-struct', 'imdb','-v7.3'); fprintf('\n'); end fprintf('done\n'); % -------------------------------------------------------------------- % Train % -------------------------------------------------------------------- % use train + val split to train imdb.images.set(imdb.images.set == 2) = 1; % minibatch options bopts = net.meta.normalization; bopts.useGpu = numel(opts.train.gpus) > 0 ; bopts.numFgRoisPerImg = 16; bopts.numRoisPerImg = 64; bopts.maxScale = 1000; bopts.scale = 600; bopts.bgLabel = numel(imdb.classes.name)+1; bopts.visualize = 0; bopts.interpolation = net.meta.normalization.interpolation; bopts.numThreads = opts.numFetchThreads; bopts.prefetch = opts.train.prefetch; [net,info] = cnn_train_dag(net, imdb, @(i,b) ... getBatch(bopts,i,b), ... opts.train) ; % -------------------------------------------------------------------- % Deploy % -------------------------------------------------------------------- modelPath = fullfile(opts.expDir, 'net-deployed.mat'); if ~exist(modelPath,'file') net = deployFRCNN(net,imdb); net_ = net.saveobj() ; save(modelPath, '-struct', 'net_') ; clear net_ ; end % -------------------------------------------------------------------- function inputs = getBatch(opts, imdb, batch) % -------------------------------------------------------------------- opts.visualize = 0; if isempty(batch) return; end images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; opts.prefetch = (nargout == 0); [im,rois,labels,btargets] = fast_rcnn_train_get_batch(images,imdb,... batch, opts); if opts.prefetch, return; end nb = numel(labels); nc = numel(imdb.classes.name) + 1; % regression error only for positives instance_weights = zeros(1,1,4*nc,nb,'single'); targets = zeros(1,1,4*nc,nb,'single'); for b=1:nb if labels(b)>0 && labels(b)~=opts.bgLabel targets(1,1,4*(labels(b)-1)+1:4*labels(b),b) = btargets(b,:)'; instance_weights(1,1,4*(labels(b)-1)+1:4*labels(b),b) = 1; end end rois = single(rois); if opts.useGpu > 0 im = gpuArray(im) ; rois = gpuArray(rois) ; targets = gpuArray(targets) ; instance_weights = gpuArray(instance_weights) ; end inputs = {'input', im, 'label', labels, 'rois', rois, 'targets', targets, ... 'instance_weights', instance_weights} ; % -------------------------------------------------------------------- function net = deployFRCNN(net,imdb) % -------------------------------------------------------------------- % function net = deployFRCNN(net) for l = numel(net.layers):-1:1 if isa(net.layers(l).block, 'dagnn.Loss') || ... isa(net.layers(l).block, 'dagnn.DropOut') layer = net.layers(l); net.removeLayer(layer.name); net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ; end end net.rebuild(); pfc8 = net.getLayerIndex('predcls') ; net.addLayer('probcls',dagnn.SoftMax(),net.layers(pfc8).outputs{1},... 'probcls',{}); net.vars(net.getVarIndex('probcls')).precious = true ; idxBox = net.getLayerIndex('predbbox') ; if ~isnan(idxBox) net.vars(net.layers(idxBox).outputIndexes(1)).precious = true ; % incorporate mean and std to bbox regression parameters blayer = net.layers(idxBox) ; filters = net.params(net.getParamIndex(blayer.params{1})).value ; biases = net.params(net.getParamIndex(blayer.params{2})).value ; boxMeans = single(imdb.boxes.bboxMeanStd{1}'); boxStds = single(imdb.boxes.bboxMeanStd{2}'); net.params(net.getParamIndex(blayer.params{1})).value = ... bsxfun(@times,filters,... reshape([boxStds(:)' zeros(1,4,'single')]',... [1 1 1 4*numel(net.meta.classes.name)])); biases = biases .* [boxStds(:)' zeros(1,4,'single')]; net.params(net.getParamIndex(blayer.params{2})).value = ... bsxfun(@plus,biases, [boxMeans(:)' zeros(1,4,'single')]); end net.mode = 'test' ;
github
Steganalysis-CNN/CNN-without-BN-master
fast_rcnn_evaluate.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/fast_rcnn/fast_rcnn_evaluate.m
6,941
utf_8
a54a3f8c3c8e5a8ff7ebe4e2b12ede30
function [aps, speed] = fast_rcnn_evaluate(varargin) %FAST_RCNN_EVALUATE Evaluate a trained Fast-RCNN model on PASCAL VOC 2007 % Copyright (C) 2016 Hakan Bilen. % 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). run(fullfile(fileparts(mfilename('fullpath')), ... '..', '..', 'matlab', 'vl_setupnn.m')) ; addpath(fullfile(vl_rootnn, 'data', 'VOCdevkit', 'VOCcode')); addpath(genpath(fullfile(vl_rootnn, 'examples', 'fast_rcnn'))); opts.dataDir = fullfile(vl_rootnn, 'data') ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.sswDir = fullfile(opts.dataDir, 'SSW'); opts.expDir = fullfile(opts.dataDir, 'fast-rcnn-vgg16-pascal07') ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.modelPath = fullfile(opts.expDir, 'net-deployed.mat') ; opts.gpu = [] ; opts.numFetchThreads = 1 ; opts.nmsThresh = 0.3 ; opts.maxPerImage = 100 ; opts = vl_argparse(opts, varargin) ; display(opts) ; if ~exist(opts.expDir,'dir') mkdir(opts.expDir) ; end if ~isempty(opts.gpu) gpuDevice(opts.gpu) end % ------------------------------------------------------------------------- % Network initialization % ------------------------------------------------------------------------- net = dagnn.DagNN.loadobj(load(opts.modelPath)) ; net.mode = 'test' ; if ~isempty(opts.gpu) net.move('gpu') ; end % ------------------------------------------------------------------------- % Database initialization % ------------------------------------------------------------------------- if exist(opts.imdbPath,'file') fprintf('Loading precomputed imdb...\n'); imdb = load(opts.imdbPath) ; else fprintf('Obtaining dataset and imdb...\n'); imdb = cnn_setup_data_voc07_ssw(... 'dataDir',opts.dataDir,... 'sswDir',opts.sswDir); save(opts.imdbPath,'-struct', 'imdb','-v7.3'); end fprintf('done\n'); bopts.averageImage = net.meta.normalization.averageImage; bopts.useGpu = numel(opts.gpu) > 0 ; bopts.maxScale = 1000; bopts.bgLabel = 21; bopts.visualize = 0; bopts.scale = 600; bopts.interpolation = net.meta.normalization.interpolation; bopts.numThreads = opts.numFetchThreads; % ------------------------------------------------------------------------- % Evaluate % ------------------------------------------------------------------------- VOCinit; VOCopts.testset='test'; testIdx = find(imdb.images.set == 3) ; cls_probs = cell(1,numel(testIdx)) ; box_deltas = cell(1,numel(testIdx)) ; boxscores_nms = cell(numel(VOCopts.classes),numel(testIdx)) ; ids = cell(numel(VOCopts.classes),numel(testIdx)) ; dataVar = 'input' ; probVarI = net.getVarIndex('probcls') ; boxVarI = net.getVarIndex('predbbox') ; if isnan(probVarI) dataVar = 'data' ; probVarI = net.getVarIndex('cls_prob') ; boxVarI = net.getVarIndex('bbox_pred') ; end net.vars(probVarI).precious = true ; net.vars(boxVarI).precious = true ; start = tic ; for t=1:numel(testIdx) speed = t/toc(start) ; fprintf('Image %d of %d (%.f HZ)\n', t, numel(testIdx), speed) ; batch = testIdx(t); inputs = getBatch(bopts, imdb, batch); inputs{1} = dataVar ; net.eval(inputs) ; cls_probs{t} = squeeze(gather(net.vars(probVarI).value)) ; box_deltas{t} = squeeze(gather(net.vars(boxVarI).value)) ; end % heuristic: keep an average of 40 detections per class per images prior % to NMS max_per_set = 40 * numel(testIdx); % detection thresold for each class (this is adaptively set based on the % max_per_set constraint) cls_thresholds = zeros(1,numel(VOCopts.classes)); cls_probs_concat = horzcat(cls_probs{:}); for c = 1:numel(VOCopts.classes) q = find(strcmp(VOCopts.classes{c}, net.meta.classes.name)) ; so = sort(cls_probs_concat(q,:),'descend'); cls_thresholds(q) = so(min(max_per_set,numel(so))); fprintf('Applying NMS for %s\n',VOCopts.classes{c}); for t=1:numel(testIdx) si = find(cls_probs{t}(q,:) >= cls_thresholds(q)) ; if isempty(si), continue; end cls_prob = cls_probs{t}(q,si)'; pbox = imdb.boxes.pbox{testIdx(t)}(si,:); % back-transform bounding box corrections delta = box_deltas{t}(4*(q-1)+1:4*q,si)'; pred_box = bbox_transform_inv(pbox, delta); im_size = imdb.images.size(testIdx(t),[2 1]); pred_box = bbox_clip(round(pred_box), im_size); % Threshold. Heuristic: keep at most 100 detection per class per image % prior to NMS. boxscore = [pred_box cls_prob]; [~,si] = sort(boxscore(:,5),'descend'); boxscore = boxscore(si,:); boxscore = boxscore(1:min(size(boxscore,1),opts.maxPerImage),:); % NMS pick = bbox_nms(double(boxscore),opts.nmsThresh); boxscores_nms{c,t} = boxscore(pick,:) ; ids{c,t} = repmat({imdb.images.name{testIdx(t)}(1:end-4)},numel(pick),1) ; if 0 figure(1) ; clf ; idx = boxscores_nms{c,t}(:,5)>0.5; if sum(idx)==0, continue; end bbox_draw(imread(fullfile(imdb.imageDir,imdb.images.name{testIdx(t)})), ... boxscores_nms{c,t}(idx,:)) ; title(net.meta.classes.name{q}) ; drawnow ; pause; %keyboard end end end %% PASCAL VOC evaluation VOCdevkitPath = fullfile(vl_rootnn,'data','VOCdevkit'); aps = zeros(numel(VOCopts.classes),1); % fix voc folders VOCopts.imgsetpath = fullfile(VOCdevkitPath,'VOC2007','ImageSets','Main','%s.txt'); VOCopts.annopath = fullfile(VOCdevkitPath,'VOC2007','Annotations','%s.xml'); VOCopts.localdir = fullfile(VOCdevkitPath,'local','VOC2007'); VOCopts.detrespath = fullfile(VOCdevkitPath, 'results', 'VOC2007', 'Main', ['%s_det_', VOCopts.testset, '_%s.txt']); % write det results to txt files for c=1:numel(VOCopts.classes) fid = fopen(sprintf(VOCopts.detrespath,'comp3',VOCopts.classes{c}),'w'); for i=1:numel(testIdx) if isempty(boxscores_nms{c,i}), continue; end dets = boxscores_nms{c,i}; for j=1:size(dets,1) fprintf(fid,'%s %.6f %d %d %d %d\n', ... imdb.images.name{testIdx(i)}(1:end-4), ... dets(j,5),dets(j,1:4)) ; end end fclose(fid); [rec,prec,ap] = VOCevaldet(VOCopts,'comp3',VOCopts.classes{c},0); fprintf('%s ap %.1f\n',VOCopts.classes{c},100*ap); aps(c) = ap; end fprintf('mean ap %.1f\n',100*mean(aps)); % -------------------------------------------------------------------- function inputs = getBatch(opts, imdb, batch) % -------------------------------------------------------------------- if isempty(batch) return; end images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ; opts.prefetch = (nargout == 0); [im,rois] = fast_rcnn_eval_get_batch(images, imdb, batch, opts); rois = single(rois); if opts.useGpu > 0 im = gpuArray(im) ; rois = gpuArray(rois) ; end inputs = {'input', im, 'rois', rois} ;
github
Steganalysis-CNN/CNN-without-BN-master
cnn_cifar.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
cnn_cifar_init_nin.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/cifar/cnn_cifar_init_nin.m
5,561
utf_8
aca711e04a8cd82821f658922218368c
function net = cnn_cifar_init_nin(varargin) opts.networkType = 'simplenn' ; opts = vl_argparse(opts, varargin) ; % CIFAR-10 model from % M. Lin, Q. Chen, and S. Yan. Network in network. CoRR, % abs/1312.4400, 2013. % % It reproduces the NIN + Dropout result of Table 1 (<= 10.41% top1 error). net.layers = {} ; lr = [1 10] ; % Block 1 net.layers{end+1} = struct('type', 'conv', ... 'name', 'conv1', ... 'weights', {init_weights(5,3,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 2) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu1') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp1', ... 'weights', {init_weights(1,192,160)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp1') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp2', ... 'weights', {init_weights(1,160,96)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp2') ; net.layers{end+1} = struct('name', 'pool1', ... 'type', 'pool', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout1', 'rate', 0.5) ; % Block 2 net.layers{end+1} = struct('type', 'conv', ... 'name', 'conv2', ... 'weights', {init_weights(5,96,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 2) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu2') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp3', ... 'weights', {init_weights(1,192,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp3') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp4', ... 'weights', {init_weights(1,192,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp4') ; net.layers{end+1} = struct('name', 'pool2', ... 'type', 'pool', ... 'method', 'avg', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout2', 'rate', 0.5) ; % Block 3 net.layers{end+1} = struct('type', 'conv', ... 'name', 'conv3', ... 'weights', {init_weights(3,192,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 1) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu3') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp5', ... 'weights', {init_weights(1,192,192)}, ... 'learningRate', lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp5') ; net.layers{end+1} = struct('type', 'conv', ... 'name', 'cccp6', ... 'weights', {init_weights(1,192,10)}, ... 'learningRate', 0.001*lr, ... 'stride', 1, ... 'pad', 0) ; net.layers{end}.weights{1} = 0.1 * net.layers{end}.weights{1} ; %net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp6') ; net.layers{end+1} = struct('type', 'pool', ... 'name', 'pool3', ... 'method', 'avg', ... 'pool', [7 7], ... 'stride', 1, ... 'pad', 0) ; % Loss layer net.layers{end+1} = struct('type', 'softmaxloss') ; % Meta parameters net.meta.inputSize = [32 32 3] ; net.meta.trainOpts.learningRate = [0.002, 0.01, 0.02, 0.04 * ones(1,80), 0.004 * ones(1,10), 0.0004 * ones(1,10)] ; net.meta.trainOpts.weightDecay = 0.0005 ; net.meta.trainOpts.batchSize = 100 ; net.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate) ; % 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('error', dagnn.Loss('loss', 'classerror'), ... {'prediction','label'}, 'error') ; otherwise assert(false) ; end function weights = init_weights(k,m,n) weights{1} = randn(k,k,m,n,'single') * sqrt(2/(k*k*m)) ; weights{2} = zeros(n,1,'single') ;
github
Steganalysis-CNN/CNN-without-BN-master
cnn_imagenet_init_resnet.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/imagenet/cnn_imagenet_init_resnet.m
6,776
utf_8
2bdef2921f7e7b0733d1a58f724cccdf
function net = cnn_imagenet_init_resnet(varargin) %CNN_IMAGENET_INIT_RESNET Initialize the ResNet-50 model for ImageNet classification opts.classNames = {} ; opts.classDescriptions = {} ; opts.averageImage = zeros(3,1) ; opts.colorDeviation = zeros(3) ; opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB opts = vl_argparse(opts, varargin) ; net = dagnn.DagNN() ; lastAdded.var = 'input' ; lastAdded.depth = 3 ; function Conv(name, ksize, depth, varargin) % Helper function to add a Convolutional + BatchNorm + ReLU % sequence to the network. args.relu = true ; args.downsample = false ; args.bias = false ; args = vl_argparse(args, varargin) ; if args.downsample, stride = 2 ; else stride = 1 ; end if args.bias, pars = {[name '_f'], [name '_b']} ; else pars = {[name '_f']} ; end net.addLayer([name '_conv'], ... dagnn.Conv('size', [ksize ksize lastAdded.depth depth], ... 'stride', stride, .... 'pad', (ksize - 1) / 2, ... 'hasBias', args.bias, ... 'opts', {'cudnnworkspacelimit', opts.cudnnWorkspaceLimit}), ... lastAdded.var, ... [name '_conv'], ... pars) ; net.addLayer([name '_bn'], ... dagnn.BatchNorm('numChannels', depth, 'epsilon', 1e-5), ... [name '_conv'], ... [name '_bn'], ... {[name '_bn_w'], [name '_bn_b'], [name '_bn_m']}) ; lastAdded.depth = depth ; lastAdded.var = [name '_bn'] ; if args.relu net.addLayer([name '_relu'] , ... dagnn.ReLU(), ... lastAdded.var, ... [name '_relu']) ; lastAdded.var = [name '_relu'] ; end end % ------------------------------------------------------------------------- % Add input section % ------------------------------------------------------------------------- Conv('conv1', 7, 64, ... 'relu', true, ... 'bias', false, ... 'downsample', true) ; net.addLayer(... 'conv1_pool' , ... dagnn.Pooling('poolSize', [3 3], ... 'stride', 2, ... 'pad', 1, ... 'method', 'max'), ... lastAdded.var, ... 'conv1') ; lastAdded.var = 'conv1' ; % ------------------------------------------------------------------------- % Add intermediate sections % ------------------------------------------------------------------------- for s = 2:5 switch s case 2, sectionLen = 3 ; case 3, sectionLen = 4 ; % 8 ; case 4, sectionLen = 6 ; % 23 ; % 36 ; case 5, sectionLen = 3 ; end % ----------------------------------------------------------------------- % Add intermediate segments for each section for l = 1:sectionLen depth = 2^(s+4) ; sectionInput = lastAdded ; name = sprintf('conv%d_%d', s, l) ; % Optional adapter layer if l == 1 Conv([name '_adapt_conv'], 1, 2^(s+6), 'downsample', s >= 3, 'relu', false) ; end sumInput = lastAdded ; % ABC: 1x1, 3x3, 1x1; downsample if first segment in section from % section 2 onwards. lastAdded = sectionInput ; %Conv([name 'a'], 1, 2^(s+4), 'downsample', (s >= 3) & l == 1) ; %Conv([name 'b'], 3, 2^(s+4)) ; Conv([name 'a'], 1, 2^(s+4)) ; Conv([name 'b'], 3, 2^(s+4), 'downsample', (s >= 3) & l == 1) ; Conv([name 'c'], 1, 2^(s+6), 'relu', false) ; % Sum layer net.addLayer([name '_sum'] , ... dagnn.Sum(), ... {sumInput.var, lastAdded.var}, ... [name '_sum']) ; net.addLayer([name '_relu'] , ... dagnn.ReLU(), ... [name '_sum'], ... name) ; lastAdded.var = name ; end end net.addLayer('prediction_avg' , ... dagnn.Pooling('poolSize', [7 7], 'method', 'avg'), ... lastAdded.var, ... 'prediction_avg') ; net.addLayer('prediction' , ... dagnn.Conv('size', [1 1 2048 1000]), ... 'prediction_avg', ... 'prediction', ... {'prediction_f', 'prediction_b'}) ; net.addLayer('loss', ... dagnn.Loss('loss', 'softmaxlog') ,... {'prediction', 'label'}, ... 'objective') ; net.addLayer('top1error', ... dagnn.Loss('loss', 'classerror'), ... {'prediction', 'label'}, ... 'top1error') ; net.addLayer('top5error', ... dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ... {'prediction', 'label'}, ... 'top5error') ; % ------------------------------------------------------------------------- % Meta parameters % ------------------------------------------------------------------------- net.meta.normalization.imageSize = [224 224 3] ; net.meta.inputSize = [net.meta.normalization.imageSize, 32] ; net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ; net.meta.normalization.averageImage = opts.averageImage ; net.meta.classes.name = opts.classNames ; net.meta.classes.description = opts.classDescriptions ; net.meta.augmentation.jitterLocation = true ; net.meta.augmentation.jitterFlip = true ; net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ; net.meta.augmentation.jitterAspect = [3/4, 4/3] ; net.meta.augmentation.jitterScale = [0.4, 1.1] ; %net.meta.augmentation.jitterSaturation = 0.4 ; %net.meta.augmentation.jitterContrast = 0.4 ; net.meta.inputSize = {'input', [net.meta.normalization.imageSize 32]} ; %lr = logspace(-1, -3, 60) ; %lr = [0.1 * ones(1,30), 0.01*ones(1,30), 0.001*ones(1,30)] ; lr = [0.1 * ones(1,1), 0.01*ones(1,1), 0.001*ones(1,1)] ; net.meta.trainOpts.learningRate = lr ; net.meta.trainOpts.numEpochs = numel(lr) ; net.meta.trainOpts.momentum = 0.9 ; net.meta.trainOpts.batchSize = 256 ; net.meta.trainOpts.numSubBatches = 4 ; net.meta.trainOpts.weightDecay = 0.0001 ; % Init parameters randomly net.initParams() ; % For uniformity with the other ImageNet networks, t % the input data is *not* normalized to have unit standard deviation, % whereas this is enforced by batch normalization deeper down. % The ImageNet standard deviation (for each of R, G, and B) is about 60, so % we adjust the weights and learing rate accordingly in the first layer. % % This simple change improves performance almost +1% top 1 error. p = net.getParamIndex('conv1_f') ; net.params(p).value = net.params(p).value / 100 ; net.params(p).learningRate = net.params(p).learningRate / 100^2 ; for l = 1:numel(net.layers) if isa(net.layers(l).block, 'dagnn.BatchNorm') k = net.getParamIndex(net.layers(l).params{3}) ; net.params(k).learningRate = 0.3 ; end end end