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
jacksky64/imageProcessing-master
savedatafile.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/savedatafile.m
8,730
utf_8
95058a04ca5983f539f85772424cc56a
%SAVEDATAFILE Save datafile % % B = SAVEDATAFILE(A,FEATSIZE,NAME,NBITS,FILESIZE) % % INPUT % A Datafile, or cell array with datafiles and/or datasets % FEATSIZE Feature size, i.e. image size of a single object in B % Default: as it is. % NAME Desired name of directory % NBITS # of bits in case of rescaling (8,16 or 32) % Default: no rescaling % FILESIZE # of elements stored in a single file % Default 10000000. % % OUTPUT % B New datafile % % The datafile A is completed by desired preprocessing and postprocessing. % It should therefore be convertable to a dataset. It is saved in the % directory NAME and B refers to it. If desired the data and target fields % are compressed (after appropriate rescaling) to NBITS unsigned integers. % The stored datafile can be retrieved by % % B = DATAFILE(NAME) % % B is a 'mature' datafile, i.e. a dataset distributed over a number of % files with maximum size FILESIZE. This has only advantages over a 'raw' % datafile defined for a directory of images in case of substantial pre- % and postprocessing, due to the overhead of the dataset construct of B. % FEATSIZE can be used to reshape the size of object (e.g. from 256 to % [16 16]) % % If A is cell array with datafiles and/or datasets, they are first % horizontally concatenated before the datafile is written. The first % element in A should be a datafile. % % The difference with CREATEDATAFILE is that SAVEDATAFILE assumes that % the datafile after completion by preprocessing can be converted into a % dataset and the data is stored as such and a sompact as possible. % CREATEDATAFILE saves every object in a separate file and is thereby % useful in case preprocessing does not yield a proper dataset with the % same number of features for every object. % % SEE ALSO DATAFILES, DATASETS, CREATEDATAFILE % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function c = savedatafile(dfile_in,featsize,dirr,nbits,filesize) prtrace(mfilename,1); if iscell(dfile_in) b = dfile_in{1}; [m,k] = size(b); for j=2:length(dfile_in(:)) if size(dfile_in{j},1) ~= m error('Datafiles or datasets to be combined should have equal number of objects') end k = k+size(dfile_in{j},2); end else b = dfile_in; [m,k] = size(b); end isvaldfile(b); c = b; if nargin < 5 % maximum nr of elements in datafile filesize = 1000000; end if nargin < 4 | isempty(nbits) % default: no conversion nbits = 0; end if nargin < 3 | isempty(dirr) % invent name if not supplied name = getname(b); if ~isempty(name) & length(name) > 10 name = [deblank(name(1:10)) '_']; else name = 'PRDatafile_'; end dirr = [name num2str(round(rand*100000))]; % make it unique dirr = fullfile(pwd,dirr); %DXD store it in the working dir end if all(nbits ~= [0 1 8 16 32]) error('Illegal number of bits supplied for conversion') end if nargin < 2, featsize = []; end % reorder datafile for faster retrieval if isdatafile(b) & ~iscell(dfile_in) file_index = getident(b.dataset,'file_index'); [jj,R] = sort(file_index(:,1)+file_index(:,2)/(max(file_index(:,2),[],1)+1)); b = b(R,:); end %[m,k] = size(b); nobj= floor(filesize/k); % # of objects per file if nobj<1 error('Filesize is too small. A single object does not even fit in!'); end nfiles = ceil(m/nobj); % # of files needed if exist(dirr) == 7 % if datafile already exists act_dir = pwd; cd(dirr); % go to it fclose('all'); delete *.mat % make it empty delete file* cd(act_dir) % return to original directory else % otherwise create it [pp,ff] = fileparts(dirr); if isempty(pp) pp = pwd; end mkdir(pp,ff) end obj1 = 1; % initialise start object obj2 = min(obj1+nobj-1,m); % initialise end object file_index = zeros(m,2); s = sprintf('Saving %4i datafiles: ',nfiles); prwaitbar(nfiles,s); spaces = ' '; % initialise structure with file information cfiles = struct('name',cell(1,nfiles),'nbits',[], ... 'offsetd',[],'scaled',[],'offsett',[],'scalet',[]); for j=1:nfiles % run over all files to be created prwaitbar(nfiles,j,[s int2str(j)]); a = dataset(b(obj1:obj2,:)); % convert objects for a single file into dataset if iscell(dfile_in) for i=2:length(dfile_in(:)) a = [a dataset(dfile_in{i}(obj1:obj2,:))]; end end if ~isempty(featsize) if prod(featsize) ~= prod(getfeatsize(a)) error('Desired feature size does not match size of data') else a = setfeatsize(a,featsize); end end lendata = size(a,2); [a,scaled,offsetd,scalet,offsett,prec] = convert(a,nbits); % convert precision filej = ['file',num2str(j)]; fname = fullfile(dirr,filej); fid = fopen(fname,'w'); if fid<0 error('Unable to write file %s.',fname); end fwrite(fid,[a.data a.targets]',prec); % store fclose(fid); cfiles(j).name = filej; % name of the file cfiles(j).prec = prec; % precision cfiles(j).scaled = scaled; % scaling for datafield cfiles(j).offsetd = offsetd; % offset for datafield cfiles(j).scalet = scalet; % scaling for target field cfiles(j).offsett = offsett; % offset for target field cfiles(j).sized = a.featsize; % feature (image) size cfiles(j).sizet = size(a.targets,2); % size target field % create file_index file_index(obj1:obj2,1) = repmat(j,obj2-obj1+1,1); file_index(obj1:obj2,2) = [1:obj2-obj1+1]'; obj1 = obj2+1; % update start object obj2 = min(obj1+nobj-1,m); % update end object end prwaitbar(0); % finalise datafile definition c.files = cfiles; % file information c.type = 'mature'; % mature datafile preproc.preproc = []; preproc.pars = {}; c.preproc = preproc; % no preprocessing c.postproc = mapping([]); % default postprocessing featsize = getfeatsize(a); % copy feature (image) size c.postproc = setsize_in(c.postproc,featsize); % set input and ... c.postproc = setsize_out(c.postproc,featsize); % output size postprocessing c.dataset = setfeatsize(c.dataset,getfeatsize(a)); % set size datafile c.dataset = setident(c.dataset,file_index,'file_index'); % store file_index %DXD give it the name of the directory, not the complete path: %c.dataset = setname(c.dataset,dirr); [pname,dname] = fileparts(dirr); c.dataset = setname(c.dataset,dname); if isempty(pname), pname = pwd; end c.rootpath = fullfile(pname,dname); %DXD this path/filename is *very* strange! %save(fullfile(pwd,dirr,dirr),'c'); % store the datafile as mat-file for fast retrieval %DXD I changed it into this: %save(fullfile(dirr,filej),'c'); % store the datafile as mat-file for %fast retrieval save(fullfile(dirr,dname),'c'); % store the datafile as mat-file for fast retrieval %closemess([],len1+len2); return function [a,scaled,offsetd,scalet,offsett,prec] = convert(a,nbits) % handle precision data and target fields if nbits == 0 % no conversion scaled = []; offsetd = []; scalet = []; offsett = []; prec = 'double'; return; end % compute data field conversion pars data = +a; maxd = max(max(data)); mind = min(min(data)); scaled = (2^nbits)/(maxd-mind); offsetd = -mind; data = (data+offsetd)*scaled; % compute target field conversion pars targ = gettargets(a); if isempty(targ) % no targets set scalet = []; offsett = []; else maxt = max(max(targ)); mint = min(min(targ)); scalet = (2^nbits)/(maxt-mint); offsett = -mint; targ = (targ+offsett)*scalet; end % execute conversion switch nbits case 8 data = uint8(data); targ = uint8(targ); prec = 'uint8'; case 16 data = uint16(data); targ = uint16(targ); prec = 'uint16'; case 32 data = uint32(data); targ = uint32(targ); prec = 'uint32'; otherwise error('Desired conversion type not found') end % store results a.data = data; a.targets = targ; return
github
jacksky64/imageProcessing-master
pls_transform.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/pls_transform.m
1,490
utf_8
5ebad849b7f357810fd3db9d4b823ba5
%pls_transform Partial Least Squares transformation % % T = pls_transform(X,R) % T = pls_transform(X,R,Options) % % INPUT % X [N -by- d_X] the input data matrix, N samples, d_X variables % R [d_X -by- nLV] the transformation matrix: T_new = X_new*R % (X_new here after preprocessing, preprocessing and un-preprocessing % could be done automatically (than Options contains info about % preprocessing) or manually); normally, R as a field of XRes % output parameter of pls_train routine % % Options structure returned by pls_train (if not supplied then will be % no preprocessing performed) % % OUTPUT % T [N -by- nLV] scores -- transformed data % % DESCRIPTION % Applys PLS (Partial Least Squares) regression model % % SEE ALSO % pls_train, pls_apply % Copyright: S.Verzakov, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: pls_transform.m,v 1.1 2007/08/28 11:00:39 davidt Exp $ function T = pls_transform(X,R,Options) if nargin < 3 Options = []; end DefaultOptions.X_centering = []; DefaultOptions.Y_centering = []; DefaultOptions.X_scaling = []; DefaultOptions.Y_scaling = []; Options = pls_updstruct(DefaultOptions, Options); [N, d_X] = size(X); [d_XR, nLv] = size(R); if d_X ~= d_XR error('size(X,2) must be equal to size(R,1)'); end T = pls_prepro(X, Options.X_centering, Options.X_scaling)*R; return;
github
jacksky64/imageProcessing-master
prdatafiles.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prdatafiles.m
3,108
utf_8
2a830c3be91c9058ada3978a7534d5bd
%PRDATAFILES Checks availability of a PRTools datafile % % PRDATAFILES % % Checks the availability of the 'prdatafiles' directory, downloads the % Contents file and m-files if necessary and adds it to the search path. % Lists Contents file. % % PRDATAFILES(DFILE) % % Checks the availability of the particular datafile DFILE. DFILE should be % the name of the m-file. If it does not exist in the 'prdatafiles' % directory an attempt is made to download it from the PRTools web site. % % PRDATAFILES(DFILEDIR,SIZE,URL) % % This command should be used inside a PRDATAFILES m-file. It checks the % availability of the particular datafile directory DFILEDIR and downloads % it if needed. SIZE is the size of the datafile in Mbyte, just used to % inform the user. In URL the web location may be supplied. Default is % http://prtools.org/prdatafiles/DFILEDIR.zip % % All downloading is done interactively and should be approved by the user. % % SEE ALSO % DATAFILES, PRDATASETS, PRDOWNLOAD % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function prdatafiles(dfile,siz,url) if nargin < 1, dfile = []; end if nargin < 2, siz = []; end if nargin < 3 | isempty(url) url = ['http://prtools.org/prdatafiles/' dfile '.zip']; end if exist('prdatafiles/Contents','file') ~= 2 path = input(['The directory prdatafiles is not found in the search path.' ... newline 'If it exists, give the path, otherwise hit the return for an automatic download.' ... newline 'Path to prdatafiles: '],'s'); if ~isempty(path) addpath(path); feval(mfilename,dfile,siz); return else [ss,dirname] = prdownload('http://prtools.org/prdatafiles/prdatafiles.zip','prdatafiles'); addpath(dirname) end end if isempty(dfile) % just list Contents file help('prdatafiles/Contents') elseif ~isempty(dfile) & nargin == 1 % check / load m-file % renew all m-files if strcmp(dfile,'renew') if exist('prdatafiles/Contents','file') ~= 2 % no prdatafiles in the path, just start feval(mfilename); else dirname = fileparts(which('prdatafiles/Contents')); prdownload('http://prtools.org/prdatafiles/prdatafiles.zip',dirname); end % this just loads the m-file in case it does not exist and updates the % Contents file elseif exist(['prdatafiles/' dfile],'file') ~= 2 prdownload(['http://prtools.org/prdatafiles/' dfile '.m'],'prdatafiles'); prdownload('http://prtools.org/prdatafiles/Contents.m','prdatafiles'); end else % dfile is now the name of the datafile directory %It might be different from the m-file, so we cann't check it. rootdir = fileparts(which('prdatafiles/Contents')); if exist(fullfile(rootdir,dfile),'dir') ~= 7 siz = ['(' num2str(siz) ' MB)']; q = input(['Datafile is not available, OK to download ' siz ' [y]/n ?'],'s'); if ~isempty(q) & ~strcmp(q,'y') error('Datafile not found') end prdownload(url,rootdir); disp(['Datafile ' dfile ' ready for use']) end end
github
jacksky64/imageProcessing-master
vandermondem.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/vandermondem.m
1,043
utf_8
908771c54d917ff448e9c41eb1bface9
%VANDERMONDEM Extend data matrix % % Z = VANDERMONDEM(X,N) % % INPUT % X Data matrix % N Order of the polynomail % % OUTPUT % Z New data matrix containing X upto order N % % DESCRIPTION % Construct the Vandermonde matrix Z from the original data matrix X by % including all orders upto N. Note that also order 0 is added: % Z = [ones X X^2 X^3 ... X^N] % This construction allows for the trivial extension of linear methods % to obtain polynomail regressions. % % SEE ALSO % LINEARR % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function z = vandemondem(x,n) if nargin<2, n=1; end if nargin<1 | isempty(x) z = mapping(mfilename,'fixed',{n}); z = setname(z,'Vandemonde map'); return end % no training, just evaluation: dat = +x; [m,dim] = size(dat); I = 1:dim; z = ones(m,n*dim+1); for i=0:(n-1) z(:,(i+1)*dim+I) = dat.*z(:,i*dim+I); end % remove the superfluous ones: z(:,1:dim-1) = []; z = setdat(x,z); return
github
jacksky64/imageProcessing-master
modselc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/modselc.m
5,399
utf_8
3a438f73efa5f4bc8e705b530915c7f8
% MODSELC Model selection % % V = MODSELC(A,W,N,NREP) % V = A*(W*MODSELC([],N,NREP)) % % INPUT % A Dataset used for training base classifiers and/or selection % B Dataset used for testing (executing) the selector % W Set of trained or untrained base classifiers % N Number of crossvalidations, default 10 % NREP Number of crossvalidation repetitions % % OUTPUT % V Selected classidfer % % DESCRIPTION % This routine selects out of a set of given classifiers stored in W the % best one on the basis of N-fold crossvalidation (see CROSSVAL), which % might be repeated NREP times. If W contains a set of already trained % classifiers, N and NREP are neglected and just the best classifier % according to the evaluation set A is returned. % % This routine can be considered as a classifier combiner based on global % selection. See DCSC for local, dynamic selection. % % SEE ALSO % DATASETS, MAPPINGS, STACKED, DCSC, CLASSC, TESTD, LABELD % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function OUT = modselc(par1,par2,par3,par4) prtrace(mfilename); name = 'Classifier Model Selection'; DefaultN = 10; DefaultNrep = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Empty Call MODSELC, MODSELC([],N,NREP) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 1 | isempty(par1) if nargin > 1 & (ismapping(par2) | iscell(par2)) if nargin < 4 | isempty(par4), par4 = DefaultNrep; end if nargin < 3 | isempty(par3), par3 = DefaultN; end OUT = mapping(mfilename,'untrained',{par2,par3,par4}); else if nargin < 3 | isempty(par3), par3 = DefaultNrep; end if nargin < 2 | isempty(par2), par2 = DefaultN; end % If there are no inputs, return an untrained mapping. % (PRTools transfers the latter into the first) OUT = mapping(mfilename,'combiner',{par2,par3}); end OUT = setname(OUT,name); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Storing Base Classifiers: W*MODSELC, MODSELC(W,N,NREP) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif ismapping(par1) if nargin < 3 | isempty(par3), par3 = DefaultNrep; end if nargin < 2 | isempty(par2), par2 = DefaultN; end % call like OUT = MODSELC(W,N) or OUT = W*MODSELC([],N) % store trained or untrained base classifiers, % ready for later training of the combiner BaseClassf = par1; if ~isparallel(BaseClassf) & ~isstacked(BaseClassf) error('Parallel or stacked set of base classifiers expected'); end OUT = mapping(mfilename,'untrained',{BaseClassf,par2,par3}); OUT = setname(OUT,name); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Selection (and training base classifiers if needed): % A*(W*MODSELC), A*(W*MODSELC([],N,NREP)), MODSELC(A,W,N,NREP) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif isdataset(par1) & ismapping(par2) & ... (isuntrained(par2) | (istrained(par2) & (isstacked(par2) | isparallel(par2)))) % call like OUT = MODSELC(TrainSet,W,N,NREP) or TrainSet*(W*MODSELC([],N,NREP)) % (PRTools transfers the latter into the first) % W is a set of trained or untrained set classifiers. if nargin < 4 | isempty(par4), par4 = DefaultNrep; end if nargin < 3 | isempty(par3), par3 = DefaultN; end TrainSet = par1; BaseClassf = par2; N = par3; Nrep = par4; isvaldfile(TrainSet,1,2); % at least one object per class, 2 classes TrainSet = setprior(TrainSet,getprior(TrainSet,0)); % avoid many warnings if ~(isstacked(BaseClassf) | isparallel(BaseClassf)) if iscombiner(BaseClassf) error('No base classifiers found') end Data = getdata(BaseClassf); BaseClassf = Data.BaseClassf; % base classifiers were already stored end if isuntrained(BaseClassf) % base classifiers untrained, crossval needed randstate = randreset; % makes routine reproducing if isparallel(BaseClassf) BaseClassf = getdata(BaseClassf); tsize = BaseClassf{end}; if ismapping(tsize) error(['Training of parallel combined untrained classifier not possible.' ... newline 'Feature sizes should be stored in the classifier first.']) end csize = cumsum([0 tsize(:)']); n = length(BaseClassf)-1; e = zeros(1,n); rstate = randreset; s = sprintf('Crossvalidating %i base classifiers: ',n); prwaitbar(n,s) for j=1:n prwaitbar(n,j,[s getname(BaseClassf{j})]); randreset(1); e(j) = crossval(TrainSet(:,csize(j)+1:csize(j+1)),BaseClassf{j},N,Nrep); end prwaitbar(0); [ee,k] = min(e); J = [csize(k)+1:csize(k+1)]; OUT = TrainSet(:,J)*BaseClassf{k}; OUT = featsel(csize(end),J)*OUT; else if isstacked(BaseClassf) BaseClassf = getdata(BaseClassf); end randreset(1); e = crossval(TrainSet,BaseClassf,N,Nrep); [ee,k] = min(e); OUT = TrainSet*BaseClassf{k}; end randreset(randstate); else % base classifiers are trained, check label lists and find best one BaseClassf = getdata(BaseClassf); n = length(BaseClassf); for j=1:n if ~isequal(getlabels(BaseClassf{j}),getlablist(TrainSet)) error('Training set and base classifiers should deal with same labels') end end e = testc(TrainSet,BaseClassf); [ee,k] = min([e{:}]); OUT = BaseClassf{k}; end else error('Illegal input'); end
github
jacksky64/imageProcessing-master
classd.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/classd.m
550
utf_8
a9ffc4f859a1a00eb46ce2c2c2d1e9ab
%CLASSD Return labels of classified dataset, outdated, use LABELD instead % $Id: classd.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function labels = classd(a,w) prtrace(mfilename); global CLASSD_REPLACED_BY_LABELD if isempty(CLASSD_REPLACED_BY_LABELD) disp([newline 'CLASSD has been replaced by LABELD, please use it']) CLASSD_REPLACED_BY_LABELD = 1; end if (nargin == 0) labels = labeld; elseif (nargin == 1) labels = labeld(a); elseif (nargin == 2) labels = labeld(a,w); else error ('too many arguments'); end return
github
jacksky64/imageProcessing-master
prcov.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prcov.m
353
utf_8
d356173c3d4ecd94c33278a0d2f06dbc
%PRCOV Call to COV() including PRWAITBAR % % B = PRCOV(A,tol) % % This calls C = COV(A, ...) and includes a message to PRWAITBAR % in case of a large A function B = prcov(varargin) [m,n] = size(varargin{1}); if m*n*n > 1e9 prwaitbaronce('covariance of %i x %i matrix ...',[m,n]); B = cov(varargin{:}); prwaitbar(0); else B = cov(varargin{:}); end
github
jacksky64/imageProcessing-master
im_stretch.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_stretch.m
1,275
utf_8
25193a277ae8513dbcd8c6a259d0b553
%IM_STRETCH Contrast stretching of images stored in a dataset (DIP_Image) % % B = IM_STRETCH(A,LOW,HIGH,MIN,MAX) % B = A*IM_STRETCH([],LOW,HIGH,MIN,MAX) % % INPUT % A Dataset with object images dataset (possibly multi-band) % LOW Lower percentile (default 0) % HIGH Highest percentile (default 100) % MIN Miniumum (default 0) % MAX Maximum (default 255) % % OUTPUT % B Dataset with filtered images % % SEE ALSO % DATASETS, DATAFILES, DIP_IMAGE, STRETCH % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_stretch(a,low,high,min,max) prtrace(mfilename); if nargin < 5 | isempty(max), max = 255; end if nargin < 4 | isempty(min), min = 0; end if nargin < 3 | isempty(high), high = 100; end if nargin < 2 | isempty(low), low = 0; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{low,high,min,max}); b = setname(b,'Image stretch'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename,{low,high,min,max}); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image a = 1.0*dip_image(a); b = stretch(a,low,high,min,max); end return
github
jacksky64/imageProcessing-master
prodc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prodc.m
1,633
utf_8
d89f9184765750c0c705dfc45192da63
%PRODC Product combining classifier % % W = PRODC(V) % W = V*PRODC % % INPUT % V Set of classifiers trained on the same classes % % OUTPUT % W Product combiner % % DESCRIPTION % It defines the product combiner on a set of classifiers, e.g. % V=[V1,V2,V3] trained on the same classes, by selecting the class % which yields the highest value of the product of the classifier % outputs. This might also be used as A*[V1,V2,V3]*PRODC in which % A is a dataset to be classified. % % If it is desired to operate on posterior probabilities, then the % input classifiers should be extended like V = V*CLASSC. % % The base classifiers may be combined in a stacked way (operating % in the same feature space) by V = [V1,V2,V3,...] or in a parallel % way (operating in different feature spaces) by V = [V1;V2;V3;...]. % % SEE ALSO % MAPPINGS, DATASETS, VOTEC, MAXC, MINC, MEDIANC, MEANC, AVERAGEC, % STACKED, PARALLEL % % EXAMPLES % See PREX_COMBINING. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: prodc.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function w = prodc(p1) prtrace(mfilename); type = 'prod'; % Define the operation processed by FIXEDCC. name = 'Product combiner'; % Define the name of the combiner. % This is a general procedure for all possible % calls of fixed combiners handled by FIXEDCC if nargin == 0 w = mapping('fixedcc','combiner',{[],type,name}); else w = fixedcc(p1,[],type,name); end if isa(w,'mapping'), w = setname(w,name); end return
github
jacksky64/imageProcessing-master
scatterdui.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/scatterdui.m
8,832
utf_8
2a9a07a5ef7fa77da861992b9fb0dddd
% SCATTERDUI Scatter plot with user interactivity % % SCATTERDUI (A) % SCATTERDUI (A,DIM,S,CMAP,FONTSIZE,'label','both','legend','gridded') % % INPUT % DATA Dataset % ... See SCATTERD % % OUTPUT % % DESCRIPTION % SCATTERDUI is a wrapper around SCATTERD (see SCATTERD for the options). If % the user clicks on a sample in the plot, the corresponding index in a % dataset is written nearby. A right-button click clears all printed indices. % Buttons along axes allow for browsing through the dataset dimensions. % Selected points are remembered when the plotted dimension changes. % % SEE ALSO % SCATTERD % This script is based on the segmentgui of Cris Luengo % <[email protected]>. % Copyright: Pavel Paclik, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: scatterdui.m,v 1.3 2006/10/23 10:21:52 davidt Exp $ function fig_hnd=scatterdui (varargin) prtrace (mfilename); % First argument is dataset. a = varargin{1}; % Place all remaining arguments in a string, for the call to SCATTERD. %args = ''; %for i = 2:size(varargin,2) %eval(sprintf('p%d = varargin{%d};',i,i)); args = [args sprintf(',p%d',i)]; %end args = varargin(2:end); % Are we called through one of the callback handles? if (ischar(a)) switch (a) case 'denclick_scatter' scatterdui_inspect; case 'scatterdui_change_dim' scatterdui_change_dim(varargin{2}); end return end % Get figure handle, clear window and start new axis. % fig_hnd = gcf; clf; ui_data.axis = subplot(1,1,1); % open a new figure figure; fig_hnd = gcf; ui_data.axis = subplot(1,1,1); % tag this figure set(fig_hnd,'tag','scatterdui'); set(fig_hnd,'busyaction','cancel','DoubleBuffer','on'); % Call SCATTERD. ui_data.args = args; %eval(['scatterd(a' args,');']); scatterd(a, args{:}); % Store the data for later reference. ui_data.a = a; % Define viable neighborhood for sample ID back-reading. range_x = get(ui_data.axis,'xlim'); range_y = get(ui_data.axis,'ylim'); ui_data.neighborhood = [0.01*abs(range_x(1)-range_x(end)) ... 0.01*abs(range_y(1)-range_y(end))]; ui_data.point_id = []; ui_data.text_hnd = []; % Add callback function to axis. set(ui_data.axis,'ButtonDownFcn','scatterdui(''denclick_scatter'')'); set(get(ui_data.axis,'Children'),'ButtonDownFcn','scatterdui(''denclick_scatter'')'); % Initialise current X- and Y-dimensions. ui_data.xdim = 1; ui_data.ydim = 2; % Place buttons for increasing/decreasing the dimensions (features) of % the dataset shown on the X- and Y-axes of the plot. pos = get(fig_hnd,'position'); ui_data.x_dim_inc = uicontrol('style','pushbutton', ... 'string','->', ... 'units','normalized', ... 'position',[0.9 0.02 0.05 0.05], ... 'callback','scatterdui(''scatterdui_change_dim'',''xinc'')'); ui_data.x_dim_dec = uicontrol('style','pushbutton', ... 'string','<-', ... 'units','normalized', ... 'position',[0.85 0.02 0.05 0.05], ... 'callback','scatterdui(''scatterdui_change_dim'',''xdec'')'); ui_data.y_dim_inc = uicontrol('style','pushbutton', ... 'string','^', ... 'units','normalized', ... 'position',[0.02 0.9 0.05 0.05], ... 'callback','scatterdui(''scatterdui_change_dim'',''yinc'')'); ui_data.y_dim_dec = uicontrol('style','pushbutton', ... 'string','v', ... 'units','normalized', ... 'position',[0.02 0.85 0.05 0.05], ... 'callback','scatterdui(''scatterdui_change_dim'',''ydec'')'); % Draw feature labels. featlabs = getfeat(ui_data.a); %RD Take care that we have proper char labels if isempty(featlabs) featlabs = num2str([1:size(ui_data.a,2)]'); elseif (isnumeric(featlabs)) featlabs = num2str(featlabs); elseif iscellstr(featlabs) featlabs = char(featlabs); end; %RD and store them in the dataset ui_data.a = setfeatlab(ui_data.a,featlabs); xlabel(sprintf('%d : %s',ui_data.xdim,featlabs(ui_data.xdim,:))); ylabel(sprintf('%d : %s',ui_data.ydim,featlabs(ui_data.ydim,:))); % Save user interface data into figure window. First clear it, to % avoid a (sometimes) very slow update. set(fig_hnd,'userdata',[]); set(fig_hnd,'userdata',ui_data); hold on; if nargout == 0 clear('fig_hnd'); end return % SCATTERDUI_CHANGE_DIM (CODE) % % Call-back for the buttons in the window: increases or decreases the % feature number (dimension) the plot represents on the x- or y-axis. CODE % can be 'xinc', 'xdec', 'yinc', 'ydec'. function scatterdui_change_dim (code) fig_hnd = gcbf; ui_data = get(fig_hnd,'userdata'); [m,k,c] = getsize(ui_data.a); % Increase/decrease feature shown in X- or Y-axis. Loop around: % feature k+1 -> 1, features 1-1 -> k. switch (code) case 'xinc' ui_data.xdim = ui_data.xdim + 1; if (ui_data.xdim > k) ui_data.xdim = 1; end case 'xdec' ui_data.xdim = ui_data.xdim - 1; if (ui_data.xdim == 0), ui_data.xdim = k; end case 'yinc' ui_data.ydim = ui_data.ydim + 1; if (ui_data.ydim > k), ui_data.ydim = 1; end case 'ydec' ui_data.ydim = ui_data.ydim - 1; if (ui_data.ydim == 0), ui_data.ydim = k; end end % Redraw figure. cla; ui_data.axis = subplot(1,1,1); % I had to add this to make it work!!!: scatterd(ui_data.a(:,[1 1])); %eval(['scatterd(ui_data.a(:,[ui_data.xdim,ui_data.ydim])' ui_data.args,');']); scatterd(ui_data.a(:,[ui_data.xdim,ui_data.ydim]), ui_data.args{:}); % Draw feature labels. featlabs = getfeat(ui_data.a); if (isnumeric(featlabs)), featlabs = num2str(featlabs); end; %PP!! deal with cell labels here: I don't know how, yet if (iscellstr(featlabs)) featlabs = (1:size(featlabs,1))'; featlabs = num2str(featlabs); end xlabel(sprintf('%d : %s',ui_data.xdim,featlabs(ui_data.xdim,:))); ylabel(sprintf('%d : %s',ui_data.ydim,featlabs(ui_data.ydim,:))); % Define viable neighborhood for sample ID back-reading. range_x = get(ui_data.axis,'xlim'); range_y = get(ui_data.axis,'ylim'); ui_data.neighborhood = [0.01*abs(range_x(1)-range_x(end)) ... 0.01*abs(range_y(1)-range_y(end))]; % Redraw selected points. ui_data.text_hnd = ... scatterdui_add_labels(ui_data.point_id, ... +ui_data.a(:,[ui_data.xdim,ui_data.ydim]), ... ui_data.neighborhood ); % Add callback function to axis. set(ui_data.axis,'ButtonDownFcn','scatterdui(''denclick_scatter'')'); set(get(ui_data.axis,'Children'),'ButtonDownFcn',... 'scatterdui(''denclick_scatter'')'); % Save user interface data into figure window. set(fig_hnd,'userdata',[]); set(fig_hnd,'userdata',ui_data); return % SCATTERDUI_INSPECT % % Callback for mouse-click in axis. Finds all samples in the neighbourhood % of the clicked point and plots them, with text labels containing the index. % Right-click clears all selected points. function scatterdui_inspect fig_hnd = gcbf; ui_data = get(fig_hnd,'userdata'); if (strcmp(get(fig_hnd,'SelectionType'),'alt')) % Clear all selected points. delete(ui_data.text_hnd); ui_data.text_hnd = []; ui_data.point_id = []; else point = get(ui_data.axis,'CurrentPoint'); % Get all points close to the selected point from the dataset. % 'Close' means inside a box around POINT defined by UI_DATA.NEIGHBORHOOD. a = +ui_data.a; a = a(:,[ui_data.xdim,ui_data.ydim]); ind = find((a(:,1) >= (point(1) - ui_data.neighborhood(1))) & ... (a(:,1) <= (point(1) + ui_data.neighborhood(1))) & ... (a(:,2) >= (point(3) - ui_data.neighborhood(2))) & ... (a(:,2) <= (point(3) + ui_data.neighborhood(2)))); % If any points fall inside the box, plot them and add them (and their % text handles) to the user interface data. if (length(ind) > 0) text_hnd = scatterdui_add_labels(ind,a,ui_data.neighborhood); ui_data.point_id = [ui_data.point_id ind']; ui_data.text_hnd = [ ui_data.text_hnd text_hnd ]; end end % Save user interface data into figure window. set(fig_hnd,'userdata',[]); set(fig_hnd,'userdata',ui_data); return % HND = SCATTERDUI_ADD_LABELS (IND,DATA,NEIGHBORHOOD) % % Plots samples with indices IND in DATA, and places the indices as text % labels next to the points (at a (x,y)-distance defined by NEIGHBORHOOD). % Returns handles to all text labels in HND. function hnd = scatterdui_add_labels (ind,data,neighborhood) hold on; % Plot the data points, plus their index in the dataset as text. hnd = plot(data(ind,1),data(ind,2),'gh'); for i = 1:length(ind) hnd=[hnd text(data(ind(i),1) + neighborhood(1), ... data(ind(i),2) + neighborhood(2), ... sprintf('%d',ind(i)))]; end % Add callback function to each of the texts. set(hnd,'ButtonDownFcn','scatterdui(''denclick_scatter'')'); return
github
jacksky64/imageProcessing-master
primport.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/primport.m
2,968
utf_8
67b864e93a49244199462b27e7dbbc95
% PRIMPORT import the old-format prtools datasets % % OUT = PRIMPORT(A) % % INPUT % A The Structure to be converted. % % OUTPUT % OUT The imported dataset % % DESCRIPTION % This routine converts old prtools datasets into the new prtools 4.x % format. Structure A is tested for existence of all the fields forming % particular dataset format. Prtools 3.x and 4.x formats are supported. % % SEE ALSO % DATASET % $Id: primport.m,v 1.4 2007/08/24 13:49:59 davidt Exp $ function out = primport(a) prtrace(mfilename) % we try to convert only structures if isstruct(a) % prtools 3.x format if isfield(struct(a),'d') & isfield(struct(a),'l') & ... isfield(struct(a),'p') & isfield(struct(a),'f') & ... isfield(struct(a),'ll') & isfield(struct(a),'c') & ... isfield(struct(a), 's') prwarning(2,'prtools 3.x dataset converted to 4.x'); % lab list could be a cell-array if iscell(a.ll) lablist=a.ll{1}; nlab=a.l; else [nlab,lablist] = renumlab(a.l); end out=dataset(a.d,nlab,'featlab',a.f,'prior',a.p,'lablist',lablist); if a.c<0 % objects are pixels xx=-a.c; yy=size(a.d,1)/xx; out.objsize=[xx yy]; end if a.c>0 % objects are pictures xx=a.c; yy=size(a.d,2)/xx; out.featsize=[xx yy]; end % prtools 4 format elseif isfield(struct(a),'data') & isfield(struct(a),'lablist') & ... isfield(struct(a),'nlab') & isfield(struct(a),'labtype') & ... isfield(struct(a),'targets') & isfield(struct(a), 'featlab') & ... isfield(struct(a),'prior') & ... isfield(struct(a),'objsize') & isfield(struct(a),'featsize') & ... isfield(struct(a),'ident') & isfield(struct(a),'version') & ... isfield(struct(a),'name') & isfield(struct(a),'user') %DXD: The previous line was commented out % Uncommenting made it work: out = dataset(a.data,a.nlab,'lablist',a.lablist); if ~isempty(a.labtype), out.labtype=a.labtype; end if ~isempty(a.targets), out.targets=a.targets; end if ~isempty(a.featlab), out.featlab=a.featlab; end if ~isempty(a.prior), out.prior=a.prior; end if ~isempty(a.objsize), out.objsize=a.objsize; end if ~isempty(a.featsize), out.featsize=a.featsize; end if ~isempty(a.ident), out.ident=a.ident; end if ~isempty(a.version), out.version=a.version; end if ~isempty(a.name), out.name=a.name; end if ~isempty(a.user), out.user=a.user; end % later, the featdom field was included if isfield(struct(a),'featdom') & ~isempty(a.featdom) out.featdom = a.featdom; end % later, the cost field was included if isfield(struct(a),'cost') & ~isempty(a.cost) out.cost = a.cost; end prwarning(2,'prtools 4.x converted from structure'); else out = []; prwarning(2,'unknown format! The structure cannot be converted into a dataset'); end else % anything else then structure: just copy to the output out=a; end
github
jacksky64/imageProcessing-master
testn.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testn.m
2,970
utf_8
6ca41edfc202366ae9aec6995f980f3b
%TESTN Error estimate of discriminant for normal distribution. % % E = TESTN(W,U,G,N) % % INPUT % W Trained classifier mapping % U C x K dataset with C class means, labels and priors (default: [0 .. 0]) % G K x K x C matrix with C class covariance matrices (default: identity) % N Number of test examples (default 10000) % % OUTPUT % E Estimated error % % DESCRIPTION % This routine estimates as good as possible the classification error % of Gaussian distributed problems with known means and covariances. N % normally distributed data vectors with means, labels and prior % probabilities defined by the dataset U (size [C,K]) and covariance % matrices G (size [K,K,C]) are generated with the specified labels and are % tested against the discriminant W. The fraction of incorrectly classified % data vectors is returned. If W is a linear 2-class discriminant and N % is not specified, the error is computed analytically. % % SEE ALSO % MAPPINGS, DATASETS, QDC, NBAYESC, TESTC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: testn.m,v 1.3 2009/01/27 13:01:42 duin Exp $ function e = testn(w,U,G,m) prtrace(mfilename); % Assert that W is a trained mapping. istrained(w); [k,c] = size(w); if (nargin < 4) & ~( isaffine(w) & (c == 2) ) prwarning(4,'number of samples N to test with not specified, assuming 10000'); m = 10000; end if (nargin < 3) prwarning(3,'covariance matrices not specified, assuming identity for each class'); G = eye(k); end if (nargin < 2) error('Class means are not specified'); else [cc,k] = size(U); p = getprior(U); u = +U; if (cc ~= c) error('Specified number of class means does not fit classifier') end end % If a single covariance is specified, use it for each class. if (length(size(G)) == 2) g = G; for j = 2:c G = cat(3,G,g); end else if (size(G,3) ~= c) error('Specified number of covariances does not fit classifier') end end % Check for analytical case: linear classifier and no data samples requested. if (nargin < 4) & (isaffine(w)) & (c == 2) prwarning(1,'computing Bayes error analytically'); e = 0; v = w.data.rot(:,1); f = w.data.offset(1); for j = 1:c % Find the index J of mean j stored in U. J = findnlab(U,j); if (length(J) ~= 1) error('The mean U does not contain correct labels.') end q = real(sqrt(v'*G(:,:,j)*v)); % std dev in direction of classifier d = (2*j-3)*(v'*u(J,:)'+f); % normalized distance to classifier if (q == 0) if (d >= 0), e = e + p(j); end else e = e + p(j) * (erf(d/(q*sqrt(2)))/2 + 0.5); end end else % Cannot solve analytically: generate data and test. a = gendatgauss(m,U,G); % Generate normally distributed data. a = setlablist(a,getlab(w)); e = testc(a,w); % Find the error of discriminant on the data. end return
github
jacksky64/imageProcessing-master
plotc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plotc.m
5,575
utf_8
e41895c418931e871fbdff32d1fcf052
%PLOTC Plot classifiers % % PLOTC(W,S,LINE_WIDTH) % PLOTC(W,LINE_WIDTH,S) % % Plots the discriminant as given by the mapping W on predefined axis, % typically set by scatterd. Discriminants are defined by the points % where class differences for mapping values are zero. % % S is the plot string, e.g. S = 'b--'. In case S = 'col' a color plot is % produced filling the regions of different classes with different colors. % Default S = 'k-'; % % LINE_WIDTH sets the width of the lines and box. Default LINE_WIDTH = 1.5 % % In W a cell array of classifiers may be given. In S a set of plot strings % of appropriate size may be given. Automatically a legend is added to % the plot. % % The linear gridsize is read from the global parameter GRIDSIZE, that % can be set by the function gridsize: for instance 'gridsize(100)' % default gridsize is 30. % % See also MAPPINGS, SCATTERD, PLOTM, GRIDSIZE % Examples in PREX_CONFMAT, PREX_PLOTC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: plotc.m,v 1.6 2009/10/30 11:01:47 davidt Exp $ function handle = plotc(w,varargin) prtrace(mfilename); linew = 1.5; s = []; if nargin < 1 | isempty(w) handle = mapping(mfilename,'combiner',s); return end % Extract the plotwidth and linewidth: for j = 1:nargin-1 if isstr(varargin{j}) s = varargin{j}; else linew = varargin{j}; end end ss = char('k-','r-','b-','m-','k--','r--','b--','m--'); ss = char(ss,'k-.','r-.','b-.','m-.','k:','r:','b:','m:'); % When we want to plot a list of classifiers, we set up different % plot strings ss and call plotc several times. if iscell(w) w = w(:); n = length(w); names = []; % Check if sufficient plotstrings are available if ~isempty(s) if size(s,1) == 1 s = repmat(s,n,1); elseif size(s,1) ~= n error('Wrong number of plot strings') end else s = ss(1:n,:); end % Plot the individual boundaries by calling 'mfilename' (i.e. this % function again) names = []; hh = []; for i=1:n h = feval(mfilename,w{i},deblank(s(i,:)),linew); hh = [hh h(1)]; names = char(names,getname(w{i})); end % Finally fix the legend: names(1,:) = []; legend(hh,names,0); if nargout > 0 handle = hh; end return end % Now the task is to plot a single boundary (multiple boundaries are % already covered above): if ~isa(w,'mapping') | ~istrained(w) error('Trained classifier expected') end [k,c] = size(w); c = max(c,2); if nargin < 2 | isempty(s) % default plot string s = 1; end %DXD: Stop when the classifier is not in 2D: if (k~=2) error('Plotc can only plot classifiers operating in 2D.'); end if ~isstr(s) if s > 16 | s < 1 error('Plotstring undefined') else s = deblank(ss(s,:)); end end % Get the figure size from the current figure: hold on V=axis; hh = []; set(gca,'linewidth',linew) % linear discriminant if isaffine(w) & c == 2 & ~strcmp(s,'col') % plot as vector d = +w; n = size(d.rot,2); if n == 2, n = 1; end for i = 1:n w1 = d.rot(:,i); w0 = d.offset(i); J = find(w1==0); if ~isempty(J) w1(J) = repmat(realmin,size(J)); end x = sort([V(1),V(2),(-w1(2)*V(3)-w0)/w1(1),(-w1(2)*V(4)-w0)/w1(1)]); x = x(2:3); y = (-w1(1)*x-w0)/w1(2); h = plot(x,y,s); set(h,'linewidth',linew) hh = [hh h]; end else % general case: find contour(0) % First define the mesh grid: n = gridsize; m = (n+1)*(n+1); dx = (V(2)-V(1))/n; dy = (V(4)-V(3))/n; [X Y] = meshgrid(V(1):dx:V(2),V(3):dy:V(4)); D = double([X(:),Y(:),zeros(m,k-2)]*w); if min(D(:)) >=0, D = log(D+realmin); end % avoid infinities % A two-class output can be given in one real number, avoid this % special case and fix it: if c == 2 & min(size(D)) == 1; D = [D -D]; end c = size(D,2); if ~strcmp(s,'col') % Plot the contour lines if c < 3 Z = reshape(D(:,1) - D(:,2),n+1,n+1); if ~isempty(contourc([V(1):dx:V(2)],[V(3):dy:V(4)],Z,[0 0])) [cc h] = contour([V(1):dx:V(2)],[V(3):dy:V(4)],Z,[0 0],s); set(h,'linewidth',linew) %DXD Matlab 7 has different handle definitions: if str2num(version('-release'))>13, h = get(h,'children'); end hh = [hh;h]; end else for j=1:c-1 L = [1:c]; L(j) = []; Z = reshape( D(:,j) - max(D(:,L),[],2),n+1,n+1); if ~isempty(contourc([V(1):dx:V(2)],[V(3):dy:V(4)],Z,[0 0])) [cc h] = contour([V(1):dx:V(2)],[V(3):dy:V(4)],Z,[0 0],s); set(h,'linewidth',linew) %DXD Matlab 7 has different handle definitions: if str2num(version('-release'))>13, h = get(h,'children'); end hh = [hh;h]; end end end else % Fill the areas with some colour: col = 0; mapp = hsv(c+1); h = []; for j=1:c L = [1:c]; L(j) = []; Z = reshape( D(:,j) - max(D(:,L)',[],1)',n+1,n+1); Z = [-inf*ones(1,n+3);[-inf*ones(n+1,1),Z,-inf*ones(n+1,1)];-inf*ones(1,n+3)]; col = col + 1; if ~isempty(contourc([V(1)-dx:dx:V(2)+dx],[V(3)-dy:dy:V(4)+dy],Z,[0 0])) [cc h] = contour([V(1)-dx:dx:V(2)+dx],[V(3)-dy:dy:V(4)+dy],Z,[0 0]); while ~isempty(cc) len = cc(2,1); h = [h;fill(cc(1,2:len+1),cc(2,2:len+1),mapp(col,:),'FaceAlpha',0.5)]; %fill(cc(1,2:len+1),cc(2,2:len+1),mapp(col,:),'FaceAlpha',0.5); cc(:,1:len+1) = []; end hh = [hh;h]; end end end end axis(V); % Return the handles if they are requested: if nargout > 0, handle = hh; end hold off return
github
jacksky64/imageProcessing-master
prsvd.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prsvd.m
426
utf_8
b8c97273dada58abf140fc88b5c1f239
%PRSVD Call to SVD() including PRWAITBAR % % VARARGOUT = PRSVD(VARARGIN) % % This calls B = RANK(A,tol) and includes a message to PRWAITBAR % in case of a large A function varargout = prsvd(varargin) [m,n] = size(varargin{1}); varargout = cell(1,nargout); if min([m,n]) >= 500 prwaitbaronce('SVD of %i x %i matrix ...',[m,n]); [varargout{:}] = svd(varargin{:}); prwaitbar(0); else [varargout{:}] = svd(varargin{:}); end
github
jacksky64/imageProcessing-master
im2obj.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im2obj.m
3,036
utf_8
f910d69b3caaaaddcaab0f7e7dc9a09d
%IM2OBJ Convert Matlab images or datafile to dataset object % % B = IM2OBJ(IM,A) % B = IM2OBJ(IM,FEATSIZE) % % INPUT % IM X*Y image, X*Y*C image, X*Y*K array of K images, % X*Y*C*K array of color images, or cell-array of images % The images may be given as a datafile. % A Input dataset % FEATSIZE Vector with desired feature sizes to solve ambiguities % % OUTPUT % B Dataset with IM added % % DESCRIPTION % Add standard Matlab images, as objects, to an existing dataset A. If A is % not given, a new dataset is created. Images of type 'uint8' are converted % to 'double' and divided by 256. The resulting feature size is X*Y or % X*Y*C. The set of images IM may be given as a datafile. % % SEE ALSO % DATASETS, DATAFILES, IM2FEAT, DATA2IM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: im2obj.m,v 1.5 2008/07/28 08:59:47 duin Exp $ function a = im2obj (im,a) prtrace(mfilename); if iscell(im) imsize = size(im{1}); else imsize = size(im); end nodataset = 0; if (nargin > 1) if (~isdataset(a)) & size(a,1) ~= 1 error('second argument should be a dataset or a size vector'); end if isdataset(a) featsize = getfeatsize(a); else featsize = a; nodataset = 1; end else % no information on feature size, assume most simple solution nodataset = 1; if length(imsize) == 2 featsize = imsize; else featsize = imsize(1:end-1); end end if length(featsize) == length(imsize) nobj = 1; elseif length(featsize) == (length(imsize)-1) nobj = imsize(end); elseif length(featsize) == (length(imsize)-2) & imsize(3) == 1 nobj = imsize(end); else wrongfeatsize; end if any(featsize ~= imsize(1:length(featsize))) wrongfeatsize; end if (isa(im,'cell')) % If IM is a cell array of images, unpack it and recursively call IM2OBJ % to add each image. im = im(:); % Reshape to 1D cell array. for i = 1:length(im) b = feval(mfilename,im{i}); if ~isempty(a) & any(a.objsize ~= b.objsize) error('Images should have equal sizes') end a = [a; feval(mfilename,im{i},featsize)]; end elseif isdatafile(im) if (nargin < 2) a = dataset([]); end testdatasize(im); a = [a; feval(mfilename,data2im(im))]; else % If IM is an image or array of images, reshape it and add it in one go. % Convert to double, if necessary if (isa(im,'uint8')) prwarning(4,'image is uint8; converting to double and dividing by 256'); im = double(im)/256; else im = double(im); end % ready for the real work, at last! if nobj == 1 im = im(:)'; else im = shiftdim(im,ndims(im)-1); im = reshape(im,nobj,prod(featsize)); end if nodataset a = dataset(im); a = setfeatsize(a,featsize); else a = [a; im]; end end return function wrongfeatsize error('Desired feature size and size of supplied image array are inconsistent') return
github
jacksky64/imageProcessing-master
getwindows.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/getwindows.m
3,090
utf_8
843fd3b7f8928e6809061d465551396d
%GETWINDOWS Get pixel feature vectors around given pixels in image dataset % % L = GETWINDOWS(A,INDEX,WSIZE,INCLUDE) % L = GETWINDOWS(A,[ROW,COL],WSIZE,INCLUDE) % % INPUT % A Dataset containing feature images % INDEX Index vector of target pixels in the images (Objects in A) % ROW Column vector of row-coordinates of target pixels % COL Column vector of column-coordinates of target pixels % WSIZE Desired size of rectangular window around target pixels % INCLUDE Flag (0/1), indicating whether target pixels should be included % (1, default), or not (0) in result. % OUTPUT % B Index in A of window pixels % % DESCRIPTION % This routine generates all objects in a dataset constructed by image % features that are in a window of size WSIZE around the target pixels % given by INDEX, or by [ROW,COL]. If WSIZE is omitted or empty ([], % default), just the 4 4-conntected neighbors of the target pixels are % returned. L points to the window pixels, such that A(L,:) is a dataset % of the corresponding objects. % % SEE ALSO % DATASETS, IM2FEAT % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function L = getwindows(a,index,wsize,include) if nargin < 4, includeflag = 1; end if nargin < 3, wsize = []; end isdataset(a); isfeatim(a); imsize = getobjsize(a); if size(index,2) == 1 [row,col] = ind2sub(imsize,index); elseif size(index,2) == 2 row = index(:,1); col = index(:,2); end n = length(row); imsize = getobjsize(a); if ~isempty(wsize) % rectangular neighborhoods if length(wsize) == 1 % square windows row1 = ceil(wsize/2)-1; col1 = row1; % # pixels above / left of target pixel row2 = floor(wsize/2); col2 = row2; % # pixels below / right of target pixel elseif length(wsize) == 2 % possibly non-square windows row1 = ceil(wsize(1)/2)-1; row2 = floor(wsize(1)/2); col1 = ceil(wsize(2)/2)-1; col2 = floor(wsize(2)/2); else error('Window size should be 1D or 2D') end [R,C] = meshgrid([-row1:row2],[-col1:col2]); k = length(R(:)); R = repmat(row(:),1,k)+repmat(R(:)',length(row),1); C = repmat(col(:),1,k)+repmat(C(:)',length(col),1); else R = repmat(row(:),1,5)+repmat([0 -1 0 1 0],length(row),1); C = repmat(col(:),1,5)+repmat([-1 0 0 0 1],length(col),1); end JR = [find(R <= 0); find(R > imsize(1))]; R(JR) = []; C(JR) = []; JC = [find(C <= 0); find(C > imsize(2))]; R(JC) = []; C(JC) = []; L = sub2ind(imsize,R,C); %b(L) = ones(length(L),1); if include % we are done L = unique(L); else % remove given objects b = zeros(imsize); % create an image of the right size b(L) = ones(length(L),1); % flag the objects we found. Z = sub2ind(imsize,row,col); % for all original objects, b(Z) = zeros(length(Z),1); % remove flags L = find(b > 0); % and see what is left end %b = a(L,:); L = unique(L); J = [find(L<1); find(L>prod(imsize))]; L(J) = []; %b = a(L,:);
github
jacksky64/imageProcessing-master
getopt_pars.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/getopt_pars.m
795
utf_8
320c88660dd14251da5693f9e2f3d6d7
%GETOPT_PARS Get optimal parameters from REGOPTC % % PARS = GETOPT_PARS % GETOPT_PARS % % DESCRIPTION % This routine retrieves the parameters as used in the final call % in computing a classifier they are optimised by REGOPTC. function pars = getopt_pars global REGOPT_PARS if nargout == 0 s = []; for j = 1:length(REGOPT_PARS) if isempty(REGOPT_PARS{j}) s = [s ' []']; elseif isstr(REGOPT_PARS{j}) s = [s ' ' REGOPT_PARS{j}]; elseif isdataset(REGOPT_PARS{j}) s = [s ' dataset']; elseif ismapping(REGOPT_PARS{j}) s = [s ' mapping']; elseif isstruct(REGOPT_PARS{j}) s = [s ' structure']; else s = [s ' ' num2str(REGOPT_PARS{j})]; end end fprintf(1,'\nParameters used: %s \n\n',s); else pars = REGOPT_PARS; end
github
jacksky64/imageProcessing-master
map.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/map.m
9,939
utf_8
83957b0af503a00779627d5493540bc5
%MAP Map a dataset, train a mapping or classifier, or combine mappings % % B = MAP(A,W) or B = A*W % % Maps a dataset A by a fixed or trained mapping (or classifier) W, % generating % a new dataset B. This is done object by object. So B has as many objects % (rows) as A. The number of features of B is determined by W. All dataset % fields of A are copied to B, except the feature labels. These are defined % by the labels stored in W. % % V = MAP(A,W) or B = A*W % % If W is an untrained mapping (or classifier), it is trained by the dataset A. % The resulting trained mapping (or classifier) is stored in V. % % V = MAP(W1,W2) or V = W1*W2 % % The two mappings W1 and W2 are combined sequentially. See SEQUENTIAL for % a description. The resulting combination is stored in V. % % See also DATASETS, MAPPINGS, SEQUENTIAL % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: map.m,v 1.19 2010/06/10 22:31:12 duin Exp $ function [d, varargout] = map(a,b,batch) prtrace(mfilename); % if map is already computed, take it % if map needs to be stored, do so. if nargout == 1 & nargin == 2 & stamp_map > 0 d = stamp_map(a,b); if ~isempty(d) return end end if nargin < 3, batch = []; end varargout = repmat({[]},[1, max((nargout-1),0)]); global CHECK_SIZES % enables the possibility to avoid checking of sizes [ma,ka] = size(a); [mb,kb] = size(b); % force batch processing for large datasets if isempty(batch) & ma >= 10000 batch = 1000; end if ~isempty(batch) & ismapping(b) & isdataset(a) & ~isfeatim(a) & getbatch(b) % batch mode s = sprintf('Mapping %i objects: ',ma); prwaitbar(ma,s); %DXD map the first batch to setup the output dataset: dd = map(a(1:batch,:),b); %DXD first test if we are dealing with a mapping that outputs just a %single value (like testc): nb = size(dd,1); average_output = 0; if (nb~=batch) if (nb==1) warning('prtools:map:AverageBatchOutputs',... ['The mapping appears to return a single object from a input',... newline,... 'dataset. The objects resulting from different batches in the batch',... newline,'processing will be *averaged*.']); average_output = 1; end end kb = size(dd,2); nobatch = 0; if isdataset(dd) d = setdata(a,zeros(ma,kb)); % d = dataset(zeros(ma,kb),getlabels(a)); % d = setlablist(dd,getlablist(dd)); % if ~isempty(a,'prior') % d = setprior(d,getprior(a,0)); % end d = setfeatlab(d,getfeatlab(dd)); elseif isa(dd,'double') d = zeros(ma,kb); else % irregular, escape from batch processing nobatch = 1; prwaitbar(0); end d(1:batch,:) = dd; if ~nobatch n = floor(ma/batch); prwaitbar(ma,batch,[s int2str(batch)]); for j=2:n L = (j-1)*batch+1:j*batch; aa = doublem(a(L,:)); d(L,:) = map(aa,b); prwaitbar(ma,j*batch,[s int2str(j*batch)]); end L = n*batch+1:ma; if ~isempty(L) aa = doublem(a(L,:)); dd = map(aa,b); d(L,:) = dd; end if isdataset(d) featlabd = getfeatlab(d); d = setdat(a,d); d = setfeatlab(d,featlabd); end if average_output d = mean(d,1); end prwaitbar(0); return end end if iscell(a) | iscell(b) % if (iscell(a) & min([ma,ka]) ~= 1) | (iscell(b)& min([mb,kb]) ~= 1) % error('Only one-dimensional cell arrays are supported') % end if iscell(a) & ~iscell(b) d = cell(size(a)); [n,s,count] = prwaitbarinit('Mapping %i cells: ',numel(a)); for i = 1:size(a,1); for j = 1:size(a,2); d{i,j} = map(a{i,j},b); count = prwaitbarnext(n,s,count); end end elseif ~iscell(a) & iscell(b) d = cell(size(b)); [n,s,count] = prwaitbarinit('Mapping %i cells: ',numel(b)); for i = 1:size(b,1); for j = 1:size(b,2); d{i,j} = map(a,b{i,j}); count = prwaitbarnext(n,s,count); end end else if size(a,2) == 1 & size(b,1) == 1 d = cell(length(a),length(b)); [n,s,count] = prwaitbarinit('Mapping %i cells: ',numel(d)); for i = 1:length(a) for j = 1:length(b) d{i,j} = map(a{i},b{j}); count = prwaitbarnext(n,s,count); end end elseif all(size(a) == size(b)) d = cell(size(a)); [n,s,count] = prwaitbarinit('Mapping %i cells: ',numel(d)); for i = 1:size(a,1) for j = 1:size(a,2) d{i,j} = map(a{i,j},b{i,j}); count = prwaitbarnext(n,s,count); end end else error('Cell sizes do not match') end end return end if all([ma,mb,ka,kb] ~= 0) & ~isempty(a) & ~isempty(b) & ka ~= mb & CHECK_SIZES error(['Output size of first argument should match input size of second.' ... newline 'Checking sizes might be skipped by defining gloabal CHECK_SIZES = 0']) end if isa(a,'mapping') & isa(b,'mapping') if isempty(b) % empty mappings are treated as unity mappings d = a; elseif istrained(a) & isaffine(a) & istrained(b) & isaffine(b) % combine affine mappings d = affine(a,b); else d = sequential(a,b); end elseif isa(a,'dataset') | isa(a,'datafile') | isa(a,'double') | isa(a,'uint8') | isa(a,'uint16') | isa(a,'dipimage') if isa(a,'uint8') | isa(a,'uint16') | isa(a,'dipimage') a = double(a); end if ~isa(b,'mapping') error('Second argument should be mapping or classifier') end if isempty(b) % treat empty mappings as unity mappings d = a; return % produce empty mapping (i.e. unity mapping) % if input data is empty elseif isempty(a) d = mapping([]); return % handle scalar * mapping by .* (see times.m) elseif isa(a,'double') & ka == 1 & ma == 1 d = a.*b; return; end mapp = getmapping_file(b); if isuntrained(b) pars = +b; if issequential(b) | isstacked(b) | isparallel(b) %iscombiner(feval(mapp)) % sequentiall, parallel and stacked need % special treatment as untrained combiners % matlab 5 cannot handle the case [d, varargout{:}] = feval when varargout is empty % because of this we have next piece of code if isempty(varargout) d = feval(mapp,a,b); else [d, varargout{:}] = feval(mapp,a,b); end else if ~iscell(pars), pars = {pars}; end if isempty(varargout) d = feval(mapp,a,pars{:}); else [d, varargout{:}] = feval(mapp,a,pars{:}); end end if ~isa(d,'mapping') error('Training an untrained classifier should produce a mapping') end if getout_conv(b) > 1 d = d*classc; end d = setscale(d,getscale(b)*getscale(d)); name = getname(b); if ~isempty(name) d = setname(d,name); end d = setbatch(d,getbatch(b)); elseif isdatafile(a) & istrained(b) if issequential(b) d = feval(mapp,a,b); else d = addpostproc(a,{b}); % just add mapping to postprocesing and execute later end elseif isdatafile(a) try % try whether this is a mapping that knows how to handle a datafile pars = getdata(b); % parameters supplied in fixed mapping definition if nargout > 0 if isempty(varargout) d = feval(mapp,a,pars{:}); else [d, varargout{:}] = feval(mapp,a,pars{:}); end else feval(mapp,a,pars{:}) return end catch [lastmsg,lastid] = lasterr; if ~strcmp(lastid,'prtools:nodatafile') error(lastmsg); end d = addpostproc(a,{b}); % just add mapping to postprocesing and execute later return end elseif isfixed(b) & isparallel(b) d = parallel(a,b); elseif isfixed(b) | iscombiner(b) if ~isdataset(a) a = dataset(a); end pars = getdata(b); % parameters supplied in fixed mapping definition if ~iscell(pars), pars = {pars}; end if nargout > 0 if isempty(varargout) fsize = getsize_in(b); if any(fsize~=0) & ~isobjim(a) a = setfeatsize(a,fsize); % needed to set object images, sometimes end d = feval(mapp,a,pars{:}); % sequential mappings are split! Solve there! else [d, varargout{:}] = feval(mapp,a,pars{:}); end else feval(mapp,a,pars{:}) return end elseif istrained(b) if ~isdataset(a) a = dataset(a); end if isempty(varargout) fsize = getsize_in(b); if any(fsize~=0) & ~isobjim(a) a = setfeatsize(a,fsize); % needed to set object images, sometimes end d = feval(mapp,a,b); else [d, varargout{:}] = feval(mapp,a,b); end if ~isreal(+d) prwarning(2,'Complex values appeared in dataset'); end if isdataset(d) d = setcost(d,b.cost); % see if we have reasonable data in the dataset end else error(['Unknown mapping type: ' getmapping_type(b)]) end if isdataset(d) % we assume that just a basic dataset is returned, % including setting of feature labels, but that scaling % and outputconversion still have to be done. % scaling v = getscale(b); if length(v) > 1, v = repmat(v(:)',ma,1); end d = v.*d; % outputconversion switch getout_conv(b); case 1 % SIGM output if size(d,2) == 1 d = [d -d]; % obviously still single output discriminant d = setfeatlab(d,d.featlab(1:2,:)); end d = sigm(d); case 2 % NORMM output if size(d,2) == 1 d = [d 1-d]; % obviously still single output discriminant d = setfeatlab(d,d.featlab(1:2,:)); end % needs conversion to two-classes before normm d = normm(d); case 3 % SIGM and NORMM output if size(d,2) == 1 d = [d -d]; % obviously still single output discriminant d = setfeatlab(d,d.featlab(1:2,:)); end % needs conversion to two-classes before sigmoid d = sigm(d); d = normm(d); end %DXD finally, apply the cost matrix when it is defined in the %mapping/dataset: d = costm(d); end elseif isa(a,'mapping') if isa(b,'dataset') error('Datasets should be given as first argument') elseif isdouble(b) & isscalar(b) d = setscale(a,b*getscale(a)); elseif istrained(a) & isdouble(b) d = a*affine(b); else error('Mapping not supported') end else %a b error('Data type not supported') end
github
jacksky64/imageProcessing-master
filtim.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/filtim.m
5,011
utf_8
bd97d5621d52f453ea77064e9fa1a408
%FILTIM Mapping to filter multiband image objects in datasets and datafiles % % B = FILTIM(A,FILTER_COMMAND,{PAR1,PAR2,....},SIZE) % B = A*FILTIM([],FILTER_COMMAND,{PAR1,PAR2,....},SIZE) % % INPUT % A Dataset or datafile with multi-band image objects % FILTER_COMMAND String with function name % {PAR1, ... } Cell array with optional parameters to FILTER_COMMAND % SIZE Output size of the mapping (default: input size) % % OUTPUT % B Dataset containing multi-band images processed by % FILTER_COMMAND, band by band. % % DESCRIPTION % For each band of each object stored in A a filter operation is performed as % % OBJECT_OUT = FILTER_COMMAND(OBJECT_IN,PAR1,PAR2,....) % % The results are collected and stored in B. In case A (and thereby B) is % a datafile, execution is postponed until conversion into a dataset, or a % call to SAVEDATAFILE. % % The difference between FILTIM and the similar command FILTM is that % FILTIM is aware of the band structure of the objects. As FILTIM treats % the bands separately it cannot be used for commands that change the number % of bands (like RGB2GRAY) or need to access them all. % % EXAMPLE % a = delft_images; b = a(120 121 131 230)*col2gray % e = b*filtim([],'fft2')*filtim([],'abs')*filtim([],'fftshift'); % figure; show(e); figure; show((1+e)*filtim([],'log')); % % SEE ALSO % DATASETS, DATAFILES, IM2OBJ, DATA2IM, IM2FEAT, DATGAUSS, DATFILT, FILTM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = filtim(a,command,pars,outsize) prtrace(mfilename); if nargin < 4, outsize = []; end if nargin < 3, pars = {}; end if nargin < 2 error('No command given') end if ~iscell(pars), pars = {pars}; end mapname = 'Dataset/file band filtering'; if isempty(a) % no data, so just mapping definition b = mapping(mfilename,'fixed',{command,pars}); if ~isempty(outsize) b = setsize_out(b,outsize); end b = setname(b,mapname); elseif isdatafile(a) % for datafiles filters will be stored isobjim(a); if isempty(getpostproc(a)) % as preprocessing (if no postproc defined) b = addpreproc(a,mfilename,{command pars},outsize); else % or as mapping as postprocessing v = mapping(mfilename,'fixed',{command,pars}); if ~isempty(outsize) v = setsize_out(v,outsize); end v = setname(v,mapname); b = addpostproc(a,v); end elseif isdataset(a) % convert to image and process isobjim(a); m = size(a,1); d = data2im(a); out = feval(mfilename,d,command,pars); % effectively jumps to double (below) fsize = size(out); if m > 1 fsize = fsize(1:3); if fsize(3) == 1 fsize = fsize(1:2); end end % store processed images in dataset b = setdata(a,im2obj(out,fsize)); b = setfeatsize(b,fsize); else % double % make imsize 4D: horz*vert*bands*objects imsize = size(a); if length(imsize) == 2 imsize = [imsize 1 1]; elseif length(imsize) == 3 imsize = [imsize 1]; end % find size of first image first = execute(command,getsubim(a,1,1),pars); %first = feval(command,getsubim(a,1,1),pars{:}); if all(imsize(3:4) == 1) % preserve DipLib format for the time being b = first; return end first = double(first); % for Dip_Image users outsize = size(first); if length(outsize) == 3 % single subimage generates multiple bands !! b = repmat(first(:,:,1),[1 1 imsize(3)*outsize(3) imsize(4)]); else b = repmat(first,[1 1 imsize(3:4)]); end % process all other images [nn,s,count] = prwaitbarinit('Filtering %i images',imsize(4)); for j = 1:imsize(4) for i = 1:imsize(3) ima = double(execute(command,getsubim(a,i,j),pars)); %ima = double(feval(command,getsubim(a,i,j),pars{:})); if (any(outsize ~= size(ima))) % check size error('All image sizes should be the same') end if length(outsize) == 2 % simple case: image_in --> image_out b(:,:,i,j) = ima; else % advanced: image_in --> bands out b(:,:,i:imsize(3):end,j) = ima; end end count = prwaitbarnext(imsize(4),'Filtering %i images: ',count); end end return function asub = getsubim(a,i,j) % needed as Dip_Image cannot handle 4d subsript if data is 2d or 3d n = ndims(a); if n == 2 if i ~= 1 | j ~= 1 error('Illegal image requested') end asub = a; elseif n == 3 if j ~= 1 error('Illegal image requested') end asub = a(:,:,i); elseif n == 4 asub = a(:,:,i,j); else error('Incorrect image supplied') end function out = execute(command,a,pars) exist_command = exist(command); if isstr(command) & any([2 3 5 6] == exist_command) out = feval(command,a,pars{:}); elseif ismapping(command) out = map(a,command); else error([command ': Filter command not found']) end return
github
jacksky64/imageProcessing-master
resizem.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/resizem.m
1,270
utf_8
ce577df4423128217dbf0c54502e6915
%RESIZEM Mapping for resizing object images in datasets and datafiles %(outdated, rplaced by im_resize) % % B = RESIZEM(A,SIZE,METHOD) % B = A*RESIZEM([],SIZE,METHOD) % % INPUT % A Dataset or datafile % SIZE Desired size % METHOD Method, see IMRESIZE % % OUTPUT % B Dataset or datafile % % DESCRIPTION % The objects stored as images in the dataset or datafile A are resized % using the IMRESIZE command. Default METHOD is 'nearest' (nearest neighbor % interpolation. In SIZE the desired output size has to be stored. Note % that for proper use in PRTools third size parameter of multi-band images, % e.g. 3 for RGB images, has to be supplied. % % SEE ALSO % MAPPINGS, DATASETS, DATAFILES, IM2OBJ, DATA2IM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = resizem(a,imsize,method) if nargin < 3 | isempty(method) method = 'nearest'; end if isempty(a) b = mapping(mfilename,'fixed',{imsize,method}); b = setname(b,'image resize'); b = setsize_out(b,imsize); return end isvaldfile(a,0); if isdataset(a) isobjim(a); end b = filtm(a,'imresize',{imsize(1:2),method},imsize);
github
jacksky64/imageProcessing-master
testdatasize.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testdatasize.m
2,682
utf_8
28a7eda7986d21fdcc452f3bf4accf70
%TESTDATASIZE of datafiles and convert to dataset % % B = TESTDATASIZE(A,STRING,FLAG) % % INPUT % A DATAFILE or DATASET % STRING 'data' (default) or 'features' or 'objects' % FLAG TRUE / FALSE, (1/0) (Default TRUE) % % OUTPUT % B DATASET (if FLAG == 1 and conversion possible) % TRUE if FLAG == 0 and conversion possible % FALSE if FLAG == 0 and conversion not possible% % DESCRIPTION % If FLAG == 1, depending on the value of PRMEMORY and the size of the % datafile A, it is converted to a dataset, otherwise an error is generated. % If FLAG == 0, depending on the value of PRMEMORY and the size of the % datafile A, the output B is set to TRUE (conversion possible) or FALSE % (conversion not possible). % % The parameter STRING controls the type of comparison: % % 'data' PROD(SIZE(A)) < PRMEMORY % 'objects' SIZE(A,1).^2 < PRMEMORY % 'features' SIZE(A,2).^2 < PRMEMORY % % SEE ALSO % DATASETS, DATAFILES, PRMEMORY % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = testdatasize(a,type,flag) prtrace(mfilename); if nargin < 3, flag = 1; end if nargin < 2 type = 'data'; end %if isdataset(a) & 0 % neglect: test of datasets not appropriate if isdataset(a) | isdouble(a) if flag b = a; else b = 1; end return end % Now we have a datafile a = setfeatsize(a,0); % featsize of datafiles is unreliable b = 1; switch type case 'data' if prod(size(a)) > prmemory if flag error(['Dataset too large for memory.' newline ... 'Size is ' int2str(prod(size(a))) ', memory is ' int2str(prmemory) newline ... 'Reduce the data or increase the memory by prmemory.']) else b = 0; end end case 'objects' if size(a,1).^2 > prmemory if flag error(['Number of objects too large for memory.' newline ... 'Size is ' int2str(size(a,1).^2) ', memory is ' int2str(prmemory) newline ... 'Reduce the data or increase the memory by prmemory.']) else b = 0; end end case 'features' if size(a,2).^2 > prmemory if flag error(['Number of features too large for memory.' newline ... 'Size is ' int2str(size(a,2).^2) ', memory is ' int2str(prmemory) newline ... 'Reduce the data or increase the memory by prmemory.']) else b = 0; end end otherwise error('Unknown test requested') end if nargout > 0 if flag b = dataset(a); end end return
github
jacksky64/imageProcessing-master
nu_svr.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nu_svr.m
4,319
utf_8
8eaeaa6ed5f4f5b39397258f05ca1b8e
%NU_SVR Support Vector Classifier: NU algorithm % % [W,J,C] = NU_SVR(A,TYPE,PAR,C,SVR_TYPE,NU_EPS,MC,PD) % % INPUT % A Dataset % TYPE Type of the kernel (optional; default: 'p') % PAR Kernel parameter (optional; default: 1) % C Regularization parameter (0 < C < 1): expected fraction of SV % (optional; default: 0.25) % SVR_TYPE This type can be 'nu' or 'epsilon' % NU_EPS The corresponding value for NU or epsilon % MC Do or do not data mean-centering (optional; default: 1 (to do)) % PD Do or do not the check of the positive definiteness (optional; % default: 1 (to do)) % % OUTPUT % W Mapping: Support Vector Classifier % J Object identifiers of support objects % C Equivalent C regularization parameter of SVM-C algorithm % % DESCRIPTION % Optimizes a support vector classifier for the dataset A by % quadratic programming. The classifier can be of one of the types % as defined by PROXM. Default is linear (TYPE = 'p', PAR = 1). In J % the identifiers of the support objects in A are returned. % % C belogs to the interval (0,1). C close to 1 allows for more class % overlap. Default C = 0.25. % % C is bounded from above by NU_MAX = (1 - ABS(Lp-Lm)/(Lp+Lm)), where % Lp (Lm) is the number of positive (negative) samples. If NU > NU_MAX % is supplied to the routine it will be changed to the NU_MAX. % % If C is less than some NU_MIN which depends on the overlap between % classes algorithm will typically take long time to converge (if at % all). So, it is advisable to set NU larger than expected overlap. % % Output is rescaled in a such manner as if it were returned by SVC with % the parameter C. % % % SEE ALSO % NU_SVRO, SVO, SVC, MAPPINGS, DATASETS, PROXM % Copyright: S.Verzakov, [email protected] % Based on SVC.M by D.M.J. Tax, D. de Ridder, R.P.W. Duin % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: nu_svr.m,v 1.2 2009/01/31 18:43:11 duin Exp $ function [W, J, epsilon_or_nu] = nu_svcr(a,type,par,C,svr_type,nu_or_epsilon,mc,pd) prtrace(mfilename); if nargin < 2 | ~isa(type,'mapping') if nargin < 8 pd = 1; end if nargin < 7 mc = 1; end if nargin < 6 nu_or_epsilon = []; end if nargin < 5 | isempty(svr_type) svr_type = 'epsilon'; end switch svr_type case 'nu' if isempty(nu_or_epsilon) prwarning(3,'nu is not specified, assuming 0.25.'); nu_or_epsilon = 0.25; end %nu = nu_or_epsilon; case {'eps', 'epsilon'} svr_type = 'epsilon'; if isempty(nu_or_epsilon) prwarning(3,'epsilon is not specified, assuming 1e-2.'); nu_or_epsilon = 1e-2; end %epsilon = nu_or_epsilon; end if nargin < 4 | isempty(C) prwarning(3,'C set to 1\n'); C = 1; end if nargin < 3 | isempty(par) par = 1; prwarning(3,'Kernel parameter par set to 1\n'); end if nargin < 2 | isempty(type) type = 'p'; prwarning(3,'Polynomial kernel type is used\n'); end if nargin < 1 | isempty(a) W = mapping(mfilename,{type,par,C,svr_type,nu_or_epsilon,mc,pd}); W = setname(W,['Support Vector Regression (' svr_type ' algorithm)']); return; end islabtype(a,'targets'); [m,k] = getsize(a); y = gettargets(a); % The 1-dim SVR if size(y,2) == 1 % 1-dim regression uy = mean(y); y = y - uy; if mc u = mean(a); a = a - ones(m,1)*u; else u = []; end K = a*proxm(a,type,par); % Perform the optimization: [v,J,epsilon_or_nu] = nu_svro(+K,y,C,svr_type,nu_or_epsilon,pd); % Store the results: v(end) = v(end)+uy; W = mapping(mfilename,'trained',{u,a(J,:),v,type,par},getlablist(a),k,1); W = setname(W,['Support Vector Regression (' svr_type ' algorithm)']); %W = setcost(W,a); J = getident(a,J); %J = a.ident(J); else error('multivariate SVR is not supported'); end else % execution w = +type; m = size(a,1); % The first parameter w{1} stores the mean of the dataset. When it % is supplied, remove it from the dataset to improve the numerical % precision. Then compute the kernel matrix using proxm. if isempty(w{1}) d = a*proxm(w{2},w{4},w{5}); else d = (a-ones(m,1)*w{1})*proxm(w{2},w{4},w{5}); end % When Data is mapped by the kernel, now we just have a linear % regression w*x+b: d = [d ones(m,1)] * w{3}; W = setdat(a,d,type); end return;
github
jacksky64/imageProcessing-master
reducm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/reducm.m
1,511
utf_8
17bcfd079a7d710c4b823060e4dc27e4
%REDUCM Reduce to minimal space % % W = REDUCM(A) % % Ortho-normal mapping to a space in which the dataset A exactly fits. % This is useful for datasets with more features than objects. For the % objects in B = A*W holds that their dimensionality is minimum, their mean % is zero, the covariance matrix is diagonal with decreasing variances and % the inter-object distances are equal to those of A. % % For this mapping just the labeled objects in A are used, unless A is % entirely unlabeled. In that case all objects are used. % % See also MAPPINGS, DATASETS, NLFISHERM, KLM, PCA % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: reducm.m,v 1.5 2010/02/08 15:29:48 duin Exp $ function W = reducm(a) prtrace(mfilename); if nargin < 1 | isempty(a) W = mapping('reducm'); W = setname(W,'Reduction mapping'); return end a = testdatasize(a); % Find the subspace R of dataset 'a' (actually data matrix 'b'): b = +cdats(a,1); [m,k] = size(b); [R,s,v] = prsvd(b',0); % Map the data: b = b*R; % Find the number of non-singular dimensions % (can be found from svd??) r = rank(b); if r == m, r = r-1; end % Order the dimensions according to the variance: % Overdone if we have already the svd G = prcov(b); [F V] = preig(G); [v,I] = sort(-diag(V)); I = I(1:r); % And store the result in an affine mapping: R = R*F(:,I); W = affine(R,-mean(b*F(:,I)),a); return
github
jacksky64/imageProcessing-master
classim.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/classim.m
1,941
utf_8
f32ac66484a886f0f8055dc61dd99584
%CLASSIM Classify image and return resulting label image % % LABELS = CLASSIM(Z) % LABELS = CLASSIM(A,W) % LABELS = A*W*CLASSIM % % INPUT % Z Classified dataset, or % A,W Dataset and classifier mapping % % OUTPUT % LABELS Label image % When no output is requested, the label image is displayed. % % DESCRIPTION % Returns an image with the labels of the classified dataset image Z % (typically, the result of a mapping or classification A*W in which A is % a set of images stored as features using IM2FEAT). For each object in % Z (a pixel), a numeric class label is returned. The colormap is loaded % automatically. % % Note that if the number of classes is small, e.g. 2, an appropriate % colormap has to be loaded for displaying the result by IMAGE(LABELS), % or more appropriately, LABELS should be multiplied such that the minimum % and maximum of LABELS are well spread in the [1,64] interval of the % standard colormaps. % % EXAMPLES % PREX_SPATM % % SEE ALSO % MAPPINGS, DATASETS, IM2FEAT, LABELD % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: classim.m,v 1.3 2007/09/09 21:21:20 duin Exp $ function labels = classim(a,w) prtrace(mfilename); % Untrained mapping if nargin == 0 labels = mapping('classim','fixed'); return end if nargin == 2 ismapping(w); a = a*w; end % Assertion: generate an error, if a is not a dataset with objects as pixels isfeatim(a); if size(a,2) == 1 % Assuming the 2-class case J = 2 - (double(a) >= 0); else % Multi-class problem [mx,J] = max(double(a),[],2); end %fl = renumlab(getfeatlab(a)); %labels = reshape(fl(J),getobjsize(a)); labels = reshape(J,getobjsize(a)); % Display the label image if nargout == 0 n = 61/(size(a,2) +0.5); imagesc(labels*n) colormap colorcube clear labels end return;
github
jacksky64/imageProcessing-master
gendatb.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatb.m
1,475
utf_8
785af17a0d25f1cc4ff2a4c43265dabc
%GENDATB Generation of banana shaped classes % % A = GENDATB(N,S) % % INPUT % N number of generated samples of vector with % number of samples per class % S variance of the normal distribution (opt, def: s=1) % % OUTPUT % A generated dataset % % DESCRIPTION % Generation of a 2-dimensional 2-class dataset A of N objects with a % banana shaped distribution. The data is uniformly distributed along the % bananas and is superimposed with a normal distribution with standard % deviation S in all directions. Class priors are P(1) = P(2) = 0.5. % Defaults: N = [50,50], S = 1. % % SEE ALSO % DATASETS, PRDATASETS % Copyright: A. Hoekstra, R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: gendatb.m,v 1.3 2008/03/20 07:53:58 duin Exp $ function a = gendatb(N,s) prtrace(mfilename); if nargin < 1, N = [50,50]; end if nargin < 2, s = 1; end % Default size of the banana: r = 5; % Default class prior probabilities: p = [0.5 0.5]; N = genclass(N,p); domaina = 0.125*pi + rand(1,N(1))*1.25*pi; a = [r*sin(domaina') r*cos(domaina')] + randn(N(1),2)*s; domainb = 0.375*pi - rand(1,N(2))*1.25*pi; a = [a; [r*sin(domainb') r*cos(domainb')] + randn(N(2),2)*s + ... ones(N(2),1)*[-0.75*r -0.75*r]]; lab = genlab(N); a = dataset(a,lab,'name','Banana Set','lablist',genlab([1;1]),'prior',p); return
github
jacksky64/imageProcessing-master
im_invert.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_invert.m
743
utf_8
934a5a84ab57a0240f1787e6af4d17c7
%IM_INVERT Inversion of images stored in a dataset % % A = IM_INVERT(A) % A = A*IM_INVERT % % Inverts image A by subtracting it from its maximum % % SEE ALSO % DATASETS, DATAFILES % Copyright: D. de Ridder, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_invert(a) prtrace(mfilename); if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed'); b = setname(b,'Image inverse'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image if isa(a,'dip_image'), a = double(a); end b = max(max(max(a)))-a; end return
github
jacksky64/imageProcessing-master
disnorm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/disnorm.m
1,646
utf_8
17034f60f84d0b97b101998541c77e85
%DISNORM Normalization of a dissimilarity matrix % % V = DISNORM(D,OPT) % F = E*V % % INPUT % D NxN dissimilarity matrix or dataset, which sets the norm % E Matrix to be normalized, e.g. D itself % OPT 'max' : maximum dissimilarity is set to 1 by global rescaling % 'mean': average dissimilarity is set to 1 by global rescaling (default) % % OUTPUT % V Fixed mapping % F Normalized dissimilarity data % % DEFAULT % OPT = 'mean' % % DESCRIPTION % Operation on dissimilarity matrices, like the computation of classifiers % in dissimilarity space, may depend on the scaling of the dissimilarities % (a single scalar for the entire matrix). This routine computes a scaling % for a giving matrix, e.g. a training set and applies it to other % matrices, e.g. the same training set or based on a test set. % Copyright: Elzbieta Pekalska, [email protected] % Faculty EWI, Delft University of Technology and % School of Computer Science, University of Manchester function V = disnorm(D,opt) if nargin < 2, opt = 'mean'; end if nargin == 0 | isempty(D) V = mapping(mfilename,{opt}); V = setname(V,'Disnorm'); return end if ~isdataset(D) D = dataset(D,1); D = setfeatlab(D,getlabels(D)); end %DEFINE mapping if isstr(opt) % discheck(D); opt = lower(opt); if strcmp(opt,'mean') n = size(D,1); m = sum(sum(+D))/(n*(n-1)); elseif strcmp(opt,'max') m = max(D(:)); else error('Wrong OPT.') end if nargout > 1 D = D./m; end V = mapping(mfilename,'trained',{m},[],size(D,2),size(D,2)); return; end % APPLY mapping if ismapping(opt) opt = getdata(opt,1); V = D./opt; return; end
github
jacksky64/imageProcessing-master
prinv.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prinv.m
309
utf_8
89acc1f05a67a2900135b943a8cd4614
%PRINV Call to INV() including PRWAITBAR % % B = PRINV(A) % % This calls B = INV(A) and includes a message to PRWAITBAR % in case of a large A function B = prinv(A) [m,n] = size(A); if min([m,n]) >= 500 prwaitbaronce('Inverting %i x %i matrix ...',[m,n]); B = inv(A); prwaitbar(0); else B = inv(A); end
github
jacksky64/imageProcessing-master
matchlablist.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/matchlablist.m
1,366
utf_8
ac9318c7c49e2c458090ca4d64934eea
%MATCHLABLIST Match entries of lablist1 with lablist2 % % I = MATCHLABLIST(LABLIST1,LABLIST2) % % INPUT % LABLIST1 list of class names % LABLIST2 list of class names % % OUTPUT % I indices for LABLIST1 appearing in LABLIST2 % % DESCRIPTION % Find the indices of places where the entries of LABLIST1 appear % in LABLIST2, i.e. LABLIST1 = LABLIST2(I). % Note that this operation is not symmetric, changing the order of % LABLIST1 and LABLIST2 changes I! % I(i) = 0 for labels appearing in LABLIST1 that are not in LABLIST2. % % SEE ALSO % DATASETS, RENUMLAB % Copyright: D.M.J. Tax [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function I = matchlablist(lablist1,lablist2) prtrace(mfilename); n = size(lablist1,1); I = zeros(n,1); % the resulting vector if isempty(lablist2) % nothing fits return end if iscell(lablist1) & iscell(lablist2) lablist1 = char(lablist1); lablist2 = char(lablist2); end for i=1:n if isstr(lablist1) & isstr(lablist2) tmp = strmatch(deblank(lablist1(i,:)),lablist2,'exact'); elseif ~isstr(lablist1) & ~isstr(lablist2) tmp = find(~sum((lablist2 ~= repmat(lablist1(i),size(lablist2,1),1)),2)); else tmp = zeros(size(lablist1,1),1); end if ~isempty(tmp) I(i) = tmp(1); else I(i) = 0; end end return
github
jacksky64/imageProcessing-master
gendatl.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatl.m
1,532
utf_8
aba983637cf024f09083ee34afe47bb2
%GENDATL Generation of Lithuanian classes % % A = GENDATL(N,S) % % INPUT % N Number of objects per class (optional; default: [50 50]) % S Standard deviation for the data generation (optional; default: 1) % % OUTPUT % A Dataset % % DESCRIPTION % Generation of Lithuanian classes, a 2-dimensional, 2-class dataset A % of N objects according to the definition given by Raudys. % The data is uniformly distributed along two sausages and is superimposed % by a normal distribution with standard deviation S in all directions. % Class priors are P(1) = P(2) = 0.5. % % SEE ALSO % DATASETS, PRDATASETS % Copyright: M. Skurichina, R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: gendatl.m,v 1.3 2007/06/19 11:44:14 duin Exp $ function a = gendatl(N,s) prtrace(mfilename); if nargin < 1, prwarning(3,'Class cardinalities are not specified, assuming [50 50].'); N = [50 50]; end if nargin < 2, prwarning(4,'Standard deviation for the data generation is not specified, assuming 1.'); s = 1; end if (length(N) == 1), N(2) = N(1); end; u1 = 2*pi/3*(rand(N(1),1)-0.5*ones(N(1),1)); u2 = 2*pi/3*(rand(N(2),1)-0.5*ones(N(2),1)); a = [[10*cos(u1) + s*randn(N(1),1) 10*sin(u1) + s*randn(N(1),1)]; ... [6.2*cos(u2) + s*randn(N(2),1) 6.2*sin(u2) + s*randn(N(2),1)]]; lab = genlab(N); a = dataset(a,lab,'name','Lithuanian Classes'); a = setlablist(a,[1 2]'); a = setprior(a,[0.5 0.5]); return;
github
jacksky64/imageProcessing-master
invsigm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/invsigm.m
1,435
utf_8
15b41aa9cbad0fb4cad94337d3a9eb78
%INVSIGM Inverse sigmoid map % % W = W*INVSIGM % B = INVSIGM(ARG) % % INPUT % ARG Mapping/Dataset % % OUTPUT % W Mapping transforming posterior probabilities into distances. % % DESCRIPTION % The inverse sigmoidal transformation to transform a classifier to a % mapping, transforming posterior probabilities into distances. % % SEE ALSO % MAPPINGS, DATASETS, CLASSC, SIGM % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: invsigm.m,v 1.3 2007/03/22 08:54:59 duin Exp $ function w = invsigm(arg) prtrace(mfilename); if nargin == 0 % Create an empty mapping: w = mapping('invsigm','combiner'); w = setname(w,'Inverse Sigmoidal Mapping'); elseif isa(arg,'mapping') % If the mapping requested a SIGM transformation (out_conv=1), it % is now removed (out_conv=0): if arg.out_conv == 1 w = set(arg,'out_conv',0); if arg.size_out == 2 w.size_out = 1; w.labels = w.labels(1,:); data.rot = w.data.rot(:,1); data.offset = w.data.offset(1); data.lablist_in = w.data.lablist_in; w.data = data; end else w_s = setname(mapping('invsigm','fixed'),'Inverse Sigmoidal Mapping'); w = arg*w_s; end else % The data is really transformed: if isdatafile(arg) w = addpostproc(arg,invsigm); else % datasets and doubles w = log(arg+realmin) - log(1-arg+realmin); end end return
github
jacksky64/imageProcessing-master
isdataim.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isdataim.m
956
utf_8
541eb52b33cb75affee631ee0b4db63f
%ISDATAIM Returns true if a dataset contains image objects or image features % % N = ISDATAIM(A) % % INPUT % A Dataset % % OUTPUT % N Scalar: 1 if A contains images as objects or features, otherwise 0 % % DESCRIPTION % If no output argument is given, the function will produce an error if A does % not contain image objects or features (i.e. it will act as an assertion). % % SEE ALSO % ISOBJIM, ISFEATIM % $Id: isdataim.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function n = isdataim (a) prtrace(mfilename); if (nargin < 1) error('Insufficient number of arguments.'); end % The FEATSIZE and OBJSIZE fields of a dataset indicate whether it contains % images. n = (isa(a,'dataset')) & ((length(a.featsize) > 1) | (length(a.objsize) > 1)) ; % Generate and error if the input is not a dataset with image data and % no output is requested (assertion). if (nargout == 0) & (n == 0) error('Dataset with images expected.') end return
github
jacksky64/imageProcessing-master
mogc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/mogc.m
2,240
utf_8
cc799611be99de1d4a78f49de3d7a6d6
%MOGC Mixture of Gaussian classifier % % W = MOGC(A,N) % W = A*MOGC([],N); % W = A*MOGC([],N,R,S); % % INPUT % A Dataset % N Number of mixtures (optional; default 2) % R,S Regularization parameters, 0 <= R,S <= 1, see QDC % OUTPUT % % DESCRIPTION % For each class j in A a density estimate is made by GAUSSM, using N(j) % mixture components. Using the class prior probabilities they are combined % into a single classifier W. If N is a scalar, this number is applied to % each class. The relative size of the components is stored in W.DATA.PRIOR. % % EXAMPLES % PREX_DENSITY % % SEE ALSO % DATASETS, MAPPINGS, QDC, PLOTM, TESTC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: mogc.m,v 1.6 2009/11/23 09:22:28 davidt Exp $ function w = mogc(a,n,r,s); prtrace(mfilename); if nargin < 4, s = 0; end if nargin < 3, r = 0; end if nargin < 2, n = 2; end if nargin < 1 | isempty(a) w = mapping(mfilename,{n,r,s}); w = setname(w,'MoG Classifier'); return end islabtype(a,'crisp','soft'); isvaldfile(a,n,2); % at least n objects per class, 2 classes % Initialize all the parameters: a = testdatasize(a); a = testdatasize(a,'features'); [m,k,c] = getsize(a); p = getprior(a); a = setprior(a,p); if length(n) == 1 n = repmat(n,1,c); end if length(n) ~= c error('Numbers of components does not match number of classes') end w = []; d.mean = zeros(sum(n),k); d.cov = zeros(k,k,sum(n)); d.prior = zeros(1,sum(n)); d.nlab = zeros(1,sum(n)); d.det = zeros(1,sum(n)); if(any(classsizes(a)<n)) error('One or more class sizes too small for desired number of components') end % Estimate a MOG for each of the classes: w = []; n1 = 1; for j=1:c n2 = n1 + n(j) - 1; b = seldat(a,j); %b = setlabtype(b,'soft'); v = gaussm(b,n(j),r,s); d.mean(n1:n2,:) = v.data.mean; d.cov(:,:,n1:n2)= v.data.cov; d.prior(n1:n2) = v.data.prior*p(j); d.nlab(n1:n2) = j; d.det(n1:n2) = v.data.det; n1 = n2+1; end w = mapping('normal_map','trained',d,getlablist(a),k,c); %w = normal_map(d,getlablist(a),k,c); w = setname(w,'MoG Classifier'); w = setcost(w,a); return;
github
jacksky64/imageProcessing-master
sigm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/sigm.m
1,231
utf_8
6c752530c0b60971e1d8bf944baa4512
%SIGM Sigmoid map % % W = W*SIGM % B = A*SIGM % W = W*SIGM([],SCALE) % B = SIGM(A,SCALE) % % INPUT % A Dataset (optional) % SCALE Scaling parameter (optional, default: 1) % % OUTPUT % W Sigmoid mapping, or % B Dataset A mapped by sigmoid mapping % % DESCRIPTION % Sigmoidal transformation, useful to transform a map to classifier, % producing posterior probability estimates. The parameter SCALE scales the % data first (A/SCALE), before the transformation. Default: SCALE = 1, i.e. % no scaling. % % SEE ALSO % DATASETS, MAPPINGS, CLASSC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: sigm.m,v 1.3 2007/04/13 09:31:44 duin Exp $ function out = sigm (a,scale) prtrace(mfilename); if (nargin < 2) prwarning(3,'no scale supplied, assuming 1'); scale = []; end % Depending on the type of call, return a mapping or sigmoid-mapped data. if (nargin == 0) | (isempty(a)) w = mapping(mfilename,'fixed',scale); w = setname(w,'Sigmoidal Mapping'); out = w; elseif (isempty(scale)) out = 1./(1+exp(-a)); else out = 1./(1+exp(-a/scale)); end return
github
jacksky64/imageProcessing-master
klldc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/klldc.m
1,713
utf_8
ee649fb58c45cab210ff1f23d1817d73
%KLLDC Linear classifier built on the KL expansion of the common covariance matrix % % W = KLLDC(A,N) % W = KLLDC(A,ALF) % % INPUT % A Dataset % N Number of significant eigenvectors % ALF 0 < ALF <= 1, percentage of the total variance explained (default: 0.9) % % OUTPUT % W Linear classifier % % DESCRIPTION % Finds the linear discriminant function W for the dataset A. This is done % by computing the LDC on the data projected on the first eigenvectors of % the averaged covariance matrix of the classes. Either first N eigenvectors % are used or the number of eigenvectors is determined such that ALF, the % percentage of the total variance is explained. (Karhunen Loeve expansion) % % If N (ALF) is NaN it is optimised by REGOPTC. % % SEE ALSO % MAPPINGS, DATASETS, PCLDC, KLM, FISHERM, REGOPTC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: klldc.m,v 1.4 2007/06/13 21:59:42 duin Exp $ function W = klldc(a,n) prtrace(mfilename); if nargin < 2 n = []; prwarning(4,'number of significant eigenvectors not supplied, 0.9 variance explained'); end if nargin == 0 | isempty(a) W = mapping('klldc',{n}); elseif isnan(n) % optimize regularisation parameter defs = {1}; parmin_max = [1,size(a,2)]; W = regoptc(a,mfilename,{n},defs,[1],parmin_max,testc([],'soft'),0); else islabtype(a,'crisp','soft'); isvaldfile(a,2,2); % at least 2 object per class, 2 classes a = testdatasize(a,'features'); a = setprior(a,getprior(a)); v = klm(a,n); W = v*ldc(a*v); W = setcost(W,a); end W = setname(W,'KL Bayes-Normal-1'); return
github
jacksky64/imageProcessing-master
weakc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/weakc.m
1,898
utf_8
f1146600c4e707fdea7974fe5cb918a0
%WEAKC Weak Classifier % % [W,V] = WEAKC(A,ALF,ITER,R) % VC = WEAKC(A,ALF,ITER,R,1) % % INPUT % A Dataset % ALF Fraction of objects to be used for training (def: 0.5) % ITER Number of trials % R R = 0: use NMC (default) % R = 1: use FISHERC % R = 2: use UDC % R = 3: use QDC % otherwise arbitrary untrained classifier % % OUTPUT % W Best classifier over ITER runs % V Cell array of all classifiers % Use VC = stacked(V) for combining % VC Combined set of classifiers % % WEAKC uses subsampled versions of A for training. Testing is done % on the entire training set A. The best classifier is returned in W. % % SEE ALSO % MAPPINGS, DATASETS, FISHERC, UDC, QDC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [w,v] = weakc(a,n,iter,r,s) prtrace(mfilename); % INITIALISATION if nargin < 5, s = 0; end if nargin < 4, r = 0; end if nargin <3, iter = 1; end if nargin < 2, n = 1; end if nargin < 1 | isempty(a) w = mapping(mfilename,{n,iter,r,s}); w = setname(w,'Weak'); return end % TRAINING v = {}; emin = 1; for it = 1:iter % Loop b = gendat(a,n); % subsample training set if ~ismapping(r) % select classifier and train if r == 0 ww = nmc(b); elseif r == 1 ww = fisherc(b); elseif r == 2 ww = udc(b); elseif r == 3 ww = qdc(b); else error('Illegal classifier requested') end else ww = b*r; end v = {v{:} ww}; % store all classifiers in v % select best classifier and store in w e = a*ww*testc; if e < emin emin = e; w = ww; end end if s == 1 w = stacked(v); end return
github
jacksky64/imageProcessing-master
bhatm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bhatm.m
3,010
utf_8
14b1869e8b30889e9d06b9665b57b7a4
%BHATM Bhattacharryya linear feature extraction mapping % % W = BHATM(A,N) % % INPUT % A Dataset % N Number of dimensions to map to (N >= 1), or fraction of cumulative % contribution to retain (0 < N < 1) % % OUTPUT % W Bhattacharryya mapping % % DESCRIPTION % Finds a mapping of the labeled dataset A onto an N-dimensional linear % subspace such that it maximizes the Bhattacharrryya distance between the % classes, assuming Gaussian distributions. Only for two-class datasets. % % SEE ALSO % MAPPINGS, DATASETS, FISHERM, NLFISHERM, KLM, PCA % Copyright: F. van der Heijden(1) and Dick de Ridder(2) % (1) Laboratory for Measurement and Instrumentation, Dept. of Electrical % Engineering, University of Twente, Enschede, The Netherlands % (2) Faculty of Electrical Engineering, Mathematics and Computer Science % Delft University of Technology, Mekelweg 4, 2628 CD Delft, The Netherlands % $Id: bhatm.m,v 1.5 2010/02/08 15:31:48 duin Exp $ function w = bhatm(a,n) prtrace(mfilename); if (nargin < 2) prwarning (4, 'fraction to map to not specified, assuming 0.9'); n = 0.9; end % If no arguments are specified, return an untrained mapping. if (nargin < 1) | (isempty(a)) w = mapping('bhatm',{n}); w = setname(w,'Bhatta mapping'); return end % Check input. a = testdatasize(a); islabtype(a,'crisp'); isvaldset(a,2,2); % At least 2 objects per class, 2 classes a = setprior(a,getprior(a)); % set priors to avoid unnecessary warnings [m,k,c] = getsize(a); if (c ~= 2) error ('works only on two-class datasets'); end; % Shift mean of data to origin. b = a*scalem(a); % Get class means and covariances. [U,G] = meancov(b); G1 = G(:,:,1); G2 = G(:,:,2); [E1,D1] = preig(G1); A = D1^-0.5*E1'; G2 = A*G2*A'; % Whiten the first class G2 = (G2+G2')/2; % Enforce symmetry [E2,D2]=preig(G2); % Decorrelate the second % Contributions to Bhattacharryya distance. d = E2'*A*(U(1,:)-U(2,:))'; D2 = diag(D2); Jb = 0.25*((d.^2)./(1.+D2)) + 0.5*log(0.5*(D2.^0.5 + D2.^-0.5)); % Calculate transform matrix. W = E2'*D1^-0.5*E1'; % The full transformation matrix [Jb,I] = sort(-Jb); % Sort according to Jb W = W(I,:); % Same %DXD: If N=0 we just want to get the Jb for all dimensions if (n==0) w = cumsum(Jb)/sum(Jb); return end % If a fraction N is given, find number of dimensions. if (n < 1) Jb = cumsum(-Jb); % Accumulate Jb ind = find(Jb < n*Jb(k)); % Find important components if (length(ind)==0) n = 1; else n = ind(length(ind)); % D is last important component end end; % Construct affine mapping. rot = W(1:n,1:k)'; off = -mean(b*rot); w = affine(rot,off,a); w = setname(w,'Bhatta mapping'); return
github
jacksky64/imageProcessing-master
prwaitbarnext.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prwaitbarnext.m
684
utf_8
c8d48c4427ac50247a6b8ab6481e7c2c
%PRWAITBARNEXT Low level routine to simplify PRWAITBAR next calls % % COUNT = PRWAITBARNEXT(N,STRING,COUNT) % % Update call for PRWAITBAR after initialisation by PRWAITBARINIT. % % In case COUNT = 0 it initializes as well and a separate call to % PRWAITBARINIT is not needed. % % SEE PRWAITBARINIT function count = prwaitbarnext(n,ss,count) if count < 0 [n,s,count] = prwaitbarinit(ss,n); else s = sprintf(ss,n); end if n > 1 count = count + 1; % we show one count more as prwaitbarnext typically is at the end of a % loop, while prwaitbar is at the beginning prwaitbar(n,count+1,[s int2str(count+1)]); if count == n prwaitbar(0); end end return
github
jacksky64/imageProcessing-master
libsvc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/libsvc.m
4,941
utf_8
fc38617bb5605c8cb8f39d1e7cb6a360
%LIBSVC Support Vector Classifier by libsvm % % [W,J] = LIBSVC(A,KERNEL,C) % % INPUT % A Dataset % KERNEL Mapping to compute kernel by A*MAP(A,KERNEL) % or string to compute kernel by FEVAL(KERNEL,A,A) % or cell array with strings and parameters to compute kernel by % FEVAL(KERNEL{1},A,A,KERNEL{2:END}) % Default: linear kernel (PROXM([],'P',1)) % C Trade_off parameter in the support vector classifier. % Default C = 1; % % OUTPUT % W Mapping: Support Vector Classifier % J Object idences of support objects. Can be also obtained as W{4} % % DESCRIPTION % Optimizes a support vector classifier for the dataset A by the libsvm % package, see http://www.csie.ntu.edu.tw/~cjlin/libsvm/. LIBSVC calls the % svmtrain routine of libsvm for training. Classifier execution for a % test dataset B may be done by D = B*W; In D posterior probabilities are % given as computed by svmpredict using the '-b 1' option. % % The kernel may be supplied in KERNEL by % - an untrained mapping, e.g. a call to PROXM like W = LIBSVC(A,PROXM([],'R',1)) % - a string with the name of the routine to compute the kernel from A % - a cell-array with this name and additional parameters. % This will be used for the evaluation of a dataset B by B*W or MAP(B,W) as % well. % % If KERNEL = 0 (or not given) it is assumed that A is already the % kernelmatrix (square). In this also a kernel matrix should be supplied at % evaluation by B*W or MAP(B,W). However, the kernel has to be computed with % respect to support objects listed in J (the order of objects in J does matter). % % REFERENCES % R.-E. Fan, P.-H. Chen, and C.-J. Lin. Working set selection using the second order % information for training SVM. Journal of Machine Learning Research 6, 1889-1918, 2005 % % SEE ALSO % MAPPINGS, DATASETS, SVC, PROXM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [W,J,u] = libsvc(a,kernel,C) prtrace(mfilename); libsvmcheck; if nargin < 3 C = 1; end if nargin < 2 | isempty(kernel) kernel = proxm([],'p',1); end if nargin < 1 | isempty(a) W = mapping(mfilename,{kernel,C}); W = setname(W,'LIBSVM Classifier'); return; end %opt = ['-s 0 -t 4 -b 1 -c ',num2str(C)]; opt = ['-s 0 -t 4 -b 1 -e 1e-3 -c ',num2str(C), ' -q']; if (~ismapping(kernel) | isuntrained(kernel)) % training islabtype(a,'crisp'); isvaldfile(a,1,2); % at least 1 object per class, 2 classes a = testdatasize(a,'objects'); [m,k,c] = getsize(a); nlab = getnlab(a); K = compute_kernel(a,a,kernel); K = min(K,K'); % make sure kernel is symmetric K = [[1:m]' K]; % as libsvm wants it % call libsvm u = svmtrain(nlab,K,opt); % Store the results: J = full(u.SVs); if isempty(J) | J == 0 aa = 0; end if isequal(kernel,0) s = []; % in_size = length(J); in_size = 0; % to allow old and new style calls else s = a(J,:); in_size = k; end lablist = getlablist(a); W = mapping(mfilename,'trained',{u,s,kernel,J,opt},lablist(u.Label,:),in_size,c); W = setname(W,'LIBSVM Classifier'); W = setcost(W,a); else % execution v = kernel; w = +v; m = size(a,1); u = w{1}; s = w{2}; kernel = w{3}; J = w{4}; opt = w{5}; K = compute_kernel(a,s,kernel); k = size(K,2); if k ~= length(J) if isequal(kernel,0) if (k > length(J)) & (k >= max(J)) % precomputed kernel; old style call prwarning(2,'Old style execution call: The precomputed kernel was calculated on a test set and the whole training set!') else error(['Inappropriate precomputed kernel!' newline ... 'For the execution the kernel matrix should be computed on a test set' ... newline 'and the set of support objects']); end else error('Kernel matrix has the wrong number of columns'); end else % kernel was computed with respect to the support objects % we make an approprite correction in the libsvm structure u.SVs = sparse((1:length(J))'); end K = [[1:m]' K]; % as libsvm wants it [lab,acc,d] = svmpredict(getnlab(a),K,u,' -b 1'); W = setdat(a,d,v); end return; function K = compute_kernel(a,s,kernel) % compute a kernel matrix for the objects a w.r.t. the support objects s % given a kernel description if isstr(kernel) % routine supplied to compute kernel K = feval(kernel,a,s); elseif iscell(kernel) K = feval(kernel{1},a,s,kernel{2:end}); elseif ismapping(kernel) K = a*map(s,kernel); elseif kernel == 0 % we have already a kernel K = a; else error('Do not know how to compute kernel matrix') end K = +K; return
github
jacksky64/imageProcessing-master
randreset.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/randreset.m
673
utf_8
c649bdd2f643bc2dc74a2f7aab5fabbc
%RANDRESET Reset state of random generators % % RANDRESET - reset states to 1 % RANDRESET(STATE) - reset states to STATE % STATE = RANDRESET - retrieve present state (no reset) % OLDSTATE = RANDRESET(STATE) - retrieve present state and reset function output = randreset(state) if nargin < 1 & nargout < 1 state = 1; end if nargout > 0 randstate = cell(1,2); randstate{1} = rand('state'); randstate{2} = randn('state'); output = randstate; end if ~(nargout == 1 & nargin == 0) if iscell(state) rand('state',state{1}); randn('state',state{2}); else rand('state',state); randn('state',state); end end
github
jacksky64/imageProcessing-master
rsscc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rsscc.m
1,918
utf_8
b6e779e3c66d0dcceb1f7815cd10ef16
%RSSCC Random subspace combining classifier % % W = RSSCC(A,CLASSF,NFEAT,NCLASSF) % % INPUT % A Dataset % CLASSF Untrained base classifier % NFEAT Number of features for training CLASSF % NCLASSF Number of base classifiers % % OUTPUT % W Combined classifer % % DESCRIPTION % This procedure computes a combined classifier consisting out of NCLASSF % base classifiers, each trained by a random set of NFEAT features of A. % W is just the set of base classifiers and still needs a combiner, e.g. % use W*MAXC or W*VOTEC. % % SEE ALSO % DATASETS, MAPPINGS, PARALLEL function w = rsscc(a,classf,nfeat,nclassf) if nargin < 4, nclassf = []; end if nargin < 3, nfeat = []; end if nargin < 2, classf = nmc; end if nargin < 1 | isempty(a) w = mapping(mfilename,'untrained',{classf,nfeat,nclassf}); w = setname(w,'rsscc'); elseif isuntrained(classf) % training isvaldset(a,1,1); [m,k] = size(a); if isempty(nfeat) nfeat = max(round(m/10),2); % use at least 2D feature spaces end if isempty(nclassf) nclassf = max(ceil(k/nfeat),10); % use at least 10 classifiers end if nfeat >= k % allow for small feature sizes (k < nfeat) nfeat = k; % use all features nclassf = 1; % compute a single classifier end nsets = ceil(nfeat*nclassf/k); featset = []; for j=1:nsets featset = [featset, randperm(k)]; end featset = featset(1:nfeat*nclassf); featset = reshape(featset,nclassf,nfeat); w = []; s = sprintf('Compute %i classifiers: ',nclassf); prwaitbar(nclassf,s); for j=1:nclassf prwaitbar(nclassf,j,[s num2str(j)]); w = [w; a(:,featset(j,:))*classf]; end prwaitbar(0) w = mapping(mfilename,'trained',{w,featset},getlablist(a),k,getsize(a,3)); else % execution, trained classifier stored in classf wdata = getdata(classf); w = wdata{1}; featset = wdata{2}'; w = a(:,featset(:))*w; end
github
jacksky64/imageProcessing-master
fisherc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/fisherc.m
3,055
utf_8
4284de41090f4d633d00ff52b68a8594
%FISHERC Fisher's Least Square Linear Classifier % % W = FISHERC(A) % % INPUT % A Dataset % % OUTPUT % W Fisher's linear classifier % % DESCRIPTION % Finds the linear discriminant function between the classes in the % dataset A by minimizing the errors in the least square sense. This % is a multi-class implementation using the one-against-all strategy. % % This classifier also works for soft and target labels. % % For high dimensional datasets or small sample size situations, the % Pseudo-Fisher procedure is used, which is based on a pseudo-inverse. % % This classifier, like all other non-density based classifiers, does not % use the prior probabilities stored in the dataset A. Consequently, it % is just for two-class problems and equal class prior probabilities % equivalent to LDC, which assumes normal densities with equal covariance % matrices. % % Note that A*(KLMS([],N)*NMC) performs a very similar operation, but uses % the prior probabilities to estimate the mean class covariance matrix used % in the pre-whitening operation performed by KLMS. The reduced % dimensionality N controls some regularization. % % REFERENCES % 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd ed. % John Wiley and Sons, New York, 2001. % 2. A. Webb, Statistical Pattern Recognition, Wiley, New York, 2002. % 3. S. Raudys and R.P.W. Duin, On expected classification error of the % Fisher linear classifier with pseudo-inverse covariance matrix, Pattern % Recognition Letters, vol. 19, no. 5-6, 1998, 385-392. % % SEE ALSO % MAPPINGS, DATASETS, TESTC, LDC, NMC, FISHERM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: fisherc.m,v 1.6 2010/02/08 15:31:48 duin Exp $ function W = fisherc(a) prtrace(mfilename); % No input arguments, return an untrained mapping. if (nargin < 1) | (isempty(a)) W = mapping(mfilename); W = setname(W,'Fisher'); return; end isvaldfile(a,1,2); % at least 1 object per class, 2 classes a = testdatasize(a); [m,k,c] = getsize(a); if islabtype(a,'crisp') & c > 2 W = mclassc(a,fisherc); return end y = gettargets(a); if islabtype(a,'soft') y = invsigm(y); % better to give [0,1] targets full range end u = mean(a); % Shift A to the origin. This is not significant, just increases accuracy. % A is extended by ones(m,1), a trick to incorporate a free weight in the % hyperplane definition. b = [+a-repmat(u,m,1), ones(m,1)]; if (rank(b) <= k) % This causes Fisherc to be the Pseudo-Fisher Classifier prwarning(2,'The dimensionality is too large. Pseudo-Fisher is trained instead.'); v = prpinv(b)*y; else % Fisher is identical to the Min-Square-Error solution. v = b\y; end offset = v(k+1,:) - u*v(1:k,:); % Free weight. W = affine(v(1:k,:),offset,a,getlablist(a),k,c); % Normalize the weights for good posterior probabilities. W = cnormc(W,a); W = setname(W,'Fisher'); return;
github
jacksky64/imageProcessing-master
dyadicm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/dyadicm.m
3,915
utf_8
fd78b4e2ab69cf6302874f80423e54e0
%DYADICM Dyadic dataset mapping % % B = DYADICM(A,P,Q,SIZE) % % INPUT % A Input dataset % P Scalar multiplication factor (default 1) % or string (name of a routine) % Q Scalar multiplication factor (default 1) % or feature size needed for splitting A % SIZE Desired images size of output objects % % OUTPUT % B Dataset % % DESCRIPTION % This fixed mapping is a low-level routine to facilitate dyadic datafile % operations. A should be a horizontal concatenation of two identically % shaped datasets: A = [A1 A2]. B is now computed as B = P*A1 + Q*A2. % The feature size for the objects in B is set to SIZE. % % If P is a string (name of a routine) the dataset A is horizontally % split and COMMAND(A1,A2) is called, in which COMMAND is the name of the % routine stored in P. % % If P is a string and Q is a number then the above split is made using % the first Q columns (features) of A for A1 and the remaining for A2. % % This routine has been written for use by PRTools programmers only. % Note that although this routine shows itself as a fixed mapping, it % is sometimes externally set to a combiner. % % SEE ALSO % DATASETS, MAPPINGS, DATAFILES % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = dyadicm(a,p,q,fsize) prtrace(mfilename,2); if nargin < 4, fsize = []; end if nargin < 3, q = []; end if nargin < 2, p = []; end if nargin < 1 | isempty(a) % note that this routine is sometimes externally set to a combiner b = mapping(mfilename,'fixed',{p,q,fsize}); b = setsize_out(b,prod(fsize)); b = setname(b,'dyadicm'); return end if isempty(p), p = 1; end if ismapping(a) % note that this routine is sometimes externally set to a combiner if istrained(a) b = a*mapping(mfilename,'fixed',{p,q,fsize}); else b = mapping(mfilename,'untrained',{a,p,q,fsize}); end elseif isdataset(a) & ismapping(p) pdata = getdata(p); c = getsize(a,3); % number of classes, size of mappings w = a*pdata{1}; % training the stacked untrained classifier v = feval(mfilename,[],pdata{2:3},c); % prepare dyadicm v = setsize_in(v,2*c); % and its input size b = w*v; % feed it with the stacked classifiers b = setlabels(b,getlablist(a)); % set its output labels. else % the basic call by data and parameters % The dataset A has horizontally to be split in two datasets A1, A2. % If P and Q are scalars or if Q = [], this is done half-half. % If P is a string (name of a routine) and Q is a number, this is % interpreted as the number of columns (features) of A that go to A1. % The remaining part goes to A2. [a1,a2,fsize] = split_dataset(a,p,q,fsize); if isstr(p) % some routine tells us what to do if isempty(q) b = feval(p,a1,a2); else b = feval(p,a1,a2,q{:}); end else % addition if isempty(q), q = 1; end b = p*a1 + q*a2; end if ~isdataset(b) b = double(b); % convert in case of logicals or DipImage elseif ~isempty(fsize) & ~iscell(a) % can a be a cell? b = setfeatsize(b,fsize); end end return function [a1,a2,fsize] = split_dataset(a,p,q,fsize) if iscell(a) a1 = double(a{1}); a2 = double(a{2}); elseif isstr(p) & ~isempty(q) isdataset(a); fsize = q; a1 = a(:,1:q); a2 = a(:,q+1:end); else isdataset(a); k = size(a,2); if isempty(fsize) | fsize == 0 fsize = k/2; end if 2*prod(fsize) ~= k error('Desired feature size should be half of input feature size') end if k ~= 2*floor(k/2) error('Feature size of dataset should be multiple of 2') end a1 = a(:,1:k/2); a2 = a(:,k/2+1:k); end
github
jacksky64/imageProcessing-master
mds.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/mds.m
34,203
utf_8
ad1048b580af1294a41a46963ebcd5e1
%MDS - Multidimensional Scaling - a variant of Sammon mapping % % [W,J,stress] = MDS(D,Y,OPTIONS) % [W,J,stress] = MDS(D,N,OPTIONS) % % INPUT % D Square (M x M) dissimilarity matrix % Y M x N matrix containing starting configuration, or % N Desired output dimensionality % OPTIONS Various parameters of the minimization procedure put into % a structure consisting of the following fields: 'q', 'optim', % 'init','etol','maxiter', 'isratio', 'itmap', 'st' and 'inspect' % (default: % OPTIONS.q = 0 % OPTIONS.optim = 'pn' % OPTIONS.init = 'cs' % OPTIONS.etol = 1e-6 (the precise value depends on q) % OPTIONS.maxiter = inf % OPTIONS.isratio = 0 % OPTIONS.itmap = 'yes' % OPTIONS.st = 1 % OPTIONS.inspect = 2). % % OUTPUT % W Multidimensional scaling mapping % J Index of points removed before optimization % stress Vector of stress values % % DESCRIPTION % Finds a nonlinear MDS map (a variant of the Sammon map) of objects % represented by a symmetric distance matrix D with zero diagonal, given % either the dimensionality N or the initial configuration Y. This is done % in an iterative manner by minimizing the Sammon stress: % % e = 1/(sum_{i<j} D_{ij}^(Q+2)) sum_{i<j} (D_{ij} - DY_{ij})^2 * D_{ij}^Q % % where DY is the distance matrix of Y, which should approximate D. If D(i,j) % = 0 for any different points i and j, then one of them is superfluous. The % indices of these points are returned in J. % % OPTIONS is an optional variable, using which the parameters for the mapping % can be controlled. It may contain the following fields: % % Q Stress measure to use (see above): -2,-1,0,1 or 2. % INIT Initialisation method for Y: 'randp', 'randnp', 'maxv', 'cs' % or 'kl'. See MDS_INIT for an explanation. % OPTIM Minimization procedure to use: 'pn' for Pseudo-Newton or % 'scg' for Scaled Conjugate Gradients. % ETOL Tolerance of the minimization procedure. Usually, it should be % MAXITER in the order of 1e-6. If MAXITER is given (see below), then the % optimization is stopped either when the error drops below ETOL or % MAXITER iterations are reached. % ISRATIO Indicates whether a ratio MDS should be performed (1) or not (0). % If ISRATIO is 1, then instead of fitting the dissimilarities % D_{ij}, A*D_{ij} is fitted in the stress function. The value A % is estimated analytically in each iteration. % ITMAP Determines the way new points are mapped, either in an iterative % manner ('yes') by minimizing the stress; or by a linear projection % ('no'). % ST Status, determines whether after each iteration the stress should % INSPECT be printed on the screen (1) or not (0). When INSPECT > 0, % ST = 1 and the mapping is onto 2D or larger, then the progress % is plotted during the minimization every INSPECT iterations. % % Important: % 1. It is assumed that D either is or approximates a Euclidean distance % matrix, i.e. D_{ij} = sqrt (sum_k(x_i - x_j)^2). % 2. Missing values can be handled; they should be marked by 'NaN' in D. % % EXAMPLES: % opt.optim = 'scg'; % opt.init = 'cs'; % D = sqrt(distm(a)); % Compute the Euclidean distance dataset of A % w1 = mds(D,2,opt); % An MDS map onto 2D initialized by Classical Scaling, % % optimized by a Scaled Conjugate Gradients algorithm % n = size(D,1); % y = rand(n,2); % w2 = mds(D,y,opt); % An MDS map onto 2D initialized by random vectors % % z = rand(n,n); % Set around 40% of the random distances to NaN, i.e. % z = (z+z')/2; % not used in the MDS mapping % z = find(z <= 0.6); % D(z) = NaN; % D(1:n+1:n^2) = 0; % Set the diagonal to zero % opt.optim = 'pn'; % opt.init = 'randnp'; % opt.etol = 1e-8; % Should be high, as only some distances are used % w3 = mds(D,2,opt); % An MDS map onto 2D initialized by a random projection % % REFERENCES % 1. M.F. Moler, A Scaled Conjugate Gradient Algorithm for Fast Supervised % Learning', Neural Networks, vol. 6, 525-533, 1993. % 2. W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, % Numerical Recipes in C, Cambridge University Press, Cambridge, 1992. % 3. I. Borg and P. Groenen, Modern Multidimensional Scaling, Springer % Verlag, Berlin, 1997. % 4. T.F. Cox and M.A.A. Cox, Multidimensional Scaling, Chapman and Hall, % London, 1994. % % SEE ALSO % MAPPINGS, MDS_STRESS, MDS_INIT, MDS_CS % % Copyright: Elzbieta Pekalska, Robert P.W. Duin, [email protected], 2000-2003 % Faculty of Applied Sciences, Delft University of Technology % function [w,J,err,opt,y] = mds(D,y,options) if (nargin < 3) options = []; % Will be filled by MDS_SETOPT, below. end opt = mds_setopt(options); if (nargin < 2) | (isempty(y)) prwarning(2,'no output dimensionality given, assuming N = 2.'); y = 2; end % No arguments given: return an untrained mapping. if (nargin < 1) | (isempty(D)) w = mapping(mfilename,{y,opt,[],[],[],[]}); w = setname(w,'MDS'); return end % YREP contains representative objects in the projected MDS space, i.e. % for which the mapping exists. YREP is empty for the original MDS, since % no projection is available yet. yrep = []; if (isdataset(D) | isa(D,'double')) [m,mm] = size(D); % Convert D to double, but retain labels in LAB. if (isdataset(D)), lab = getlab(D); D = +D; else, lab = ones(m,1); end; if (ismapping(y)) % The MDS mapping exists; this means that YREP has already been stored. pars = getdata(y); [k,c] = size(y); y = []; % Empty, should now be found. yrep = pars{1}; % There exists an MDS map, hence YREP is stored. opt = pars{2}; % Options used for the mapping. II = pars{3}; % Index of non-repeated points in YREP. winit = pars{4}; % The Classical Scaling map, if INIT = 'cs'. v = pars{5}; % Weights used for adding new points if ITMAP = 'no'. n = c; % Number of dimensions of the projected space. % Initialization by 'cs' is not possible when there is no winit % (i.e. the CS map) and new points should be added. if (strcmp(opt.init,'cs')) & (isempty(winit)) prwarning(2,'OPTIONS.init = cs is not possible when adding points; using kl.'); opt.init = 'kl'; end % If YREP is a scalar, we have an empty mapping. if (max(size(yrep)) == 1) y = yrep; yrep = []; end % Check whether D is a matrix with the zero diagonal for the existing map. if (m == mm) & (length(intersect(find(D(:)<eps),1:m+1:(m*mm))) >= m) w = yrep; % D is the same matrix as in the projection process; return % YREP is then the solution end if (length(pars) < 6) | (isempty(pars{6})) yinit = []; else yinit = pars{6}; % Possible initial configuration for points to % be added to an existing map if (size(yinit,1) ~= size(D,1)) prwarning(2,'the size of the initial configuration does not match that of the dissimilarity matrix, using random initialization.') yinit =[]; end end else % No MDS mapping available yet; perform the checks. if (~issym(D,1e-12)) prwarning(2,'D is not a symmetric matrix; will average.'); D = (D+D')/2; end % Check the number of zeros on the diagonal if (any(abs(diag(D)) > 0)) error('D should have a zero diagonal'); end end else % D is neither a dataset nor a matrix of doubles error('D should be a dataset or a matrix of doubles.'); end if (~isempty(y)) % Y is the initial configuration or N, no MDS map exists yet; % D is a square matrix. % Remove identical points, i.e. points for which D(i,j) = 0 for i ~= j. % I contains the indices of points left for the MDS mapping, J those % of the removed points and P those of the points left in I which were % identical to those removed. [I,J,P] = mds_reppoints(D); D = D(I,I); [ni,nc] = size(D); % NANID is an extra field in the OPTIONS structure, containing the indices % of NaN values (= missing values) in distance matrix D. opt.nanid = find(isnan(D(:)) == 1); % Initialise Y. [m2,n] = size(y); if (max(m2,n) == 1) % Y is a scalar, hence really is a dimensionality N. n = y; [y,winit] = mds_init(D,n,opt.init); else if (mm ~= m2) error('The matrix D and the starting configuration Y should have the same number of columns.'); end winit = []; y = +y(I,:); end % The final number of true distances is: no_dist = (ni*(ni-1) - length(opt.nanid))/2; else % This happens only if we add extra points to an existing MDS map. % Remove identical points, i.e. points for which D(i,j) = 0 for i ~= j. % I contains the indices of points left for the MDS mapping, J those % of the removed points and P those of the points left in I which were % identical to those removed. [I,J,P] = mds_reppoints(D(:,II)); D = D(I,II); [ni,nc] = size(D); yrep = yrep(II,:); n = size(yrep,2); % NANID is an extra field in the OPTIONS structure, containing the indices % of NaN values (= missing values) in distance matrix D. opt.nanid = find(isnan(D(:))); % Initialise Y. if the new points should be added in an iterative manner. [m2,n] = size(yrep); if (~isempty(yinit)) % An initial configuration exists. y = yinit; elseif (strcmp(opt.init, 'cs')) & (~isempty(winit)) y = D*winit; else y = mds_init(D,n,opt.init); end if (~isempty(opt.nanid)) % Rescale. scale = (max(yrep)-min(yrep))./(max(y)-min(y)); y = y .* repmat(scale,ni,1); end % The final number of true distances is: no_dist = (ni*nc - length(opt.nanid)); end % Check whether there is enough data left. if (~isempty(opt.nanid)) if (n*ni+2 > no_dist), error('There are too many missing distances: it is not possible to determine the MDS map.'); end if (strcmp (opt.itmap,'no')) opt.itmap = 'yes'; prwarning(1,'Due to the missing values, the projection can only be iterative. OPTIONS are changed appropriately.') end end if (opt.inspect > 0) opt.plotlab = lab(I,:); % Labels to be used for plotting in MDS_SAMMAP. else opt.plotlab = []; end if (isempty(yrep)) | (~isempty(yrep) & strcmp(opt.itmap, 'yes')) % Either no MDS exists yet OR new points should be mapped in an iterative manner. printinfo(opt); [yy,err] = mds_sammap(D,y,yrep,opt); % Define the linear projection of distances. v = []; if (isempty(yrep)) & (isempty(opt.nanid)) if (rank(D) < m) v = prpinv(D)*yy; else v = D \ yy; end end else % New points should be added by a linear projection of dissimilarity data. yy = D*v; end % Establish the projected configuration including the removed points. y = zeros(m,n); y(I,:) = +yy; if (~isempty(J)) if (~isempty(yrep)) y(J,:) = +yrep(II(P),:); else for k=length(J):-1:1 % J: indices of removed points. y(J(k),:) = y(P(k),:); % P: indices of points equal to points in J. end end end % In the definition step: shift the obtained configuration such that the % mean lies at the origin. if (isempty(yrep)) y = y - ones(length(y),1)*mean(y); y = dataset(y,lab); else w = dataset(y,lab); return; end % In the definition step: the mapping should be stored. opt = rmfield(opt,'nanid'); % These fields are to be used internally only; opt = rmfield(opt,'plotlab'); % not to be set up from outside w = mapping(mfilename,'trained',{y,opt,I,winit,v,[]},[],m,n); w = setname(w,'MDS'); return % ********************************************************************************** % Extra functions % ********************************************************************************** % PRINTINFO(OPT) % % Prints progress information to the file handle given by OPT.ST. function printinfo(opt) fprintf(opt.st,'Sammon mapping, error function with the parameter q=%d\n',opt.q); switch (opt.optim) case 'pn', fprintf(opt.st,'Minimization by Pseudo-Newton algorithm\n'); case 'scg', fprintf(opt.st,'Minimization by Scaled Conjugate Gradients algorithm\n'); otherwise error(strcat('Possible initialization methods: pn (Pseudo-Newton), ',... 'or scg (Scaled Conjugate Gradients).')); end return % ********************************************************************************** % [I,J,P] = MDS_REPPOINTS(D) % % Finds the indices of repeated/left points. J contains the indices of % repeated points in D. This means that for each j in J, there is a point % k ~= j such that D(J(j),k) = 0. I contains the indices of the remaining % points, and P those of the points in I that were identical to those in J. % Directly used in MDS routine. function [I,J,P] = mds_reppoints(D) epsilon = 1e-20; % Differences smaller than this are assumed to be zero. [m,mm] = size(D); I = 1:m; J = []; P = []; if (m == mm) & (all(abs(D(1:m+1:end)) <= epsilon)) K = intersect (find (triu(ones(m),1)), find(D < epsilon)); if (~isempty(K)) P = mod(K,m); J = fix(K./m) + 1; I(J) = []; end else [J,P] = find(D<=epsilon); I(J) = []; end return; % ********************************************************************************** % MDS_SETOPT Sets parameters for the MDS mapping % % OPT = MDS_SETOPT(OPT_GIVEN) % % INPUT % OPT_GIVEN Parameters for the MDS mapping, described below (default: []) % % OUTPUT % OPT Structure of chosen options; if OPT_GIVEN is empty, then % OPT.q = 0 % OPT.optim = 'pn' % OPT.init = 'cs' % OPT.etol = 1e-6 (the precise value depends on q) % OPT.maxiter = inf % OPT.itmap = 'yes' % OPT.isratio = 0 % OPT.st = 1 % OPT.inspect = 2 % % DESCRIPTION % Parameters for the MDS mapping can be set or changed. OPT_GIVEN consists % of the following fields: 'q', 'init', 'optim', 'etol', 'maxiter','itmap', % 'isratio', 'st' and 'inspect'. OPTIONS can include all the fields or some % of them only. The fields of OPT have some default values, which can be % changed by the OPT_GIVEN field values. If OPT_GIVEN is empty, then OPT % contains all default values. For a description of the fields, see MDS. % % Copyright: Elzbieta Pekalska, [email protected], 2000-2003 % Faculty of Applied Sciences, Delft University of Technology % function opt = mds_setopt (opt_given) opt.q = 0; opt.init = 'cs'; opt.optim = 'pn'; opt.st = 1; opt.itmap = 'yes'; opt.maxiter = inf; opt.inspect = 2; opt.etol = inf; opt.isratio = 0; opt.nanid = []; % Here are some extra values; set up in the MDS routine. opt.plotlab = []; % Not to be changed by the user. if (~isempty(opt_given)) if (~isstruct(opt_given)) error('OPTIONS should be a structure with at least one of the following fields: q, init, etol, optim, maxiter, itmap, isratio, st or inspect.'); end fn = fieldnames(opt_given); if (~all(ismember(fn,fieldnames(opt)))) error('Wrong field names; valid field names are: q, init, optim, etol, maxiter, itmap, isratio, st or inspect.') end for i = 1:length(fn) opt = setfield(opt,fn{i},getfield(opt_given,fn{i})); end end if (isempty(intersect(opt.q,-2:1:2))) error ('OPTIONS.q should be -2, -1, 0, 1 or 2.'); end if (opt.maxiter < 2) error ('OPTIONS.iter should be at least 1.'); end if (isinf(opt.etol)) switch (opt.q) % Different defaults for different stresses. case -2, opt.etol = 1e-6; case {-1,0} opt.etol = 10*sqrt(eps); case {1,2} opt.etol = sqrt(eps); end elseif (opt.etol <= 0) | (opt.etol >= 0.1) error ('OPTIONS.etol should be positive and smaller than 0.1.'); end if (~ismember(opt.optim, {'pn','scg'})) error('OPTIONS.optim should be pn or scg.'); end if (~ismember(opt.itmap, {'yes','no'})) error('OPTIONS.itmap should be yes or no.'); end return % ********************************************************************************** % MDS_SAMMAP Sammon iterative nonlinear mapping for MDS % % [YMAP,ERR] = MDS_SAMMAP(D,Y,YREP,OPTIONS) % % INPUT % D Square (M x M) dissimilarity matrix % Y M x N matrix containing starting configuration, or % YREP Configuration of the representation points % OPTIONS Various parameters of the minimization procedure put into % a structure consisting of the following fields: 'q', 'optim', % 'init','etol','maxiter', 'isratio', 'itmap', 'st' and 'inspect' % (default: % OPTIONS.q = 0 % OPTIONS.optim = 'pn' % OPTIONS.init = 'cs' % OPTIONS.etol = 1e-6 (the precise value depends on q) % OPTIONS.maxiter = inf % OPTIONS.isratio = 0 % OPTIONS.itmap = 'yes' % OPTIONS.st = 1 % OPTIONS.inspect = 2). % % OUTPUT % YMAP Mapped configuration % ERR Sammon stress % % DESCRIPTION % Maps the objects given by a symmetric distance matrix D (with a zero % diagonal) onto, say, an N-dimensional configuration YMAP by an iterative % minimization of a variant of the Sammon stress. The minimization starts % from the initial configuration Y; see MDS_INIT. % % YREP is the Sammon configuration of the representation set. It is used % when new points have to be projected. In other words, if D is an M x M % symmetric distance matrix, then YREP is empty; if D is an M x N matrix, % then YMAP is sought such that D can approximate the distances between YMAP % and YREP. % % Missing values can be handled by marking them by NaN in D. % % SEE ALSO % MAPPINGS, MDS, MDS_CS, MDS_INIT, MDS_SETOPT % % Copyright: Elzbieta Pekalska, [email protected], 2000-2003 % Faculty of Applied Sciences, Delft University of Technology % function [y,err] = mds_sammap(Ds,y,yrep,opt) if (nargin < 4) opt = []; % Will be filled by MDS_SETOPT, below. end if isempty(opt), opt = mds_setopt(opt); end if (nargin < 3) yrep = []; end % Extract labels and calculate distance matrix. [m,n] = size(y); if (~isempty(yrep)) replab = getlab(yrep); yrep = +yrep; D = sqrt(distm(y,yrep)); else D = sqrt(distm(y)); yrep = []; replab = []; end if (isempty(opt.plotlab)) opt.plotlab = ones(m,1); end it = 0; % Iteration number. eold = inf; % Previous stress (error). % Calculate initial stress. [e,a]= mds_samstress(opt.q,y,yrep,Ds,D,opt.nanid,opt.isratio); err = e; fprintf(opt.st,'iteration: %4i stress: %3.8d\n',it,e); switch (opt.optim) case 'pn', % Pseudo-Newton minimization. epr = e; % Previous values of E, EOLD for line search algorithm. eepr = e; add = 1e-4; % Avoid G2 equal 0; see below. BETA = 1e-3; % Parameter for line search algorithm. lam1 = 0; lam2 = 1; % LAM (the step factor) lies in (LAM1, LAM2). LMIN = 1e-10; % Minimum acceptable value for LAM in line search. lambest = 1e-4; % LAM = LAMBEST, if LAM was not found. % Loop until the error change falls below the tolerance or until % the maximum number of iterations is reached. while (abs(e-eold) >= opt.etol*(1 + abs(e))) & (it < opt.maxiter) % Plot progress if requested. if (opt.st > 0) & (opt.inspect > 0) & (mod(it,opt.inspect) == 0) % if (it == 0), figure(1); clf; end mds_plot(y,yrep,opt.plotlab,replab,e); end yold = y; eold = e; % Calculate the stress. [e,a] = mds_samstress (opt.q,yold,yrep,Ds,[],opt.nanid,opt.isratio); % Calculate gradients and pseudo-Newton update P. [g1,g2,cc] = mds_gradients (opt.q,yold,yrep,a*Ds,[],opt.nanid); p = (g1/cc)./(abs(g2/cc) + add); slope = g1(:)' * p(:); lam = 1; % Search for a suitable step LAM using a line search. while (1) % Take a step and calculate the delta error DE. y = yold + lam .* p; [e,a] = mds_samstress(opt.q,y,yrep,Ds,[],opt.nanid,opt.isratio); de = e - eold; % Stop if the condition for a suitable lam is fulfilled. if (de < BETA * lam * slope) break; end % Try to find a suitable step LAM. if (lam ~= 1) r1 = de - lam*slope; r2 = epr - eepr - lam2*slope; aa = (2*de + r1/lam^2 - r2/lam2^2)/(lam2-lam1)^3; bb = ((-lam2*r1)/lam^2 +(lam*r2)/lam2^2)/(lam2-lam1)^2; if (abs(aa) <= eps) lamtmp = -0.5 * slope/bb; else lamtmp = (-bb + sqrt(max(0,(bb^2 - 3*aa*slope))))/(3*aa); end % Prevent LAM from becoming too large. if (lamtmp > 0.5 * lam), lamtmp = 0.5 * lam; end else lamtmp = -0.5 * slope/(e - eold - slope); end % Prevent LAM from becoming too small. lam2 = lam; lam = max(lamtmp, 0.1*lam); epr = e; eepr = eold; if (lam < LMIN) y = yold + lambest .* p; [e,a] = mds_samstress(opt.q,y,yrep,Ds,[],opt.nanid,opt.isratio); break; end end it = it + 1; err = [err; e]; fprintf(opt.st,'iteration: %4i stress: %3.8d\n',it,e); end case 'scg', % Scaled Conjugate Gradient minimization. sigma0 = 1e-8; lambda = 1e-8; % Regularization parameter. lambda1 = 0; % Calculate initial stress and direction of decrease P. [e,a] = mds_samstress(opt.q,y,yrep,Ds,D,opt.nanid,opt.isratio); g1 = mds_gradients(opt.q,y,yrep,a*Ds,D,opt.nanid); % Gradient p = -g1; % Direction of decrease gnorm2 = g1(:)' * g1(:); success = 1; % Sanity check. if (gnorm2 < 1e-15) prwarning(2,['Gradient is nearly zero: ' gnorm2 ' (unlikely); initial configuration is the right one.']); return end % Loop until the error change falls below the tolerance or until % the maximum number of iterations is reached. while (abs(eold - e) > opt.etol * (1 + e)) & (it < opt.maxiter) g0 = g1; % Previous gradient pnorm2 = p(:)' * p(:); eold = e; % Plot progress if requested. if (opt.inspect > 0) & (mod(it,opt.inspect) == 0) % if (it == 0), figure(1); clf; end mds_plot(y,yrep,opt.plotlab,replab,e); end if (success) sigma = sigma0/sqrt(pnorm2); % SIGMA: a small step from y to yy yy = y + sigma .*p; [e,a] = mds_samstress(opt.q,yy,yrep,Ds,[],opt.nanid,opt.isratio); g2 = mds_gradients(opt.q,yy,yrep,a*Ds,[],opt.nanid); % Gradient for yy s = (g2-g1)/sigma; % Approximation of Hessian*P directly, instead of computing delta = p(:)' * s(:); % the Hessian, since only DELTA = P'*Hessian*P is in fact needed end % Regularize the Hessian indirectly to make it positive definite. % DELTA is now computed as P'* (Hessian + regularization * Identity) * P delta = delta + (lambda1 - lambda) * pnorm2; % Indicate if the Hessian is negative definite; the regularization above was too small. if (delta < 0) lambda1 = 2 * (lambda - delta/pnorm2); % Now the Hessian will be positive definite delta = -delta + lambda * pnorm2; % This is obtained after plugging lambda1 lambda = lambda1; % into the formulation a few lines above. end mi = - p(:)' * g1(:); yy = y + (mi/delta) .*p; % mi/delta is a step size [ee,a] = mds_samstress(opt.q,yy,yrep,Ds,[],opt.nanid,opt.isratio); % This minimization procedure is based on the second order approximation of the % stress function by using the gradient and the Hessian approximation. The Hessian % is regularized, but maybe not sufficiently. The ratio Dc (<=1) below indicates % a proper approximation, if Dc is close to 1. Dc = 2 * delta/mi^2 * (e - ee); e = ee; % If Dc > 0, then the stress can be successfully decreased. success = (Dc >= 0); if (success) y = yy; [ee,a] = mds_samstress(opt.q,yy,yrep,Ds,[],opt.nanid,opt.isratio); g1 = mds_gradients(opt.q,yy,yrep,a*Ds,[],opt.nanid); gnorm2 = g1(:)' * g1(:); lambda1 = 0; beta = max(0,(g1(:)'*(g1(:)-g0(:)))/mi); p = -g1 + beta .* p; % P is a new conjugate direction if (g1(:)'*p(:) >= 0 | mod(it-1,n*m) == 0), p = -g1; % No much improvement, restart end if (Dc >= 0.75) lambda = 0.25 * lambda; % Make the regularization smaller end it = it + 1; err = [err; e]; fprintf (opt.st,'iteration: %4i stress: %3.8d\n',it,e); else % Dc < 0 % Note that for Dc < 0, the iteration number IT is not increased, % so the Hessian is further regularized until SUCCESS equals 1. lambda1 = lambda; end % The approximation of the Hessian was poor or the stress was not % decreased (Dc < 0), hence the regularization lambda is enlarged. if (Dc < 0.25) lambda = lambda + delta * (1 - Dc)/pnorm2; end end end return; % ********************************************************************************** %MDS_STRESS - Calculate Sammon stress during optimization % % E = MDS_SAMSTRESS(Q,Y,YREP,Ds,D,NANINDEX) % % INPUT % Q Indicator of the Sammon stress; Q = -2,-1,0,1,2 % Y Current lower-dimensional configuration % YREP Configuration of the representation objects; it should be % empty when no representation set is considered % Ds Original distance matrix % D Approximate distance matrix (optional; otherwise computed from Y) % NANINDEX Index of the missing values; marked in Ds by NaN (optional; to % be found in Ds) % % OUTPUT % E Sammon stress % % DESCRIPTION % Computes the Sammon stress between the original distance matrix Ds and the % approximated distance matrix D between the mapped configuration Y and the % configuration of the representation set YREP, expressed as follows: % % E = 1/(sum_{i<j} Ds_{ij}^(q+2)) sum_{i<j} (Ds_{ij} - D_{ij})^2 * Ds_{ij}^q % % It is directly used in the MDS_SAMMAP routine. % % Copyright: Elzbieta Pekalska, Robert P.W. Duin, [email protected], 2000-2003 % Faculty of Applied Sciences, Delft University of Technology % function [e,alpha] = mds_samstress (q,y,yrep,Ds,D,nanindex,isratio) % If D is not given, calculate it from Y, the current mapped points. if (nargin < 5) | (isempty(D)) if (~isempty(yrep)) D = sqrt(distm(y,yrep)); else D = sqrt(distm(y)); end end if (nargin < 6) nanindex = []; % Not given, so calculate below. end if (nargin < 7) isratio = 0; % Assume this is meant. end todefine = isempty(yrep); [m,n] = size(y); [mm,k] = size(Ds); if (m ~= mm) error('The sizes of Y and Ds do not match.'); end if (any(size(D) ~= size(Ds))) error ('The sizes of D and Ds do not match.'); end m2 = m*k; % Convert to double. D = +D; Ds = +Ds; % I is the index of non-NaN, non-zero (> eps) values to be included % for the computation of the stress. I = 1:m2; if (~isempty(nanindex)) I(nanindex) = []; end O = []; if (todefine), O = 1:m+1:m2; end I = setdiff(I,O); % If OPTIONS.isratio is set, calculate optimal ALPHA to scale with. if (isratio) alpha = sum((Ds(I).^q).*D(I).^2)/sum((Ds(I).^(q+1)).*D(I)); Ds = alpha*Ds; else alpha = 1; end % C is the normalization factor. c = sum(Ds(I).^(q+2)); % If Q == 0, prevent unnecessary calculation (X^0 == 1). if (q ~= 0) e = sum(Ds(I).^q .*((Ds(I)-D(I)).^2))/c; else e = sum(((Ds(I)-D(I)).^2))/c; end return; % ********************************************************************************** %MDS_GRADIENTS - Gradients for variants of the Sammon stress % % [G1,G2,CC] = MDS_GRADIENTS(Q,Y,YREP,Ds,D,NANINDEX) % % INPUT % Q Indicator of the Sammon stress; Q = -2,-1,0,1,2 % Y Current lower-dimensional configuration % YREP Configuration of the representation objects; it should be % empty when no representation set is considered % Ds Original distance matrix % D Approximate distance matrix (optional; otherwise computed from Y) % nanindex Index of missing values; marked in Ds by NaN (optional; % otherwise found from Ds) % % OUTPUT % G1 Gradient direction % G2 Approximation of the Hessian by its diagonal % % DESCRIPTION % This is a routine used directly in the MDS_SAMMAP routine. % % SEE ALSO % MDS, MDS_INIT, MDS_SAMMAP, MDS_SAMSTRESS % % Copyright: Elzbieta Pekalska, Robert P.W. Duin, [email protected], 2000-2003 % Faculty of Applied Sciences, Delft University of Technology % function [g1,g2,c] = mds_gradients(q,y,yrep,Ds,D,nanindex) % If D is not given, calculate it from Y, the current mapped points. y = +y; yrep = +yrep; if (nargin < 5) | (isempty(D)) if (~isempty(yrep)) D = sqrt(distm(y,yrep)); else D = sqrt(distm(y)); end end % If NANINDEX is not given, find it from Ds. if (nargin < 6) nanindex = find(isnan(Ds(:))==1); end % YREP is empty if no representation set is defined yet. % This happens when the mapping should be defined. todefine = (isempty(yrep)); if (todefine) yrep = y; end [m,n] = size(y); [mm,k] = size(Ds); if (m ~= mm) error('The sizes of Y and Ds do not match.'); end if (any(size(D) ~= size(Ds))) error ('The sizes of D and Ds do not match.'); end m2 = m*k; % Convert to doubles. D = +D; Ds = +Ds; % I is the index of non-NaN, non-zero (> eps) values to be included % for the computation of the gradient and the Hessians diagonal. I = (1:m2)'; if (~isempty(nanindex)) I(nanindex) = []; end K = find(Ds(I) <= eps | D(I) <= eps); I(K) = []; % C is a normalization factor. c = -2/sum(Ds(I).^(q+2)); % Compute G1, the gradient. h1 = zeros(m2,1); if (q == 0) % Prevent unnecessary computation when Q = 0. h1(I) = (Ds(I)-D(I)) ./ D(I); else h1(I) = (Ds(I)-D(I)) ./ (D(I).*(Ds(I).^(-q))); end h1 = reshape (h1',m,k); g2 = h1 * ones(k,n); % Here G2 is assigned only temporarily, g1 = c * (g2.*y - h1*yrep); % for the computation of G1. % Compute G2, the diagonal of the Hessian, if requested. if (nargout > 1) h2 = zeros(m2,1); switch (q) case -2, h2(I) = -1./(Ds(I).*D(I).^3); case -1, h2(I) = -1./(D(I).^3); case 0, h2(I) = - Ds(I)./(D(I).^3); case 1, h2(I) = - Ds(I).^2./(D(I).^3); case 2, h2(I) = -(Ds(I)./D(I)).^3; end h2 = reshape (h2',m,k); g2 = c * (g2 + (h2*ones(k,n)).*y.^2 + h2*yrep.^2 - 2*(h2*yrep).*y); end return; % ********************************************************************************** %MDS_PLOT Plots the results of the MDS mapping in a 2D or 3D figure % % MDS_PLOT(Y,YREP,LAB,REPLAB,E) % % INPUT % Y Configuration in 2D or 3D space % YREP Configuration of the representation points in 2D or 3D space % LAB Labels of Y % REPLAB Labels of YREP % E Stress value % % DESCRIPTION % Used directly in MDS_SAMMAP routine. function mds_plot (y,yrep,lab,replab,e) % This is done in a rather complicated way in order to speed up drawing. K = min(size(y,2),3); if (K > 1) y = +y; col = 'brmk'; sym = ['+*xosdv^<>p']'; ii = [1:44]; s = [col(ii-floor((ii-1)/4)*4)' sym(ii-floor((ii-1)/11)*11)]; [nlab,lablist] = renumlab([replab;lab]); c = max(nlab); [ms,ns] = size(s); if (ms == 1), s = setstr(ones(m,1)*s); end yy = [yrep; y]; cla; if (K == 2) hold on; for i = 1:c J = find(nlab==i); plot(yy(J,1),yy(J,2),s(i,:)); end else for i = 1:c J = find(nlab==i); plot3(yy(J,1),yy(J,2),yy(J,3),s(i,:)); if (i == 1), hold on; grid on; end end end title(sprintf('STRESS: %f', e)); axis equal; drawnow; end return;
github
jacksky64/imageProcessing-master
fixedcc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/fixedcc.m
6,296
utf_8
7f063504ddd492c6c189c15418da0f1a
%FIXEDCC Construction of fixed combiners % % V = FIXEDCC(A,W,TYPE,NAME,PAR) % % INPUT % A Dataset % W A set of classifier mappings % TYPE The type of combination rule % NAME The name of this combination rule % PAR Possible parameter for combiner defined by TYPE % % OUTPUT % V Mapping % % DESCRIPTION % Define a mapping V which applies the combination rule TYPE to the % set of mappings W. The set of mappings W should be a parallel % combination (see MAPPINGS). % % The TYPE of combining can be any of the following: % average, min, max, mean, median, prod, vote, % % Note that average is only possible for affine 2-class classifiers. % % When W is a set of classifiers and A a dataset (possibly the result % of B*W, where W is again a set of classifiers) then: % % V = FIXEDCC(W,[],TYPE) combines the mappings W with the comb. rule TYPE % V = FIXEDCC(A,[],TYPE) computes the combining output for dataset A % V = FIXEDCC(A,W,TYPE) computes the combining output for dataset A, % where W is trained using A % % EXAMPLES % See prex_combining. % % SEE ALSO % MAPPINGS, VOTEC, MAXC, MEANC, MEDIANC, MINC, PRODC, AVERAGEC % $Id: fixedcc.m,v 1.3 2009/02/04 10:53:10 duin Exp $ function v = fixedcc(a,w,type,name,par) prtrace(mfilename); if nargin == 0 % Without input, just return an completely empty combiner mapping (even % without defining the combination rule): v = mapping(mfilename,'combiner'); return end if nargin < 5, par = []; end if isempty(a) % just return a combiner mapping with just the combining rule v = mapping(mfilename,'combiner',{[],type,name,par}); elseif isa(a,'mapping') & isempty(w) % v = comb_classifier*fixedcc, % we combine a set of classifiers, not interesting, except for the % 'average' type, there a new affine transformation is computed: if isuntrained(a) % store untrained comb_classifier v = mapping(mfilename,'untrained',{a,type,name,par}); else % handle or store trained comb_classifier and all info [nclass,classlist] = renumlab(getlabels(a)); % Special case is to average affine coefficients for 'average' combining switch type case 'average' if ~(isaffine(a) & size(classlist,1) == 2) error('Average combining only possible for affine 2-class classifiers') end n = length(a.data); rot = zeros(size(a,1),1); off = 0; for j=1:length(a.data) rot = rot + a.data{j}.data.rot(:,1); off = off + a.data{j}.data.offset(1); end v = affine(rot/n,off/n); otherwise % Standard procedure: make a new trained mapping v = mapping(mfilename,'trained',{a,type,name,par}); end v = set(v,'size_in',size(a,1),'size_out',size(classlist,1),'labels',classlist); v = setcost(v,a); end elseif isa(a,'dataset') & isempty(w) % Call like v = dataset*fixedcc, % Here the work will be done: % the dataset has already been mapped through the mappings, and the outputs % should be processed according to the combiner type. % get all the relevant parameters: [m,k] = size(a); featlist = getfeatlab(a); if isempty(featlist) prwarning(2,'No class names given: numbering inserted') nclass = [1:k]'; classlist = [1:k]'; else [nclass,classlist] = renumlab(featlist); end c = size(classlist,1); d = zeros(size(a,1),c); b = +a; % the classifier outputs to be processed %DXD: I need for my one-class classifiers that the feature domains %are retained: newfeatdom = getfeatdom(a); if ~isempty(newfeatdom) newfeatdom = newfeatdom(1:size(d,2)); end % for each of the classes the outputs should now be combined to a new % one, using the combining rule: for j=1:c J = find(nclass==j); switch type case 'min' d(:,j) = min(b(:,J),[],2); case 'max' d(:,j) = max(b(:,J),[],2); case 'mean' d(:,j) = mean(b(:,J),2); case 'prod' %d(:,j) = prod(b(:,J),2); d(:,j) = exp(sum(log(b(:,J)),2)); case 'median' d(:,j) = median(b(:,J),2); case 'vote' % Assumes that classifier outcomes are well ordered in b % For voting we cannot combine the basic classifier outputs, % but we should use the classifier labels: n = size(a,2) / c; if ~isint(n) error('All classifiers should refer to all classes') end % First get the votes for each of the classes: [nf,fl] = renumlab(featlist); mlab = zeros(m,n); for j=1:n J = [(j-1)*c+1:j*c]; labels = labeld(a(:,J)); [nl,nlab,ll] = renumlab(fl,labels); mlab(:,j) = nlab; end % Then count the number of votes: for j=1:c d(:,j) = (sum(mlab==j,2)+1)/(n+c); end %DXD: for this voting rule, the feature domain will change: for k=1:c newfeatdom{k} = [0 inf; 0 inf]; end case 'perc' d(:,j) = prctile(b(:,J),par,2); case 'average' error([newline 'Average combiner should directly call the classifiers' ... newline 'e.g. A*AVERAGEC([W1 W2 W3]), or A*([W1 W2 W3]*AVERAGEC)']) otherwise error(['Unknown method for fixed combining: ' type]) end end v = setdata(a,d,classlist); %DXD: I need for my one-class classifiers that the feature domains %are retained: if ~isempty(newfeatdom) v = setfeatdom(v,newfeatdom); end elseif isa(a,'dataset') & isa(w,'mapping') % call like v = dataset * trained combiner (e.g. a*votec([u v w])) % This means that we first have to map the data through the mappings, and % then map this new dataset through the combiner: if strcmp(getmapping_file(w),mfilename) % Then we already have a nice combining rule: % get the relevant parameters: type = w.data{2}; name = w.data{3}; par - w.data{4}; % Evaluate the mapped data (a*w.data{1}) by this combining rule: v = feval(mfilename,a*w.data{1},[],type,name,par); else % We will use the parameters given in the argument list % evaluate the mapped data (a*w) by this combining rule: v = feval(mfilename,a*w,[],type,name,par); end else % this should not happen error('Call cannot be parsed') end if isa(v,'mapping') v = setname(v,name); end return
github
jacksky64/imageProcessing-master
gendath.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendath.m
1,639
utf_8
a279b0efc2f6f7597ef201039460de3f
%GENDATH Generation of Highleyman classes % % A = GENDATH(N,LABTYPE) % % INPUT % N Number of objects (optional; default: [50,50]) % LABTYPE Label type (optional; default: 'crisp') % % OUTPUT % A Generated dataset % % DESCRIPTION % Generation of a 2-dimensional 2-class dataset A of N objects % according to Highleyman. % % The two Highleyman classes are defined by % 1: Gauss([1 1],[1 0; 0 0.25]). % 2: Gauss([2 0],[0.01 0; 0 4]). % Class priors are P(1) = P(2) = 0.5 % % If N is a vector of sizes, exactly N(I) objects are generated % for class I, I = 1,2. % % LABTYPE defines the desired label type: 'crisp' or 'soft'. In the % latter case true posterior probabilities are set for the labels. % % Defaults: N = [50,50], LABTYPE = 'crisp'. % % EXAMPLES % PREX_PLOTC, PREX_CLEVAL % % SEE ALSO % DATASETS, GAUSS, PRDATASETS % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: gendath.m,v 1.5 2009/01/27 13:01:42 duin Exp $ function A = gendath(N,labtype) prtrace(mfilename); if nargin < 1, N = [50, 50]; end if nargin < 2, labtype = 'crisp'; end GA = [1 0; 0 0.25]; GB = [0.01 0; 0 4]; G = cat(3,GA,GB); p = [0.5 0.5]; N = genclass(N,p); U = dataset([1 1; 2 0],[1 2]','prior',p); U = setprior(U,p); A = gendatgauss(N,U,G); A = setname(A,'Highleyman Dataset'); switch labtype case 'crisp' ; case 'soft' W = nbayesc(U,cat(3,GA,GB)); targets = A*W*classc; A = setlabtype(A,'soft',targets); otherwise error(['Label type ' labtype ' not supported']) end return
github
jacksky64/imageProcessing-master
plotgtm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plotgtm.m
4,021
utf_8
b23f60d48591b5a6f674a0de4bca4108
%PLOTGTM Plot a trained GTM mapping in 1D, 2D or 3D % % H = PLOTGTM (W) % % INPUT % W Trained GTM mapping % % OUTPUT % H Graphics handles % % DESCRIPTION % Creates a plot of the GTM manifold in the original data space, but at % most in 3D. % % SEE ALSO % GTM, SOM, PLOTSOM % (c) Dick de Ridder, 2003 % Information & Communication Theory Group % Faculty of Electrical Engineering, Mathematics and Computer Science % Delft University of Technology, Mekelweg 4, 2628 CD Delft, The Netherlands function ret = plotgtm (w) prtrace(mfilename); global GRIDSIZE; gs = [ 100 10 5 ]+1; if (~ismapping(w)) | (~strcmp(get(w,'name'),'GTM')) error ('can only plot a GTM mapping'); else data = getdata(w); K = data{1}; M = data{2}; W = data{3}; sigma = data{4}; mapto = data{5}; end; [d,D] = size(w); KK = prod(K); MM = prod(M); phi_mu = makegrid(M,D); % Basis function centers. phi_sigma = 2/(mean(M)-1); % Basis function widths. % For plotting. if (D == 1), Kplot = gs(1); sz = 1/(gs(1)-1); xplot = 0:sz:1; elseif (D == 2) Kplot = gs(2)^2; sz = 1/(gs(2)-1); [xx,yy] = meshgrid(0:sz:1,0:sz:1); xplot = [reshape(xx,1,Kplot); reshape(yy,1,Kplot)]; elseif (D >= 3) Kplot = gs(3)^3; sz = 1/(gs(3)-1); [xx,yy,zz] = meshgrid(0:sz:1,0:sz:1,0:sz:1); xplot = [reshape(xx,1,Kplot); reshape(yy,1,Kplot); reshape(zz,1,Kplot)]; D = 3; end; % Pre-calculate Phiplot. for j = 1:Kplot for i = 1:MM Phiplot(i,j) = exp(-(xplot(1:D,j)-phi_mu(1:D,i))'*(xplot(1:D,j)-phi_mu(1:D,i))/(phi_sigma^2)); end; end; % Plot grid lines. yplot = W(1:d,:)*Phiplot; hold on; h = []; if (D == 1) h = [h plot(yplot(1,:),yplot(2,:),'k-')]; elseif (D == 2) for k = 1:gs(2) h = [h plot(yplot(1,(k-1)*gs(2)+1:k*gs(2)),yplot(2,(k-1)*gs(2)+1:k*gs(2)),'k-')]; h = [h plot(yplot(1,k:gs(2):end),yplot(2,k:gs(2):end),'k-')]; end; elseif (D >= 3) for k = 1:gs(3) for l = 1:gs(3) h = [h plot3(yplot(1,(k-1)*gs(3)^2+(l-1)*gs(3)+1:(k-1)*gs(3)^2+l*gs(3)),... yplot(2,(k-1)*gs(3)^2+(l-1)*gs(3)+1:(k-1)*gs(3)^2+l*gs(3)),... yplot(3,(k-1)*gs(3)^2+(l-1)*gs(3)+1:(k-1)*gs(3)^2+l*gs(3)),'k-')]; h = [h plot3(yplot(1,(k-1)*gs(3)^2+l:gs(3):k*gs(3)^2),... yplot(2,(k-1)*gs(3)^2+l:gs(3):k*gs(3)^2),... yplot(3,(k-1)*gs(3)^2+l:gs(3):k*gs(3)^2),'k-')]; h = [h plot3(yplot(1,(k-1)*gs(3)+l:gs(3)^2:end),... yplot(2,(k-1)*gs(3)+l:gs(3)^2:end),... yplot(3,(k-1)*gs(3)+l:gs(3)^2:end),'k-')]; end; end; view(3); end; set (h,'LineWidth',2); hold off; if (nargout > 0), ret = h; end; return % GRID = MAKEGRID (K,D) % % Create a KK = prod(K)-dimensional grid with dimensions K(1), K(2), ... of % D-dimensional uniformly spaced grid points on [0,1]^prod(K), and store it % as a D x KK matrix X. function grid = makegrid (K,D) KK = prod(K); for h = 1:D xx{h} = 0:(1/(K(h)-1)):1; % Support point means end; % Do that voodoo / that you do / so well... if (D==1) xm = xx; else cmd = '['; for h = 1:D-1, cmd = sprintf ('%sxm{%d}, ', cmd, h); end; cmd = sprintf ('%sxm{%d}] = ndgrid(', cmd, D); for h = 1:D-1, cmd = sprintf ('%sxx{%d}, ', cmd, h); end; cmd = sprintf ('%sxx{%d});', cmd, D); eval(cmd); end; cmd = 'mm = zeros(D, '; for h = 1:D-1, cmd = sprintf ('%s%d, ', cmd, K(h)); end; cmd = sprintf ('%s%d);', cmd, K(D)); eval (cmd); for h = 1:D cmd = sprintf ('mm(%d,', h); for g = 1:D-1, cmd = sprintf ('%s:,', cmd); end; cmd = sprintf ('%s:) = xm{%d};', cmd, h); eval (cmd); end; grid = reshape(mm,D,KK); return
github
jacksky64/imageProcessing-master
drbmc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/drbmc.m
20,444
utf_8
fc2e95de4fb99b6c90dbe11a9b994b18
function [B, ll] = drbmc(A, W, L, I) %DRBMC Discriminative Restricted Boltzmann Machine classifier % % W = DRBMC(A) % W = DRBMC(A, N) % W = DRBMC(A, N, L) % % INPUT % A Dataset % N Number of hidden units % L Regularization parameter (L2) % % OUTPUT % W Discriminative Restricted Boltzmann Machine classifier % % DESCRIPTION % The classifier trains a discriminative Restricted Boltzmann Machine (RBM) % on dataset A. The discriminative RBM can be viewed as a logistic % regressor with hidden units. The discriminative RBM has N hidden units % (default = 50). It is trained with L2 regularization using regularization % parameter L (default = 0). % % New objects are classified in the same way as in a logistic regressor, % using a softmax function over the labels. % % REFERENCE % H. Larochelle and Y. Bengio. Classification using Discriminative Restricted % Boltzmann Machines. Proceedings of the 25th International Conference on % Machine Learning (ICML), pages 536?543, 2008. % % SEE ALSO % DATASETS, MAPPINGS, LOGLC % (C) Laurens van der Maaten, 2010 % University of California, San Diego name = 'Discr. RBM'; % Handle untrained calls like W = drbmc([]); if nargin == 0 || isempty(A) B = mapping(mfilename); B = setname(B, name); return; % Handle training on dataset A (use A * drbmc, A * drbmc([]), and drbmc(A)) elseif (nargin == 1 && isa(A, 'dataset')) || (isa(A, 'dataset') && isa(W, 'double')) if nargin < 2 W = 10; end if nargin < 3 L = 0; else if ~isa(L, 'double') error('Illegal call'); end end if nargin < 4 I = 1e-3; else if ~isa(I, 'double') error('Illegal call'); end end islabtype(A, 'crisp'); isvaldfile(A, 1, 2); A = testdatasize(A, 'features'); A = setprior(A, getprior(A)); [m, k, c] = getsize(A); % Normalize data and add extra feature train_X = +A; data.min_X = min(train_X(:)); train_X = train_X - data.min_X; data.max_X = max(train_X(:)); train_X = train_X / data.max_X; train_X = (train_X * 2) - 1; data.max_radius = max(sum(train_X .^ 2, 2)); train_X = [train_X sqrt(data.max_radius - sum(train_X .^ 2, 2))]; % Train the dRBM [data.machine, ll] = train_drbm(train_X, getnlab(A), W, 100, L, I); B = mapping(mfilename, 'trained', data, getlablist(A), k, c); B = setname(B, name); % Handle evaluation of a trained dRBM W for a dataset A elseif isa(A, 'dataset') && isa(W, 'mapping') % Normalize data and add extra feature test_X = +A; test_X = test_X - W.data.min_X; test_X = test_X / W.data.max_X; test_X = (test_X * 2) - 1; test_X = [test_X sqrt(W.data.max_radius - sum(test_X .^ 2, 2))]; % Evaluate dRBM [test_labels, test_post] = predict_ff(W.data.machine, test_X, length(W.labels)); A = dataset(A); B = setdata(A, test_post, getlabels(W)); ll = []; % This should not happen else error('Illegal call'); end end function [machine, ll] = train_drbm(X, labels, h, max_iter, weight_cost, variance) %TRAIN_DRBM Trains a discrimative RBM using gradient descent % % machine = train_drbm(X, labels, h, max_iter, weight_cost, variance) % % Trains a discriminative Restricted Boltzmann Machine on dataset X. The RBM % has h hidden nodes (default = 100). The training is performed by means of % the gradient descent. The visible and hidden units are binary stochastic, % whereas the label layer has softmax units. The maximum number of % iterations can be specified through max_iter (default = 30). % The trained RBM is returned in the machine struct. % % % (C) Laurens van der Maaten % University of California San Diego, 2010 % Process inputs if ischar(X) load(X); end if ~exist('h', 'var') || isempty(h) h = 100; end if ~exist('max_iter', 'var') || isempty(max_iter) max_iter = 15; end if ~exist('weight_cost', 'var') || isempty(weight_cost) weight_cost = 0; end % Randomly permute data ind = randperm(size(X, 1)); X = X(ind,:); labels = labels(ind); % Convert labels to binary matrix no_labels = length(unique(labels)); label_matrix = zeros(length(labels), no_labels); label_matrix(sub2ind(size(label_matrix), (1:length(labels))', labels)) = 1; % Initialize some variables [n, v] = size(X); machine.W = randn(v, h) * variance; machine.labW = randn(no_labels, h) * variance; machine.bias_upW = zeros(1, h); machine.bias_labW = zeros(1, no_labels); % Main loop for iter=1:max_iter % Encode current solution x = [machine.W(:); machine.labW(:); machine.bias_upW(:); machine.bias_labW(:)]; % Run conjugate gradients using five linesearches % checkgrad('drbm_grad', x, 1e-7, machine, cur_X, cur_lab, cur_labmat, weight_cost) x = minimize(x, 'drbm_grad', 9, machine, X, labels, label_matrix, weight_cost); % Process the updated solution ii = 1; machine.W = reshape(x(ii:ii - 1 + numel(machine.W)), size(machine.W)); ii = ii + numel(machine.W); machine.labW = reshape(x(ii:ii - 1 + numel(machine.labW)), size(machine.labW)); ii = ii + numel(machine.labW); machine.bias_upW = reshape(x(ii:ii - 1 + numel(machine.bias_upW)), size(machine.bias_upW)); ii = ii + numel(machine.bias_upW); machine.bias_labW = reshape(x(ii:ii - 1 + numel(machine.bias_labW)), size(machine.bias_labW)); end machine.type = 'drbm'; ll = drbm_grad(x, machine, X, labels, label_matrix, weight_cost); end function [test_labels, test_post] = predict_ff(machine, test_X, no_labels) %PREDICT_FF Perform label predictions in a feed-forward neural network % % [test_labels, test_post] = predict_ff(network, test_X, no_labels) % % The function performs label prediction in the feed-forward neural net % specified in network (trained using TRAIN_DBN) on dataset test_X. The % predicted labels are returned in test_labels. The class posterior is % returned in test_post. % % % (C) Laurens van der Maaten % University of California San Diego, 2010 % Precompute W dot X + bias Wx = bsxfun(@plus, test_X * machine.W, machine.bias_upW); % Loop over all labels to compute p(y|x) n = size(test_X, 1); energy = zeros(n, size(machine.labW, 2), no_labels); label_logpost = zeros(n, no_labels); for i=1:no_labels % Clamp current label lab = zeros(1, no_labels); lab(i) = 1; % Compute log-posterior probability for current class energy(:,:,i) = bsxfun(@plus, lab * machine.labW, Wx); label_logpost(:,i) = machine.bias_labW(i) + sum(log(1 + exp(energy(:,:,i))), 2); end test_post = exp(bsxfun(@minus, label_logpost, max(label_logpost, [], 2))); test_post = bsxfun(@rdivide, test_post, sum(test_post, 2)); [foo, test_labels] = max(test_post, [], 2); end function [C, dC] = drbm_grad(x, machine, X, labels, label_matrix, weight_cost) %DRBM_GRAD Computes gradient for training a discriminative RBM % % [C, dC] = drbm_grad(x, machine, X, labels, label_matrix) % % Computes gradient for training a discriminative RBM. % % % (C) Laurens van der Maaten % University of California San Diego, 2010 % Decode the current solution if ~isempty(x) ii = 1; machine.W = reshape(x(ii:ii - 1 + numel(machine.W)), size(machine.W)); ii = ii + numel(machine.W); machine.labW = reshape(x(ii:ii - 1 + numel(machine.labW)), size(machine.labW)); ii = ii + numel(machine.labW); machine.bias_upW = reshape(x(ii:ii - 1 + numel(machine.bias_upW)), size(machine.bias_upW)); ii = ii + numel(machine.bias_upW); machine.bias_labW = reshape(x(ii:ii - 1 + numel(machine.bias_labW)), size(machine.bias_labW)); end no_labels = size(label_matrix, 2); n = size(X, 1); % Precompute W dot X + bias Wx = bsxfun(@plus, X * machine.W, machine.bias_upW); % Loop over all labels to compute p(y|x) energy = zeros(n, size(machine.labW, 2), no_labels); label_logpost = zeros(n, no_labels); for i=1:no_labels % Clamp current label lab = zeros(1, no_labels); lab(i) = 1; % Compute log-posterior probability for current class energy(:,:,i) = bsxfun(@plus, lab * machine.labW, Wx); label_logpost(:,i) = machine.bias_labW(i) + sum(log(1 + exp(energy(:,:,i))), 2); end label_post = exp(bsxfun(@minus, label_logpost, max(label_logpost, [], 2))); label_post = bsxfun(@rdivide, label_post, sum(label_post, 2)); % Compute cost function -sum(log p(y|x)) Pyx = log(sum(label_matrix .* label_post, 2)); C = -sum(Pyx) + weight_cost * sum(machine.W(:) .^ 2); % Only compute gradients if they are requested if nargout > 1 % Precompute sigmoids of energies, and products with label posterior sigmoids = 1 ./ (1 + exp(-energy)); sigmoids_label_post = sigmoids; for i=1:no_labels sigmoids_label_post(:,:,i) = bsxfun(@times, sigmoids_label_post(:,:,i), label_post(:,i)); end % Initialize gradients grad_W = zeros(size(machine.W)); grad_labW = zeros(size(machine.labW)); grad_bias_upW = zeros(size(machine.bias_upW)); % Sum gradient with respect to the data-hidden weights for i=1:no_labels ind = find(labels == i); grad_W = grad_W + X(ind,:)' * sigmoids(ind,:,i) - X' * sigmoids_label_post(:,:,i); end grad_W = grad_W - 2 * weight_cost * machine.W; % Compute gradient with respect to bias on label-hidden weights for i=1:no_labels grad_labW(i,:) = sum(sigmoids(labels == i,:,i), 1) - sum(sigmoids_label_post(:,:,i), 1); end % Compute gradient with respect to bias on hidden units for i=1:no_labels grad_bias_upW = grad_bias_upW + sum(sigmoids(labels == i,:,i), 1) - sum(sigmoids_label_post(:,:,i), 1); end % Compute the gradient with respect to bias on labels grad_bias_labW = sum(label_matrix - label_post, 1); % Encode the gradient dC = -[grad_W(:); grad_labW(:); grad_bias_upW(:); grad_bias_labW(:)]; end end function [X, fX, i] = minimize(X, f, length, P1, P2, P3, P4, P5); % Minimize a continuous differentialble multivariate function. Starting point % is given by "X" (D by 1), and the function named in the string "f", must % return a function value and a vector of partial derivatives. The Polack- % Ribiere flavour of conjugate gradients is used to compute search directions, % and a line search using quadratic and cubic polynomial approximations and the % Wolfe-Powell stopping criteria is used together with the slope ratio method % for guessing initial step sizes. Additionally a bunch of checks are made to % make sure that exploration is taking place and that extrapolation will not % be unboundedly large. The "length" gives the length of the run: if it is % positive, it gives the maximum number of line searches, if negative its % absolute gives the maximum allowed number of function evaluations. You can % (optionally) give "length" a second component, which will indicate the % reduction in function value to be expected in the first line-search (defaults % to 1.0). The function returns when either its length is up, or if no further % progress can be made (ie, we are at a minimum, or so close that due to % numerical problems, we cannot get any closer). If the function terminates % within a few iterations, it could be an indication that the function value % and derivatives are not consistent (ie, there may be a bug in the % implementation of your "f" function). The function returns the found % solution "X", a vector of function values "fX" indicating the progress made % and "i" the number of iterations (line searches or function evaluations, % depending on the sign of "length") used. % % Usage: [X, fX, i] = minimize(X, f, length, P1, P2, P3, P4, P5) % % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13 RHO = 0.01; % a bunch of constants for line searches SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current bracket MAX = 20; % max 20 function evaluations per line search RATIO = 100; % maximum allowed slope ratio argstr = [f, '(X']; % compose string used to call function for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; end argstr = [argstr, ')']; if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end if length>0, S=['Linesearch']; else S=['Function evaluation']; end i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed fX = []; [f1 df1] = eval(argstr); % get function value and gradient i = i + (length<0); % count epochs?! s = -df1; % search direction is steepest d1 = -s'*s; % this is the slope z1 = red/(1-d1); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; f0 = f1; df0 = df1; % make a copy of current values X = X + z1*s; % begin line search [f2 df2] = eval(argstr); i = i + (length<0); % count epochs?! d2 = df2'*s; f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1 if length>0, M = MAX; else M = min(MAX, -length-i); end success = 0; limit = -1; % initialize quanteties while 1 while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0) limit = z1; % tighten the bracket if f2 > f1 z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit else A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit B = 3*(f3-f2)-z3*(d3+2*d2); z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok! end if isnan(z2) | isinf(z2) z2 = z3/2; % if we had a numerical problem then bisect end z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits z1 = z1 + z2; % update the step X = X + z2*s; [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; z3 = z3-z2; % z3 is now relative to the location of z2 end if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1 break; % this is a failure elseif d2 > SIG*d1 success = 1; break; % success elseif M == 0 break; % failure end A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation B = 3*(f3-f2)-z3*(d3+2*d2); z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok! if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign? if limit < -0.5 % if we have no upper limit z2 = z1 * (EXT-1); % the extrapolate the maximum amount else z2 = (limit-z1)/2; % otherwise bisect end elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max? z2 = (limit-z1)/2; % bisect elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit z2 = z1*(EXT-1.0); % set to extrapolation limit elseif z2 < -z3*INT z2 = -z3*INT; elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit? z2 = (limit-z1)*(1.0-INT); end f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2 z1 = z1 + z2; X = X + z2*s; % update current estimates [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; end % end of line search if success % if line search succeeded f1 = f2; fX = [fX' f1]'; s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction tmp = df1; df1 = df2; df2 = tmp; % swap derivatives d2 = df1'*s; if d2 > 0 % new slope must be negative s = -df1; % otherwise use steepest direction d2 = -s'*s; end z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO d1 = d2; ls_failed = 0; % this line search did not fail else X = X0; f1 = f0; df1 = df0; % restore point from before failed line search if ls_failed | i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end tmp = df1; df1 = df2; df2 = tmp; % swap derivatives s = -df1; % try steepest d1 = -s'*s; z1 = 1/(1-d1); ls_failed = 1; % this line search failed end end end function d = checkgrad(f, X, e, P1, P2, P3, P4, P5, P6); % checkgrad checks the derivatives in a function, by comparing them to finite % differences approximations. The partial derivatives and the approximation % are printed and the norm of the diffrence divided by the norm of the sum is % returned as an indication of accuracy. % % usage: checkgrad('f', X, e, P1, P2, ...) % % where X is the argument and e is the small perturbation used for the finite % differences. and the P1, P2, ... are optional additional parameters which % get passed to f. The function f should be of the type % % [fX, dfX] = f(X, P1, P2, ...) % % where fX is the function value and dfX is a vector of partial derivatives. % % Carl Edward Rasmussen, 2001-08-01. argstr = [f, '(X']; % assemble function call strings argstrd = [f, '(X+dx']; for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; argstrd = [argstrd, ',P', int2str(i)]; end argstr = [argstr, ')']; argstrd = [argstrd, ')']; [y dy] = eval(argstr); % get the partial derivatives dy dh = zeros(length(X),1) ; for j = 1:length(X) dx = zeros(length(X),1); dx(j) = dx(j) + e; % perturb a single dimension y2 = eval(argstrd); dx = -dx ; y1 = eval(argstrd); dh(j) = (y2 - y1)/(2*e); end disp([dy dh]) % print the two vectors d = norm(dh-dy)/norm(dh+dy); % return norm of diff divided by norm of sum end
github
jacksky64/imageProcessing-master
prtrace.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prtrace.m
2,266
utf_8
2492aac5f515f3f1e84df641d32beb43
%PRTRACE Trace PRTools routines % % Routine is outdated and will directly return % % PRTRACE ON Tracing of the PRTools routines is switched on % PRTRACE OFF Tracing of the PRTools routines is switched off % PRTRACE(MESSAGE,LEVEL) % % INPUT % MESSAGE String % LEVEL Trace level (optional; default: 1/0 if PRTRACE is ON/OFF) % % DESCRIPTION % Note that PRTRACE describes both a global variable (ON/OFF) and a function. % If PRTRACE is ON, each access to each PRTools routine is reported. % Additional trace messages may be added by PRTRACE(MESSAGE) in which MESSAGE % is a string, listed when the command is encountered and PRTRACE is ON. The % standard MESSAGE is the name of the executing m-file (MFILENAME). % % PRTRACE(MESSAGE,LEVEL) lists the traced message above some level. If % PRTRACE is switched ON, the trace-level is increased by one. Only % if LEVEL >= trace-level, MESSAGE is displayed. If PRTRACE is switched % OFF, the trace-level is reset to 0. For all main routines of PRTools, % LEVEL is set to 1. All basic routines defining MAPPINGS and DATASETS % (except for MAPPING and DATASET themselves) have the trace-level of 2. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: prtrace.m,v 1.4 2008/07/28 09:02:30 duin Exp $ function prtrace(message,level) return % persistent PRTRACEGLOBAL % % % If PRTRACEGLOBAL was not defined, do it now. % if isempty(PRTRACEGLOBAL) % PRTRACEGLOBAL = 0; % dataset; % make sure that PRTools is activated % end % % % Check the input arguments. % if (nargin == 0) % ; % elseif (~isstr(message)) % error('No MESSAGE string found.') % else % % Depending on message, we should turn the messaging ON or OFF, or we % % have to increase the trace-level and show the message when the % % trace-level is high enough. % % switch message % case {'on','ON'} % PRTRACEGLOBAL = PRTRACEGLOBAL+1; % case {'off','OFF'} % PRTRACEGLOBAL = 0; % otherwise % if (PRTRACEGLOBAL) % if (nargin == 1) % level = 1; % end % if (PRTRACEGLOBAL >= level) % disp(message); % end % end % end % end % % return;
github
jacksky64/imageProcessing-master
featselm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featselm.m
3,336
utf_8
ca470807d2d85e5ff55358b1b70152ae
%FEATSELM Feature selection map % % [W,R] = FEATSELM(A,CRIT,METHOD,K,T,PAR1,...) % % INPUT % A Training dataset % CRIT Name of criterion: 'in-in', 'maha-s', 'NN' or others % (see FEATEVAL) or an untrained classifier V (default: 'NN') % METHOD - 'forward' : selection by featself (default) % - 'float' : selection by featselp % - 'backward': selection by featselb % - 'b&b' : branch and bound selection by featselo % - 'ind' : individual % - 'lr' : plus-l-takeaway-r selection by featsellr % - 'sparse' : use sparse untrained classifier CRIT % K Desired number of features (default: K = 0, return optimal set) % T Tuning set to be used in FEATEVAL (optional) % PAR1,.. Optional parameters: % - L,R : for 'lr' (default: L = 1, R = 0) % % OUTPUT % W Feature selection mapping % R Matrix with step by step results % % DESCRIPTION % Computation of a mapping W selecting K features. This routines offers a % central interface to all other feature selection methods. W can be used % for selecting features in a dataset B using B*W. % % SEE ALSO % MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELI, % FEATSELP, FEATSELF, FEATSELLR % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [w,res] = featselm(a,crit,arg3,ksel,t,par1,par2) prtrace(mfilename); if (nargin < 2 | isempty(crit)) prwarning(2,'criterion not specified, assuming NN'); crit = 'NN'; end if (nargin < 3 | isempty(arg3)) prwarning(2,'method not specified, assuming forward'); arg3 = 'forward'; end if (nargin < 4) ksel = []; end if (nargin < 5) prwarning(3,'no tuning set supplied (risk of overfit)'); t = []; end if (nargin < 6), par1 = []; end; if (nargin < 7), par2 = []; end; % If no arguments are supplied, return an untrained mapping. if (nargin == 0) | (isempty(a)) w = mapping('featselm',{crit,arg3,ksel,t,par1,par2}); w = setname(w,'Feature Selection'); return end a = testdatasize(a); [m,k] = size(a); if (isstr(arg3)) method = arg3; % If the third argument is a string, switch (method) % it specifies the method to use. case {'forward','featself'} [w,res] = featself(a,crit,ksel,t); case {'float','featselp'} [w,res] = featselp(a,crit,ksel,t); case {'backward','featselb'} [w,res] = featselb(a,crit,ksel,t); case {'b&b','featselo'} [w,res] = featselo(a,crit,ksel,t); case {'ind','featseli'} [w,res] = featseli(a,crit,ksel,t); case {'lr','featsellr'} [w,res] = featsellr(a,crit,ksel,par1,par2,t); case {'sparse'} v = a*crit; if isaffine(v) v = getdata(v,'rot'); w = featsel(size(a,2),find(v(:,1) == 0)); else v = getdata(v,'beta'); end w = featsel(size(a,2),find(v(:,1) ~= 0)); otherwise error('Unknown method specified.') end elseif (ismapping(arg3)) w = arg3; % If the third argument is a mapping, isuntrained(w); % assert it is untrained and train [w,res] = feval(mfilename,a,crit,w.mapping_file,ksel,t,par1,par2); else error('Illegal method specified.') end return
github
jacksky64/imageProcessing-master
seldat.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/seldat.m
5,055
utf_8
44125bd3175a5107456aafda72e2e865
%SELDAT Select subset of dataset % % [B,J] = SELDAT(A,C,F,N) % B = A*SELDAT([],C,F,N) % [B,J] = SELDAT(A,D) % % INPUT % A Dataset % C Indexes of classes (optional; default: all) % F Indexes of features (optional; default: all) % N Indices of objects extracted from classes in C % Should be cell array in case of multiple classes % (optional; default: all) % D Dataset % % OUTPUT % B Subset of the dataset A % J Indices of returned objects in dataset A: B = A(J,:) % % DESCRIPTION % B is a subset of the dataset A defined by the set of classes (C), % the set of features (F) and the set of objects (N). Classes and % features have to be identified by their index. The order of class % names can be found by GETLABLIST(A). The index of a particular % class can be determined by GETCLASSI. N is applied to all classes % defined in C. Defaults: select all, except unlabeled objects. % % In case A is soft labeled or is a target dataset by B = SELDAT(A,C) the % entire dataset is returned, but the labels or targets are reduced to the % selected class (target) C. % % B = SELDAT(A,D) % % If D is a dataset that is somehow is derived from A, e.g. by selection % and mappings, then the corresponding objects of A are retrieved by their % object identifiers and returned into B. % % B = SELDAT(A) % % Retrieves all labeled objects of A. % % In all cases empty classes are removed. % % EXAMPLES % Generate 8 class, 2-D dataset and select: the second feature, objects % 1 from class 1, 0 from class 2 and 1:3 from class 6 % % A = GENDATM([3,3,3,3,3,3,3,3]); % B = SELDAT(A,[1 2 6],2,{1;[];1:3}); % or % B = SELDAT(A,[],2,{1;[];[];[];[];1:3}); % % SEE ALSO % DATASETS, GENDAT, GETLABLIST, GETCLASSI, REMCLASS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: seldat.m,v 1.13 2009/02/19 12:27:10 duin Exp $ function [b,J] = seldat(a,clas,feat,n) prtrace(mfilename); if nargin < 4, n = {}; end if nargin < 3, feat = []; end if nargin < 2, clas = []; end if isempty(a), b = mapping(mfilename,'fixed',{clas,feat,n}); return; end [m,k,c] = getsize(a); allfeat = 0; allclas = 0; if isempty(feat), allfeat = 1; feat = [1:k]; end if (isempty(clas) & isempty(n)) allclas = 1; clas = [1:c]; end if isdataset(clas) % If input D is a dataset, it is assumed that D was derived from % A, and therefore the object identifiers have to be matched. J = getident(clas); L = findident(a,J); L = cat(1,L{:}); b = a(L,:); else % Otherwise, we have to extract the right class/fetaures and/or % objects: %if ~islabtype(a,'crisp') & ~allclas % error('Class selection only possible in case of crisp labels') %end if max(feat) > k error('Feature out of range'); end %DXD: allow for selection based on class names instead of class %indices: if ~isa(clas,'double') % names in cell arrays are also possible if isa(clas,'cell') clas = strvcat(clas); end % be sure we are dealing with char's here (if it were doubles, % we were not even allowed to enter here) if ~isa(clas,'char') error('I am expecting class indices or names.'); end % match the names with the lablist: names = clas; ll = getlablist(a); clas = zeros(1,size(names,1)); for i = 1:size(names,1) %DXD test if the class is present at all, otherwise an error %occurs: found = strmatch(names(i,:),ll); if ~isempty(found) clas(1,i) = found; end end end clas = clas(:)'; if max(clas) > c error('Class number out of range') end if iscell(n) if (~(isempty(n) | isempty(clas))) & (length(n) ~= size(clas,2)) error('Number of cells in N should be equal to the number of classes') end else if size(clas,2) > 1 error('N should be a cell array, specifying objects for each class'); end n = {n}; end % Do the extraction: if allclas & isempty(n) J = findnlab(a,0); if ~isempty(J) a(J,:) = []; end else if isempty(clas) & ~isempty(n) clas = zeros(1,length(n)); for i = 1:length(n) if(~isempty(n(i))) clas(1,i) = i; end end end if islabtype(a,'crisp') J = []; for j = 1:size(clas,2) JC = findnlab(a,clas(1,j)); if ~isempty(n) if max(cat(1,n{j})) > length(JC) error('Requested objects not available in dataset') end J = [J; JC(n{j})]; else J = [J; JC]; end end a = a(J,:); else labl = getlablist(a); labl = labl(clas,:); targ = gettargets(a); targ = targ(:,clas); [tt,nlab] = max(targ,[],2); a = setnlab(a,1); a = setlablist(a,labl); a = settargets(a,targ); a = setnlab(a,nlab); if ~isempty(a.prior) priora = a.prior(clas); priora = priora/sum(priora); a.prior = priora; end end end if allfeat b = a; else b = a(:,feat); end end b = setlablist(b); % reset lablist to remove empty classes return;
github
jacksky64/imageProcessing-master
gtm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gtm.m
7,622
utf_8
01519a52974eadcfbb3cd939ee1f98b7
%GTM Fit a Generative Topographic Mapping using the % expectation-maximisation algorithm. % % [W,L] = GTM (A,K,M,MAPTYPE,REG,EPS,MAXITER) % % INPUT % A Dataset or double matrix % K Vector containing number of nodes per dimension (default: [5 5], 2D map) % M Vector containing number of basis functions per dimension (default: [10 10]) % MAPTYPE Map onto mean of posterior ('mean', default) or mode ('mode') % REG Regularisation (default: 0) % EPS Change in likelihood to stop training (default: 1e-5) % MAXITER Maximum number of iterations (default: inf) % % OUTPUT % W GTM mapping % L Likelihood % % DESCRIPTION % Trains a Generative Topographic Mapping of any dimension, using the EM % algorithm. % % REFERENCES % Bishop, C.M., Svensen, M. and Williams, C.K.I., "GTM: The Generative % Topographic Mapping", Neural Computation 10(1):215-234, 1998. % % SEE ALSO % PLOTGTM, SOM, PLOTSOM % (c) Dick de Ridder, 2003 % Information & Communication Theory Group % Faculty of Electrical Engineering, Mathematics and Computer Science % Delft University of Technology, Mekelweg 4, 2628 CD Delft, The Netherlands function [w,L] = gtm (a, arg2, M, mapto, reg, epsilon, maxiter) prtrace(mfilename); step = 10; if (nargin < 2) prwarning(3,'number of nodes K not given, assuming [5 5] (2D map)'); arg2 = [5 5]; end; if (~ismapping(arg2)) if (nargin < 7) maxiter = inf; end; if (nargin < 6) prwarning(3,'stopping criteria not given, assuming EPSILON = 1e-10'); epsilon = 1e-10; end; if (nargin < 5) prwarning(3,'regularisation REG not given, assuming 0'); reg = 0; end; if (nargin < 4) prwarning(3,'mapping type MAPTO not given, assuming mean'); mapto = 'mean'; end; if (nargin < 3) prwarning(3,'number of basis functions M not given, assuming 10'); M = 5; end; end; if (nargin == 0) | isempty(a) W = mapping(mfilename); W = setname(W,'GTM'); return; end % Prevent annoying messages: we will tell the user about any problems. warning off; a = testdatasize(a); t = +a'; [d,N] = size(t); [m,k] = size(a); % If we're to apply a trained mapping, unpack its parameters. if (ismapping(arg2)) w = arg2; data = getdata(w); K = data{1}; M = data{2}; W = data{3}; sigma = data{4}; mapto = data{5}; else K = arg2; end; % Create a KK-dimensional grid with dimensions K(1), K(2), ... of % D-dimensional grid points and store it as a D x KK matrix X. Do the % same for the basis function centers PHI_MU, with grid dimensions M(1), ... K = reshape(K,1,prod(size(K))); % Turn into vectors. M = reshape(M,1,prod(size(M))); % Check: either K or M should be a vector, or both should be vectors of % the same length. if (length(K) > 1) & (length(M) == 1) M = M * ones(1,length(K)); elseif (length(M) > 1) & (length(K) == 1) K = K * ones(1,length(M)); elseif (length(K) ~= length(M)) error ('Length of vectors K and M should be equal, or K and/or M should be scalar.'); end; D = length(K); KK = prod(K); MM = prod(M); if (D > d) error ('Length of vectors K and M should be <= the data dimensionality.'); end; x = makegrid(K,D); % Grid points. phi_mu = makegrid(M,D); % Basis function centers. phi_sigma = 2/(mean(M)-1); % Basis function widths. % Pre-calculate Phi. for j = 1:KK for i = 1:MM Phi(i,j) = exp(-(x(:,j)-phi_mu(:,i))'*(x(:,j)-phi_mu(:,i))/(phi_sigma^2)); end; end; if (~ismapping(arg2)) % Train mapping. tries = 0; retry = 1; while ((retry == 1) & (tries <= 5)) % Initialisation. ptx = zeros(KK,N); R = (1/KK)*ones(KK,N); C = prcov(t'); [U,DD] = preig(C); [dummy,ind] = sort(-diag(DD)); W = U(:,ind(1:D))*x*prpinv(Phi); if (size(C,1) > D) sigma = sqrt(DD(D+1,D+1)); else sigma = 1/mean(M); end; done = 0; iter = 0; retry = 0; likelihood = 1.0e20; while ((~done) & (~retry)) iter = iter + 1; done = 1; factor1 = (1/(2*pi*sigma^2))^(d/2); factor2 = (-1/(2*sigma^2)); WPhi = W*Phi; for i = 1:KK ptx(i,:) = factor1 * exp(factor2*sum((WPhi(:,i)*ones(1,N)-t).^2)); end; if (~retry) s = sum(ptx); s(find(s==0)) = realmin; % Prevent divide-by-zero. R = ptx ./ (ones(size(ptx,1),1)*s); G = diag(sum(R')); % M-step #1 (eqn. 12) W = (prinv(Phi*G*Phi' + reg*eye(MM))*Phi*R*t')'; % M-step #1 (eqn. 13) s = 0; WPhi = W*Phi; for i = 1:KK s = s + sum(R(i,:).*sum((WPhi(:,i)*ones(1,N)-t).^2)); end; sigma = sqrt((1/(N*d)) * s); % Re-calculate log-likelihood. prev_likelihood = likelihood; likelihood = sum(log(mean(ptx)+realmin)); if (rem (iter,step) == 0) prwarning (10, sprintf('[%3d] L: %2.2f (change: %2.2e)', ... iter, likelihood, abs ((likelihood - prev_likelihood)/likelihood))); end; % Continue? done = (abs ((likelihood - prev_likelihood)/likelihood) < epsilon); done = (done | (iter > maxiter)); if (~isfinite(likelihood)) prwarning(3,'Problem is poorly conditioned, retrying'); retry = 1; tries = tries + 1; end; end; end; end; L = likelihood; if (~retry) w = mapping(mfilename,'trained',{K,M,W,sigma,mapto},[],k,D); w = setname(w,'GTM'); else prwarning(3,'Problem is too poorly conditioned, giving up'); prwarning(3,'Consider lowering K and M or increasing REG'); w = []; end; else % Apply mapping. factor1 = (1/(2*pi*sigma^2))^(d/2); factor2 = (-1/(2*sigma^2)); WPhi = W*Phi; for i = 1:KK ptx(i,:) = factor1 * exp(factor2*sum((WPhi(:,i)*ones(1,N)-t).^2)); end; s = sum(ptx); s(find(s==0)) = realmin; % Prevent divide-by-zero. R = ptx ./ (ones(size(ptx,1),1)*s); switch(mapto) case 'mean', out = (x*R)'; case 'mode', [dummy,ind] = max(R); out = x(:,ind)'; otherwise, error ('unknown mapping type: should be mean or mode') end; w = setdata(a,out,getlabels(w)); end; warning on; return % GRID = MAKEGRID (K,D) % % Create a KK = prod(K)-dimensional grid with dimensions K(1), K(2), ... of % D-dimensional uniformly spaced grid points on [0,1]^prod(K), and store it % as a D x KK matrix X. function grid = makegrid (K,D) KK = prod(K); for h = 1:D xx{h} = 0:(1/(K(h)-1)):1; % Support point means end; % Do that voodoo / that you do / so well... if (D==1) xm = xx; else cmd = '['; for h = 1:D-1, cmd = sprintf ('%sxm{%d}, ', cmd, h); end; cmd = sprintf ('%sxm{%d}] = ndgrid(', cmd, D); for h = 1:D-1, cmd = sprintf ('%sxx{%d}, ', cmd, h); end; cmd = sprintf ('%sxx{%d});', cmd, D); eval(cmd); end; cmd = 'mm = zeros(D, '; for h = 1:D-1, cmd = sprintf ('%s%d, ', cmd, K(h)); end; cmd = sprintf ('%s%d);', cmd, K(D)); eval (cmd); for h = 1:D cmd = sprintf ('mm(%d,', h); for g = 1:D-1, cmd = sprintf ('%s:,', cmd); end; cmd = sprintf ('%s:) = xm{%d};', cmd, h); eval (cmd); end; grid = reshape(mm,D,KK); return
github
jacksky64/imageProcessing-master
naivebcc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/naivebcc.m
4,467
utf_8
98b2b2891939f7514f2b34f6ca7d6cac
% NAIVEBCC Naive Bayes Combining Classifier % % W = A*(WU*NAIVEBCC) % W = WT*NAIVEBCC(B*WT) % D = C*W % % INPUT % A Dataset used for training base classifiers as well as combiner % B Dataset used for training combiner of trained base classifiers % C Dataset used for testing (executing) the combiner % WU Set of untrained base classifiers, see STACKED % WT Set of trained base classifiers, see STACKED % % OUTPUT % W Trained Naive Bayes Combining Classifier % D Dataset with prob. products (over base classifiers) per class % % DESCRIPTION % During training the combiner computes the probabilities % P(class | classifier outcomes) based on the crisp class assignements % made by the base classifiers for the training set. During execution the % product of these probabilities are computed, again following the crisp % class assignments of the base classifiers. These products are returned % as columns in D. Use CLASSC to normalise the outcomes. Use TESTD or % LABELD to inspect performances and assigned labels. % % NAIVEBCC differs from the classifier NAIVEBC by the fact that the % latter uses continuous inputs (no crisp labeling) and does not make a % distinction between classifiers. Like almost any other classifier % however, NAIVEBC may be used as a trained combiner as well. % % REFERENCE % 1. Kuncheva, LI. Combining pattern classifiers, 2004, pp.126-128. % % SEE ALSO % DATASETS, MAPPINGS, STACKED, NAIVEBC, CLASSC, TESTD, LABELD % Copyright: Chunxia Zhang, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function V = naivebcc(A,W) prtrace(mfilename); name = 'Naive Bayes combiner'; if nargin < 1 | isempty(A) % If there are no inputs, return an untrained mapping. V = mapping(mfilename); V = setname(V,name); elseif nargin == 1 % call like V = NBC(A): train a NB classifier on the outcomes of the % base classifiers. So A has c x k columns: % c outcomes (classes) x k classifiers islabtype(A,'crisp'); % allow crisp labels only isvaldfile(A,1,2); % at least one object per class, 2 classes A = testdatasize(A,'features'); % test whether they fit A = setprior(A,getprior(A,0)); % avoid many warnings [m,k,c] = getsize(A); % size of training set (m objects; k features; c classes) L = k/c; % compute the number of classifiers G = zeros(L*c,c); % confusion matrix for each base classifier for i = 1:L data = +A(:,(i-1)*c+1:i*c); [max_val,max_ind] = max(data,[],2); CM = zeros(c,c); % the (k,s)th entry indicates the number of elements % whose true labels are omega_k and are assigned to omega_s for k = 1:c for s = 1:c CM(k,s) = sum(A.nlab == k & max_ind == s); end end G((i-1)*c+1:i*c,:) = CM'; % transpose the confusion matrix to facilitate % the further computation end vector = classsizes(A); % Find all class probs for all classifiers P(class | classifiers) % P = (vector/m)*prod((G+1/c)./repmat(vector+1,size(G,1),1)); P = (G+1/c)./repmat(vector+1,size(G,1),1); % P(x|class) P = P.*repmat(getprior(A),size(P,1),1); % P(x|class) P(class) q = sum(P,2); % P(x) P = P./repmat(q,1,c); % P(class|x) V = mapping(mfilename,'trained',P,getlablist(A),L*c,c); V = setname(V,name); elseif nargin == 2 & ismapping(W) % execution % call like V = A*W, in which W is a trained NBC isdataset(A); [m,k] = size(A); P = getdata(W); % Prob matrix found by training c = size(P,2); % Number of classes L = size(P,1)/c; % number of classifiers % We assume that the k features of A (columns) are the results of % L classifiers producing c outcomes. We will construct a matrix % M with for every classifier a 1 for its maximum class (most % confident) class. M = zeros(m,k); for i = 1:L NM = zeros(m,c); S = (i-1)*c+1:i*c; [maxv,maxi] = max(+A(:,S),[],2); NM(sub2ind([m,c],[1:m]',maxi)) = ones(m,1); M(:,S) = NM; end % Now the confidences of the combiner will be estimated according % to the product over the classifiers of P(classifier|class) % estimated during training d = zeros(m,c); R = reshape(find(M'==1)-[1:c:m*c*L]',L,m)'+repmat([1:c:c*L],m,1); for j=1:c q = P(:,j)'; d(:,j) = prod(q(R),2); end %d = d*normm; % normalise confidences, leave to user V = setdat(A,d,W); % store in dataset end return
github
jacksky64/imageProcessing-master
gendatgauss.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatgauss.m
4,913
utf_8
979e2ea312308dfc22d0d67f3d74fb28
%GENDATGAUSS (Formerly GAUSS) Generation of a multivariate Gaussian dataset % % A = GENDATGAUSS(N,U,G,LABTYPE) % % INPUT (in case of generation a 1-class dataset in K dimensions) % N Number of objects to be generated (default 50). % U Desired mean (vector of length K). % G K x K covariance matrix. Default eye(K). % LABTYPE Label type (default 'crisp') % % INPUT (in case of generation a C-class dataset in K dimensions) % N Vector of length C with numbers of objects per class. % U C x K matrix with class means, or % Dataset with means, labels and priors of classes % (default: zeros(C,K)) % G K x K x C covariance matrix of right size. % Default eye(K); % LABTYPE Label type (default 'crisp') % % OUTPUT % A Dataset containing multivariate Gaussian data % % DESCRIPTION % Generation of N K-dimensional Gaussian distributed samples for C classes. % The covariance matrices should be specified in G (size K*K*C) and the % means, labels and prior probabilities can be defined by the dataset U with % size (C*K). If U is not a dataset, it should be a C*K matrix and A will % be a dataset with C classes. % % If N is a vector, exactly N(I) objects are generated for class I, % I = 1..C. % % EXAMPLES % 1. Generation of 100 points in 2D with mean [1 1] and default covariance % matrix: % % GENDATGAUSS(100,[0 0]) % % 2. Generation of 50 points for each of two 1-dimensional distributions with % mean -1 and 1 and with variances 1 and 2: % % GENDATGAUSS([50 50],[-1;1],CAT(3,1,2)) % % Note that the two 1-dimensional class means should be given as a column % vector [1;-1], as [1 -1] defines a single 2-dimensional mean. Note that % the 1-dimensional covariance matrices degenerate to scalar variances, % but have still to be combined into a collection of square matrices using % the CAT(3,....) function. % % 3. Generation of 300 points for 3 classes with means [0 0], [0 1] and % [1 1] and covariance matrices [2 1; 1 4], EYE(2) and EYE(2): % % GENDATGAUSS(300,[0 0; 0 1; 1 1]*3,CAT(3,[2 1; 1 4],EYE(2),EYE(2))) % % SEE ALSO % DATASETS, PRDATASETS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function a = gendatgauss(n,u,g,labtype) prtrace(mfilename); if (nargin < 1) prwarning (2,'number of samples not specified, assuming N = 50'); n = 50; end cn = length(n); if (nargin < 2) prwarning (2,'means not specified; assuming one dimension, mean zero'); u = zeros(cn,1); end; if (nargin < 3) prwarning (2,'covariances not specified, assuming unity'); g = eye(size(u,2)); end if (nargin < 4) prwarning (3,'label type not specified, assuming crisp'); labtype = 'crisp'; end % Return an empty dataset if the number of samples requested is 0. if (length(n) == 1) & (n == 0) a = dataset([]); return end % Find C, desired number of classes based on U and K, the number of % dimensions. Make sure U is a dataset containing the means. if (isa(u,'dataset')) [m,k,c] = getsize(u); lablist = getlablist(u); p = getprior(u); if c == 0 u = double(u); end end if isa(u,'double') [m,k] = size(u); c = m; lablist = genlab(ones(c,1)); u = dataset(u,lablist); p = ones(1,c)/c; end if (cn ~= c) & (cn ~= 1) error('The number of classes specified by N and U does not match'); end % Generate a class frequency distribution according to the desired priors. n = genclass(n,p); % Find CG, the number of classes according to G. % Make sure G is not a dataset. if (isempty(g)) g = eye(k); cg = 1; else g = real(+g); [k1,k2,cg] = size(g); if (k1 ~= k) | (k2 ~= k) error('The number of dimensions of the means U and covariance matrices G do not match'); end if (cg ~= m & cg ~= 1) error('The number of classes specified by the means U and covariance matrices G do not match'); end end % Create the data A by rotating and scaling standard normal distributions % using the eigenvectors of the specified covariance matrices, and adding % the means. a = []; for i = 1:m j = min(i,cg); % Just in case CG = 1 (if G was not specified). % Sanity check: user can pass non-positive definite G. [V,D] = preig(g(:,:,j)); V = real(V); D = real(D); D = max(D,0); a = [a; randn(n(i),k)*sqrt(D)*V' + repmat(+u(i,:),n(i),1)]; end % Convert A to dataset by adding labels and priors. labels = genlab(n,lablist); a = dataset(a,labels,'lablist',lablist,'prior',p); % If non-crisp labels are requested, use output of Bayes classifier. switch (labtype) case 'crisp' ; case 'soft' w = nbayesc(u,g); targets = a*w*classc; a = setlabtype(a,'soft',targets); otherwise error(['Label type ' labtype ' not supported']) end a = setname(a,'Gaussian Data'); return
github
jacksky64/imageProcessing-master
marksize.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/marksize.m
421
utf_8
5f56b132318a2fe2d3554b9581dfe7b6
%MARKSIZE Change markersize in lineplot or scatterplot % % marksize(size,marker) % % The marker fontsize (default set by matlab to 6) is reset % to size for the given marker, default: all markers. % function marksize(siz,marker) if nargin == 1, marker = ' '; end h = get(gca,'Children')'; for i = h if strcmp(get(i,'Type'),'line') if nargin == 1 | get(i,'Marker') == marker set(i,'MarkerSize',siz); end end end
github
jacksky64/imageProcessing-master
svmr.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/svmr.m
2,133
utf_8
a4b79163f7829d338e4df40e406fc30c
%SVMR SVM regression % % W = SVMR(X,NU,KTYPE,KPAR,EP) % % INPUT % X Regression dataset % NU Fraction of objects outside the 'data tube' % KTYPE Kernel type (default KTYPE='p', for polynomial) % KPAR Extra parameter for the kernel % EP Epsilon, with of the 'data tube' % % OUTPUT % W Support vector regression % % DESCRIPTION % Train an nu-Support Vector Regression on dataset X with parameter NU. % The kernel is defined by kernel type KTYPE and kernel parameter KPAR. % For the definitions of these kernels, have a look at proxm.m. % % SEE ALSO % LINEARR, PROXM, GPR, SVC % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function y = svmr(x,nu,ktype,kpar,ep) if nargin<5 ep = 0.2; end if nargin<4 kpar = 1; end if nargin<3 ktype = 'p'; end if nargin<2 nu = 0.01; end if nargin<1 | isempty(x) y = mapping(mfilename,{nu,ktype,kpar,ep}); y = setname(y,'SVM regression'); return end if ~ismapping(nu) %training [n,d] = size(x); y = gettargets(x); % kernel mapping: wk = proxm(+x,ktype,kpar); K = +(x*wk); % setup optimization: tol = 1e-6; C = 1/(n*nu); H = [K -K; -K K]; f = repmat(ep,2*n,1) - [y; -y]; A = []; b = []; Aeq = [ones(1,n) -ones(1,n)]; beq = 0; lb = zeros(2*n,1); ub = repmat(C,2*n,1); %do the optimization: if exist('qld') alf = qld(H,f,Aeq,beq,lb,ub,[],1); else alf = quadprog(H,f,A,b,Aeq,beq,lb,ub); end % find SV's w = alf(1:n)-alf((n+1):end); % the real weights Isv = find(abs(w)>tol); Ibnd = find(abs(w(Isv))<C-tol); % for the 'real' sv's, we want the classifier output to compute the % offset: I = Isv(Ibnd); out1 = sum(repmat(w',length(Ibnd),1).*K(I,:),2); sw = sign(w); out = y(I) - out1 - sw(I).*ep; % store the useful parameters: W.b = mean(out); W.wk = proxm(+x(Isv,:),ktype,kpar); W.w = w(Isv); y = mapping(mfilename,'trained',W,1,d,1); y = setname(y,'Linear regression'); else % evaluation W = getdata(nu); [n,d] = size(x); Kz = +(x*W.wk); out = sum(repmat(W.w',n,1).*Kz,2) + repmat(W.b,n,1); y = setdat(x,out); end
github
jacksky64/imageProcessing-master
scatterr.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/scatterr.m
729
utf_8
7d9a51df0874b46f92b6d1850ff9eaaf
%SCATTERR Scatter regression data % % H = SCATTERR(X,CLRS) % % INPUT % X Regression dataset % CLRS Plot string (default CLRS = 'k.') % % OUTPUT % H Vector of handles % % DESCRIPTION % Scatter the regression dataset X with marker colors CLRS. % % SEE ALSO % PLOTR % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function h = plottarget(x,clrs) if nargin<2 clrs = 'k.'; end y = gettargets(x); h = plot(+x(:,1),y,clrs); fl = getfeatlab(x); xlabel(fl(1,:)); ylabel('target'); % also set the identifiers: ud = get(h,'UserData'); ud.ident = getident(x); set(h,'UserData',ud); if nargout<1 clear h; end return
github
jacksky64/imageProcessing-master
istrained.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/istrained.m
719
utf_8
16db91f39638d441eeea6d5517bdd52a
%ISTRAINED Test on trained mapping % % I = ISTRAINED(W) % ISTRAINED(W) % % True if the mapping type of W is 'trained' (see HELP MAPPINGS). If % called without an output argument ISTRAINED generates an error if the % mapping type of W is not 'trained'. % $Id: istrained.m,v 1.1 2009/03/18 16:12:41 duin Exp $ function i = istrained(w) prtrace(mfilename,2); if iscell(w) i = strcmp(w{1}.mapping_type,'trained'); for j=2:length(w) if strcmp(w{j}.mapping_type,'trained') ~= i error('Cell array of classifiers cannot be partially trained') end end else i = strcmp(w.mapping_type,'trained'); end if nargout == 0 & i == 0 error([newline '---- Trained mapping expected ----']) end return
github
jacksky64/imageProcessing-master
testk.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testk.m
1,874
utf_8
e4041302fe206e0842baa466bfa2e810
%TESTK Error estimation of the K-NN rule % % E = TESTK(A,K,T) % % INPUT % A Training dataset % K Number of nearest neighbors (default 1) % T Test dataset (default [], i.e. find leave-one-out estimate on A) % % OUTPUT % E Estimated error of the K-NN rule % % DESCRIPTION % Tests a dataset T on the training dataset A using the K-NN rule and % returns the classification error E. In case no set T is provided, the % leave-one-out error estimate on A is returned. % % The advantage of using TESTK over TESTC is that it enables leave-one-out % error estimation. However, TESTK is based on just counting errors and % does not weight with testobject priors. % % SEE ALSO % DATASETS, KNNC, KNN_MAP, TESTC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: testk.m,v 1.4 2009/07/22 19:29:41 duin Exp $ function [e,labels] = testk(a,knn,t) prtrace(mfilename); if (nargin < 2) prwarning(2,'number of neighbours K not specified, assuming 1'); knn = 1; end % Calculate the KNN classifier. a = seldat(a); % get labeled objects only w = knnc(a,knn); [m,k] = size(a); nlab = getnlab(a); lablist = getlablist(a); if (nargin <= 2) % Leave-one-out error estimate. d = knn_map([],w); % Posterior probabilities of KNNC(A,KNN). [dmax,J] = max(d,[],2); % Find the maximum. e = nlabcmp(J,nlab)/m; % Calculate error: compare numerical labels. else % Error estimation on tuning set T. [n,kt] = size(t); if (k ~= kt) error('Number of features of A and T do not match.'); end d = knn_map(t,w); % Posterior probabilities of T*KNNC(A,KNN). [dmax,J] = max(d,[],2); % Find the maximum. % Calculate error: compare full labels. e = nlabcmp(getlab(t),lablist(J,:))/n; end labels = lablist(J,:); return
github
jacksky64/imageProcessing-master
userkernel.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/userkernel.m
1,998
utf_8
67ccb0c570bbc7742a528966a9f20de7
%USERKERNEL Construct user defined kernel mapping % % K = USERKERNEL(B,R,FUNC,P1,P2, ...) % K = B*USERKERNEL([],R,FUNC,P1,P2, ...) % W = USERKERNEL([],R,FUNC,P1,P2, ...) % W = R*USERKERNEL([],[],FUNC,P1,P2, ...) % K = B*W % % INPUT % R Dataset, representation set, default B % B Dataset % FUNC String with function name to compute kernels (proximities) by % K = FEVAL(FUNC,B,R,P1,P2, ...) % % OUTPUT % W Trained kernel mapping % K Kernel (proximity) matrix % % DESCRIPTION % The kernel matrix K is computed according to the definition given by the % user supplied function FUNC. The size of K is [SIZE(B,1) SIZE(R,1)] % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function w = userkernel(a,r,kernel,varargin) prtrace(mfilename); if nargin < 3, kernel = []; end if nargin < 2, r = []; end if nargin < 1, a = []; end if isempty(a) & isempty(r) w = mapping(mfilename,'untrained',{[],kernel,varargin{:}}); w = setname(w,'userkernel mapping'); elseif isempty(r) [m,k] = size(a); w = mapping(mfilename,'trained',{a,kernel,varargin},getlab(a),k,m); elseif isempty(a) [m,k] = size(r); w = mapping(mfilename,'trained',{r,kernel,varargin},getlab(r),k,m); elseif ismapping(r) % execution of a*userkernel (trained) u = getdata(r); [r,kernel,pars] = deal(u{:}); w = compute_kernel(kernel,a,r,pars); elseif isdataset(a) % execution w = compute_kernel(kernel,a,r,varargin); end function k = compute_kernel(kernel,a,r,pars) if isempty(kernel) error('No kernel function or kernel mapping supplied') elseif ~exist(kernel) error('kernel function not found') end if isempty(pars) k = feval(kernel,+a,+r); else k = feval(kernel,+a,+r,pars{:}); end k = setdat(a,k); if isdataset(r) k = setfeatlab(k,getlabels(r)); end return
github
jacksky64/imageProcessing-master
ldc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/ldc.m
5,010
utf_8
852b8584fa6dc210f4cb125a86fe288c
%LDC Linear Bayes Normal Classifier (BayesNormal_1) % % [W,R,S,M] = LDC(A,R,S,M) % W = A*LDC([],R,S,M); % % INPUT % A Dataset % R,S Regularization parameters, 0 <= R,S <= 1 % (optional; default: no regularization, i.e. R,S = 0) % M Dimension of subspace structure in covariance matrix (default: K, % all dimensions) % % OUTPUT % W Linear Bayes Normal Classifier mapping % R Value of regularization parameter R as used % S Value of regularization parameter S as used % M Value of regularization parameter M as usedd % % DESCRIPTION % Computation of the linear classifier between the classes of the dataset A % by assuming normal densities with equal covariance matrices. The joint % covariance matrix is the weighted (by a priori probabilities) average of % the class covariance matrices. R and S (0 <= R,S <= 1) are regularization % parameters used for finding the covariance matrix G by: % % G = (1-R-S)*G + R*diag(diag(G)) + S*mean(diag(G))*eye(size(G,1)) % % This covariance matrix is then decomposed as % % G = W*W' + sigma^2 * eye(K) % % where W is a K x M matrix containing the M leading principal components % and sigma^2 is the mean of the K-M smallest eigenvalues. The use of soft labels % is supported. The classification A*W is computed by NORMAL_MAP. % % If R, S or M is NaN the regularisation parameter is optimised by REGOPTC. % The best result are usually obtained by R = 0, S = NaN, M = [], or by % R = 0, S = 0, M = NaN (which is for problems of moderate or low dimensionality % faster). If no regularisation is supplied a pseudo-inverse of the % covariance matrix is used in case it is close to singular. % % Note that A*(KLMS([],N)*NMC) performs a similar operation by first % pre-whitening the data in an N-dimensional space, followed by the % nearest mean classifier. The regularization controlled by N is different % from the above in LDC as it entirely removes small variance directions. % % To some extend LDC is also similar to FISHERC. % % EXAMPLES % See PREX_PLOTC. % a = gendatd; % generate Gaussian distributed data in two classes % w = ldc(a); % compute a linear classifier between the classes % scatterd(a); % make a scatterplot % plotc(w) % plot the classifier % % REFERENCES % 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd edition, % John Wiley and Sons, New York, 2001. % 2. A. Webb, Statistical Pattern Recognition, John Wiley & Sons, New York, 2002. % 3. C. Liu and H. Wechsler, Robust Coding Schemes for Indexing and Retrieval % from Large Face Databases, IEEE Transactions on Image Processing, vol. 9, % no. 1, 2000, 132-136. % % SEE ALSO % MAPPINGS, DATASETS, REGOPTC, NMC, NMSC, LDC, UDC, QUADRC, NORMAL_MAP, FISHERC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: ldc.m,v 1.11 2010/02/08 15:31:48 duin Exp $ function [W,r,s,dim] = ldc(a,r,s,dim) prtrace(mfilename); if (nargin < 4) prwarning(4,'subspace dimensionality M not given, assuming K'); dim = []; end if (nargin < 3) | isempty(s) prwarning(4,'Regularisation parameter S not given, assuming 0.'); s = 0; end if (nargin < 2) | isempty(r) prwarning(4,'Regularisation parameter R not given, assuming 0.'); r = 0; end if (nargin < 1) | (isempty(a)) % No input arguments: W = mapping(mfilename,{r,s,dim}); % return an untrained mapping. elseif any(isnan([r,s,dim])) % optimize regularisation parameters defs = {0,0,[]}; parmin_max = [1e-8,9.9999e-1;1e-8,9.9999e-1;1,size(a,2)]; [W,r,s,dim] = regoptc(a,mfilename,{r,s,dim},defs,[3 2 1],parmin_max,testc([],'soft'),[1 1 0]); else % training islabtype(a,'crisp','soft'); isvaldfile(a,2,2); % at least 2 object per class, 2 classes [m,k,c] = getsize(a); % Calculate mean vectors, priors and the covariance matrix G. %DXD: for large datasets (high dim, many classes) it is impossible %to keep all cov. matrices into memory. We have to loop over the %individual classes: %[U,G] = meancov(a); U = meancov(a); w.mean = +U; w.prior = getprior(a); %G = reshape(sum(reshape(G,k*k,c)*w.prior',2),k,k); [tmpU,G] = meancov(seldat(a,1)); G = w.prior(1)*G; for i=2:c [tmpU,tmpG] = meancov(seldat(a,i)); G = G + w.prior(i)*tmpG; end clear tmpG; % Regularize if (s > 0) | (r > 0) G = (1-r-s)*G + r * diag(diag(G)) + s*mean(diag(G))*eye(size(G,1)); end if (dim < k) dim = min(rank(G)-1,dim); [eigvec,eigval] = preig(G); eigval = diag(eigval); [dummy,ind] = sort(-eigval); % Estimate sigma^2 as avg. eigenvalue outside subspace. sigma2 = mean(eigval(ind(dim+1:end))); % Subspace basis: first DIM eigenvectors * sqrt(eigenvalues). G = eigvec(:,ind(1:dim)) * diag(eigval(ind(1:dim))) * eigvec(:,ind(1:dim))' + ... sigma2 * eye(k); end w.cov = G; W = normal_map(w,getlab(U),k,c); W = setcost(W,a); end W = setname(W,'Bayes-Normal-1'); return
github
jacksky64/imageProcessing-master
gendati.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendati.m
1,667
utf_8
d55740da279d0ca29c66d7e9a9581d96
%GENDATI Create dataset from randomly selected windows in a given image % % A = GENDATI(IMAGE,WSIZE,N,LABEL) % % INPUT % IMAGE - Image of any dimensionality % WSIZE - Vector with size of the window % N - Number windows to be generated % LABEL - Optional string or number with label for all objects % % OUTPUT % A - Dataset of N objects and prod(WSIZE) features % % DESCRIPTION % Windows of the specified size are arbitrarily positioned in the % image, converted to a row vector and stored in the dataset A. % % If specified, all objects have label LABEL. Otherwise they are % unlabeled. % % SEE ALSO % DATASETS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function a = gendati(im,ws,m,label) if nargin < 4, label = []; end if nargin < 3, m = 100; end n = length(ws); imsize = size(im); if length(imsize) ~= n error('Window size should have same number of components as image size') end if any(ws > imsize) error('Window size should not be larger than image size') end we = prod(ws); n = length(ws); window_offset = [0:ws(1)-1]'; for j=2:n wo = window_offset; for i=1:ws(j)-1 wo = wo + prod(imsize(1:j-1)); window_offset = cat(j,window_offset,wo); end end window_offset = window_offset(:)'; N = cell(1,n); for j=1:n R = imsize(j)-ws(j)+1; N(j) = {ceil(rand(m,1)*R)}; end N = sub2ind(imsize,N{:}); a = zeros(m,prod(ws)); for i=1:m a(i,:) = im(N(i)+window_offset); end a = dataset(a); a = setfeatsize(a,ws); if ~isempty(label) a = setlabels(a,label); end
github
jacksky64/imageProcessing-master
im_bdilation.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_bdilation.m
1,266
utf_8
58572ed6d27092bdd0a812440507dfcb
%IM_BDILATION Binary dilation of images stored in a dataset (DIP_Image) % % B = IM_BDILATION(A,N,CONNECTIVITY,EDGE_CONDITION) % B = A*IM_BDILATION([],N,CONNECTIVITY,EDGE_CONDITION) % % INPUT % A Dataset with binary object images dataset (possibly multi-band) % N Number of iterations (default 1) % CONNECTIVITY See BDILATION % EDGE_CONDITION Value of edge, default 0 % % OUTPUT % B Dataset with dilated images % % SEE ALSO % DATASETS, DATAFILES, DIP_IMAGE, BDILATION % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function b = im_bdilation(a,n,connect,edgecon) prtrace(mfilename); if nargin < 4 | isempty(edgecon), edgecon = 0; end if nargin < 3 | isempty(connect), connect = -2; end if nargin < 2 | isempty(n), n = 1; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{n,connect,edgecon}); b = setname(b,'Image dilation'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename,{n,connect,edgecon}); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image a = dip_image(a,'bin'); b = bdilation(a,n,connect,edgecon); end return
github
jacksky64/imageProcessing-master
ridger.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/ridger.m
1,036
utf_8
f3d6e200f6fabf110cd0dc0db2f057b6
%RIDGER Ridge Regression % % W = RIDGER(X,LAMBDA) % % INPUT % X Regression dataset % LAMBDA Regularization parameter (default LAMBDA=1) % % OUTPUT % W Ridge regression mapping % % DESCRIPTION % Perform a ridge regression on dataset X, with the regularization % parameter LAMBDA. % % SEE ALSO % LASSOR, PLOTR, LINEARR % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function y = ridger(x,lambda) if nargin<2 lambda = 1; end if nargin<1 | isempty(x) y = mapping(mfilename,{lambda}); y = setname(y,'Ridge regression'); return end if ~ismapping(lambda) %training [n,d] = size(x); y = gettargets(x); X = +x; beta = prpinv(X'*X + diag(repmat(lambda,d,1)))*X'*(y-mean(y)); W = [mean(y); beta]; % don't forget the offset y = mapping(mfilename,'trained',W,1,d,1); y = setname(y,'Ridge regression'); else % evaluation w = getdata(lambda); [n,d] = size(x); out = [ones(n,1) +x]*w; y = setdat(x,out); end
github
jacksky64/imageProcessing-master
bpxnc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bpxnc.m
1,765
utf_8
7e46cf4aa7c956f4e576e53a00508a32
%BPXNC Back-propagation trained feed-forward neural net classifier % % [W,HIST] = BPXNC (A,UNITS,ITER,W_INI,T,FID) % % INPUT % A Dataset % UNITS Array indicating number of units in each hidden layer (default: [5]) % ITER Number of iterations to train (default: inf) % W_INI Weight initialisation network mapping (default: [], meaning % initialisation by Matlab's neural network toolbox) % T Tuning set (default: [], meaning use A) % FID File descriptor to report progress to (default: 0, no report) % % OUTPUT % W Trained feed-forward neural network mapping % HIST Progress report (see below) % % DESCRIPTION % A feed-forward neural network classifier with length(N) hidden layers with % N(I) units in layer I is computed for the dataset A. Training is stopped % after ITER epochs (at least 50) or if the iteration number exceeds twice % that of the best classification result. This is measured by the labeled % tuning set T. If no tuning set is supplied A is used. W_INI is used, if % given, as network initialisation. Use [] if the standard Matlab % initialisation is desired. Progress is reported in file FID (default 0). % % The entire training sequence is returned in HIST (number of epochs, % classification error on A, classification error on T, MSE on A, MSE on T). % % Uses the Mathwork's Neural Network toolbox. % % SEE ALSO % MAPPINGS, DATASETS, LMNC, NEURC, RNNC, RBNC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: bpxnc.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function [w,hist] = bpxnc(varargin) prtrace(mfilename); [w,hist] = ffnc(mfilename,varargin{:}); return
github
jacksky64/imageProcessing-master
edicon.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/edicon.m
5,932
utf_8
feac26635d4fbb0b972e4435a7e6bf14
% EDICON Multi-edit and condense a training set % % J = EDICON(D,NSETS,NITERS,NTRIES) % % INPUT % D Distance matrix dataset % NSETS Number of subsets for editing, or [] for no editing (default: 3) % NITERS Number of iterations for editing (default: 5) % NTRIES Number of tries for condensing, or [] for no condensing (dflt: 10) % % OUTPUT % J Indices of retained samples % % DESCRIPTION % Returns the set of objects J such that the nearest neigbour gives zero error % on the remaining objects. If MODE = 0, multi-edit the dataset represented by % distance matrix D first. D can be computed from a dataset A by A*proxm(A). % % REFERENCES % Devijver, P. and Kittler, J. "Pattern recognition", Prentice-Hall, 1982. % % SEE ALSO % DATASET, KNNC, PROXM % Copyright: E. Pekalska and D. de Ridder, {E.Pekalska,D.deRidder}@ewi.tudelft.nl % Faculty of Electrical Engineering, Mathematics and Computer Science % Delft University of Technology, Mekelweg 4, 2628 CD Delft, The Netherlands function J = edicon (D,no_subsets,max_iter,no_tries) if (nargin < 4 | isempty(no_tries)) prwarning(4,'number of tries for condensing not specified, assuming 10'); no_tries = 10; end; if (nargin < 3 | isempty(max_iter)) prwarning(4,'number of iterations for editing not specified, assuming 5'); max_iter = 5; end; if (nargin < 2 | isempty(no_subsets)) prwarning(4,'number of subsets for editing not specified, assuming 3'); no_subsets = 5; end; % Extract dataset information. nlab = getnlab(D); lablist = getlablist(D); [m,k,c] = getsize(D); p = getprior(D); if (~isdataset(D) | (m ~= k)) error('require a square distance matrix dataset'); end J = 1:m; % Initialise index array. % If requested, apply the multi-edit algorithm. if (~isempty(no_subsets)) iter = 1; while (iter <= max_iter) % 1. Create NO_SUBSETS distinct subsets out of the sample indices % remaining in J. Store the subset indices in subset_ind{.}. % Note: this is slightly more complicated than strictly % necessary, to enforce that each class is represented equally % in each subset. m = length(J); J = J(randperm(m)); subset_size = floor(m/no_subsets); % Find the MC(J) indices of samples belonging to class J in CLASS_IND{J}. % Also create a random permutation for class J. for j = 1:c class_ind{j} = find(nlab(J)==j); mc(j) = length(class_ind{j}); perm{j} = randperm(mc(j)); end; % Distribute the samples over the subsets, per class. for i = 1:no_subsets subset_ind{i} = []; for j = 1:c num = min(floor(mc(j)/no_subsets),length(class_ind{j})); subset_ind{i} = [subset_ind{i}; class_ind{j}(1:num)]; class_ind{j} = class_ind{j}(num+1:end); end; perm_subset_ind{i} = J(subset_ind{i}); end; % 2. In turn, classify each subset I using 1-NN on subset I+1. drop = []; for i = 1:no_subsets L1 = perm_subset_ind{i}; L2 = perm_subset_ind{mod(i,no_subsets)+1}; if (length(L2)>1) [dummy,nearest] = min(D(L2,L1)); else nearest = 1; end; drop = [drop; subset_ind{i}(find(nlab(L1)~=nlab(L2(nearest))))]; end; % 3. Discard incorrectly classified samples from J. if (isempty(drop)) iter = iter + 1; else J(drop) = []; iter = 0; end; end; D = D(J,J); end; % Condense. if (~isempty(no_tries)) % Extract dataset information. nlab = getnlab(D); lablist = getlablist(D); [m,k,c] = getsize(D); p = getprior(D); D = +D; % The whole procedure starts from a random object and continues to add % objects, so it is not optimal. Therefore it is repeated NO_TRIES times % and the smallest set found is returned. K = zeros(m,no_tries); storesz = zeros(1,no_tries); for o = 1:no_tries % Start with 1 sample index in STORE, the others in GRABBAG. p = randperm(m); store = p(1); grabbag = p(2:m); % While there are changes... transfer = 0; while (~transfer) & (~isempty(grabbag)) storelab = nlab(store); grabbaglab = nlab(grabbag); new_grabbag = []; % For all samples in GRABBAG... transfer = 0; for k = 1:length(grabbag) % ... find the nearest sample in STORE... [dummy,z] = min(D(grabbag(k),store)); % ... if it has a different label, move it to STORE. if (storelab(z) ~= grabbaglab(k)) store = [store; grabbag(k)]; storelab = [storelab; grabbaglab(k)]; transfer = 1; else new_grabbag = [new_grabbag; grabbag(k)]; end; end; grabbag = new_grabbag; end % Remember the STORE and its size for this repetition. storesz(o) = length(store); K(1:storesz(o),o) = store; end % Take the STORE with minimal size. [minsz,minszind] = min(storesz); J = J(K(1:minsz,minszind)); end; return
github
jacksky64/imageProcessing-master
isstacked.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isstacked.m
796
utf_8
eb8484829ee9efe2498d3fae02ee6066
%ISSTACKED Test on stacked mapping % % N = ISSTACKED(W) % ISSTACKED(W) % % INPUT % W Mapping % % OUTPUT % N Scalar, 1 if W is a stacked mapping, 0 otherwise % % DESCRIPTION % Returns 1 for stacked mappings. If no output is requested, false outputs % are turned into errors. This may be used for assertion. % % SEE ALSO % ISMAPPING, ISPARALLEL % $Id: isstacked.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function n = isstacked(w) prtrace(mfilename); if (isa(w,'mapping')) & (strcmp(w.mapping_file,'stacked') | ... strcmp(w.mapping_file,'dyadicm')) n = 1; else n = 0; end % Generate an error if the input is not a stacked mapping and no output % is requested (assertion). if (nargout == 0) & (n == 0) error([newline '---- Stacked mapping expected -----']) end return
github
jacksky64/imageProcessing-master
gendat.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendat.m
4,567
utf_8
741d390eee21a0c39a0f761c86e04757
%GENDAT Random sampling of datasets for training and testing % % [A,B,IA,IB] = GENDAT(X,N) % A = X*GENDAT([],N) % [A,B,IA,IB] = GENDAT(X) % [A,B,IA,IB] = GENDAT(X,ALF) % A = X*GENDAT([],ALF) % % INPUT % X Dataset % N,ALF Number/fraction of objects to be selected % (optional; default: bootstrapping) % % OUTPUT % A,B Datasets % IA,IB Original indices from the dataset X % % DESCRIPTION % Generation of N objects from dataset X. They are stored in dataset A, % the remaining objects in dataset B. IA and IB are the indices of the % objects selected from X for A and B. The random object generation follows % the class prior probabilities. So is the prior probability of a class is % PA, then in expectation PA*N objects are selected from that class. If N % is large or if one of the classes has too few objects in A, the number of % generated objects might be less than N. % % If N is a vector of sizes, exactly N(i) objects are generated for class i. % Classes are ordered using RENUMLAB(GETLAB(X)). % % If the function is called without specifying N, the data set X is % bootstrapped and stored in A. Not selected samples are stored in B. % % ALF should be a scalar < 1. For each class a fraction ALF of the objects % is selected for A and the not selected objects are stored in B. % % If X is a cell array of datasets the command is executed for each % dataset separately. Results are stored in cell arrays. For each dataset % the random seed is reset, resulting in aligned sets for the generated % datasets if the sets in X were aligned. % % EXAMPLES % See PREX_PLOTC. % % SEE ALSO % DATASETS, GENSUBSETS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: gendat.m,v 1.7 2010/06/01 08:48:55 duin Exp $ function [A,B,IA,IB] = gendat(X,N); prtrace(mfilename); if (nargin < 2), N = []; end if (nargin < 1 | isempty(X)) A = mapping(mfilename,'fixed',N); A = setname(A,'Data sampling'); return end % If an input is a cell array of datasets, apply this procedure % to the individual datasets. if (iscell(X)) A = cell(size(X)); B = cell(size(X)); IA = cell(size(X)); IB = cell(size(X)); seed = rand('seed'); for j=1:length(X(:)) rand('seed',seed); [A{j},B{j},IA{j},IB{j}] = feval(mfilename,X{j},N); end return; end % When required, get the right number of objects from the given % fraction ALF. if ~isdatafile(X), X = dataset(X); end X = setlablist(X); % remove empty classes first [m,k,c] = getsize(X); % we need at least one class below: unlabeled = 0; if c==0, X=cdats(X,1); c=1; unlabeled = 1; % we need to correct for labeling at the end end R = classsizes(X); if ~isempty(N) & length(N) ~= 1 & length(N) ~= c error('Data size should be scalar or a vector matching the number of classes') end if ~islabtype(X,'crisp') if numel(N) > 1 prwarning(1,'Specification of numbers of objects per class not possible for given label type') N = sum(N); end if N < 1, N = ceil(N*m); end end if (nargin == 2) & all(N < 1) & islabtype(X,'crisp') %DXD it should also be possible to have a fraction for each of the %classes, I think... if length(N)==1 N = ceil(N*R); else N = ceil(N(:).*R(:)); end end % Depending if N (or ALF) is given, the objects are created using % subsampling or bootstrapping. IA = []; if (nargin < 2) | (isempty(N)) % Bootstrap for i=1:c J = findnlab(X,i); K = ceil(rand(R(i),1)*R(i)); IA = [IA; J(K)]; end else % Subsampling if ~islabtype(X,'crisp') K = randperm(m); if (N > m) %DXD: I would like to have just a warning: %error('More objects requested than available.') prwarning(4,'More objects requested than available.') N = m; end IA = K(1:N); else %p = X.prior; % avoid warning if isempty(X,'prior') p = classsizes(X); p = p/sum(p); else p = getprior(X); end %p = getprior(X); N = genclass(N,p); for i=1:c J = findnlab(X,i); K = randperm(R(i)); if (N(i) > R(i)) %DXD: I would like to have just a warning: %error('More objects requested than available.') prwarning(1,'More objects requested than available in class %d.',i) N(i) = R(i); end IA = [IA; J(K(1:N(i)))]; end end end % Finally, extract the datasets: IB = [1:m]'; IB(IA) = []; if unlabeled X = setlabels(X,[]); % reset unlabeling end A = X(IA,:); B = X(IB,:); return;
github
jacksky64/imageProcessing-master
pcldc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/pcldc.m
1,556
utf_8
6795cecd9c8f254cdc84b6cf74d6ece4
%PCLDC Linear classifier using PC expansion on the joint data. % % W = PCLDC(A,N) % W = PCLDC(A,ALF) % % INPUT % A Dataset % N Number of eigenvectors % ALF Total explained variance (default: ALF = 0.9) % % OUTPUT % W Mapping % % DESCRIPTION % Finds the linear discriminant function W for the dataset A % computing the LDC on a projection of the data on the first N % eigenvectors of the total dataset (Principle Component Analysis). % % When ALF is supplied the number of eigenvalues is chosen such that at % least a part ALF of the total variance is explained. % % If N (ALF) is NaN it is optimised by REGOPTC. % % SEE ALSO % MAPPINGS, DATASETS, KLLDC, KLM, FISHERM, REGOPTC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: pcldc.m,v 1.4 2007/06/13 21:59:42 duin Exp $ function W = pcldc(a,n) prtrace(mfilename); if nargin < 2, n = []; end if nargin == 0 | isempty(a) W = mapping('pcldc',{n}); elseif isnan(n) % optimize regularisation parameter defs = {1}; parmin_max = [1,size(a,2)]; W = regoptc(a,mfilename,{n},defs,[1],parmin_max,testc([],'soft'),0); else islabtype(a,'crisp','soft'); isvaldfile(a,2,2); % at least 2 object per class, 2 classes a = testdatasize(a,'features'); a = setprior(a,getprior(a)); % Make a sequential classifier combining PCA and LDC: v = pca(a,n); W = v*ldc(a*v); W = setcost(W,a); end W = setname(W,'PC Bayes-Normal-1'); return
github
jacksky64/imageProcessing-master
im_maxf.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_maxf.m
1,134
utf_8
2f834256ee1f68b17045bb73babd63ff
%IM_MAXF Maximum filter of images stored in a dataset (DIP_Image) % % B = IM_MAXF(A,SIZE,SHAPE) % B = A*IM_MAXF([],SIZE,SHAPE) % % INPUT % A Dataset with object images dataset (possibly multi-band) % SIZE Filter width in pixels, default SIZE = 7 % SHAPE String with shape:'rectangular', 'elliptic', 'diamond' % Default: elliptic % % OUTPUT % B Dataset with filtered images % % SEE ALSO % DATASETS, DATAFILES, DIP_IMAGE, MINF % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_maxf(a,size,shape) prtrace(mfilename); if nargin < 3 | isempty(shape), shape = 'elliptic'; end if nargin < 2 | isempty(size), size = 7; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{size,shape}); b = setname(b,'Maximum filter'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename,{size,shape}); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image a = 1.0*dip_image(a); b = maxf(a,size,shape); end return
github
jacksky64/imageProcessing-master
prdownload.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prdownload.m
2,080
utf_8
b8843c8b48d744580c216fc478b612d3
%PRDOWNLOAD Download well defined data and toolboxes % % STATUS = PRDOWNLOAD(URL,DIRNAME) % % INPUT % URL String containing URL of file to be downloaded % DIRNAME Final directory for download, created if necessary % README Name of possible readme-file to be preserved % % DESCRIPTION % The URL will be downloaded in directory DIRNAME (to be created if % needed). The resulting file will be uncompressed in case of a zip-, gz- % or tar-file. % % The main purpose of this routine is to download missing datafiles or % datasets from PRDATAFILES and PRDATASETS. % % SEE ALSO % PRDATASETS, PRDATAFILES % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [status,dirname] = prdownload(url,dirname) % create target directory if needed if exist(dirname,'dir') ~= 7 success = mkdir(dirname); if ~success maindir = input(['It is not possible to create a directory here.' newline ... 'Please give another location: '],'s'); dirname = fullfile(maindir,dirname); mkdir(dirname); end end % download [dd,ff,xx]= fileparts(url); filename = [ff xx]; disp(['Downloading ' filename ' ....']) rfilename = fullfile(dirname,filename); if ~usejava('jvm') & isunix [stat,s] = unix(['wget -q -O ' rfilename [' '] url]); status = (stat == 0); else [f,status] = urlwrite(url,rfilename); end if status == 0 error('Server unreachable or file not found') end % assume file is created, uncompress if needed % delete compressed file if strcmp(xx,'.zip') disp('Decompression ....') if ~usejava('jvm') & isunix [stat,s] = unix(['unzip ' rfilename ' -d ' dirname]); else unzip(rfilename,dirname); end delete(rfilename); elseif strcmp(xx,'.gz') disp('Decompression ....') gunzip(filename,dirname); delete(filename); elseif strcmp(xx,'.tar')| strcmp(xx,'.tgz') | strcmp(xx,'.tar.gz') disp('Decompression ....') untar(filename,dirname); delete(filename); end disp('Ready')
github
jacksky64/imageProcessing-master
votec.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/votec.m
1,705
utf_8
ecfba23be0f9a5b45b42b9d0caabaae5
%VOTEC Voting combining classifier % % W = VOTEC(V) % W = V*VOTEC % % INPUT % V Set of classifiers % % OUTPUT % W Voting combiner % % DESCRIPTION % If V = [V1,V2,V3,...] is a stacked set of classifiers trained for the % same classes, W is the voting combiner: it selects the class with the % highest vote of the base classifiers. This might also be used as % A*[V1,V2,V3]*VOTEC in which A is a dataset to be classified. % % The direct classifier outputs D = B*W for a test set B are posterior % probability estimates. D(i,j) = (v+1) / (n+c), in which v is the number % of votes object i receives for the j-th class. n is the total number of % classifiers, c the total number of classes. % % The base classifiers may be combined in a stacked way (operating in the % same feature space) by V = [V1,V2,V3, ... ] or in a parallel way % (operating in different feature spaces) by V = [V1;V2;V3; ... ] % % EXAMPLES % PREX_COMBINING % % SEE ALSO % MAPPINGS, DATASETS, PRODC, MAXC, MINC, % MEDIANC, MEANC, AVERAGEC, STACKED, PARALLEL % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: votec.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function w = votec(p1) prtrace(mfilename); type = 'vote'; % define the operation processed by FIXEDCC. name = 'Voting combiner'; % define the name of the combiner. % this is the general procedure for all possible % calls of fixed combiners handled by FIXEDCC if nargin == 0 w = mapping('fixedcc','combiner',{[],type,name}); else w = fixedcc(p1,[],type,name); end if isa(w,'mapping') w = setname(w,name); end return
github
jacksky64/imageProcessing-master
dataim.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/dataim.m
2,017
utf_8
114c84e258c8243a70363e9e342145a0
%DATAIM Image operation on dataset images % % B = DATAIM(A,'IMAGE_COMMAND',PAR1,PAR2,....) % % INPUT % A Dataset containing images % IMAGE_COMMAND Function name % PAR1, ... Optional parameters to IMAGE_COMMAND % % OUTPUT % B Dataset containing images processed by IMAGE_COMMAND % % DESCRIPTION % For each image stored in A (as either feature or object), performs % % IMAGE_OUT = IMAGE_COMMAND(IMAGE_IN,PAR1,PAR2,....) % % and stores the result in dataset B. % % EXAMPLES % B = DATAIM (A,'CONV2',[-1 0 1; -1 0 1; -1 0 1],'same'); % Performs a convolution with a horizontal gradient filter (see CONV2). % % SEE ALSO % DATASETS, IM2OBJ, DATA2IM, IM2FEAT, DATGAUSS, DATFILT % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: dataim.m,v 1.4 2007/03/22 08:53:12 duin Exp $ function b = dataim (a,command,varargin) prtrace(mfilename); isdataim(a); % Assert that A contains images. im = data2im(a); % Convert A to array of images. [m,k] = size(a); [height,width,n_im] = size(im); % Perform command on first image to check whether image size stays equal % (for feature images; the number of objects can change without problems). first = feval(command,im(:,:,1),varargin{:}); first = double(first); % for DipLib users [newheight,newwidth] = size(first); if (isfeatim(a)) & ((newheight ~= height) | (newwidth ~= width)) error('image size is not allowed to change') end % Process the remaining images. out = zeros(newheight,newwidth,n_im); out(:,:,1) = first; for i = 2:n_im out(:,:,i) = double(feval(command,im(:,:,i),varargin{:})); end % Convert the image array back into a dataset. if (isfeatim(a)) b = setdata(a,im2feat(out),getfeatlab(a)); %images are stored in columns else b = setdata(a,im2obj(out)); %images are stored in rows b = setfeatsize(b,size(first)); end return
github
jacksky64/imageProcessing-master
hclust.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/hclust.m
3,650
utf_8
2c71eb6b426dcac1014b6a0cfa5230c7
%HCLUST hierarchical clustering % % [LABELS, DENDROGRAM] = HCLUST(D,TYPE,K) % DENDROGRAM = HCLUST(D,TYPE) % % INPUT % D dissimilarity matrix % TYPE string name of clustering criterion (optional) % 's' or 'single' : single linkage (default_ % 'c' or 'complete' : complete linkage % 'a' or 'average' : average linkage (weighted over cluster sizes) % K number of clusters (optional) % % OUTPUT % LABELS vector with labels % DENDROGRAM matrix with dendrogram % % DESCRIPTION % Computation of cluster labels and a dendrogram between the clusters for % objects with a given distance matrix D. K is the desired number of % clusters. The dendrogram is a 2*K matrix. The first row yields all % cluster sizes. The second row is the cluster level on which the set of % clusters starting at that position is merged with the set of clusters % just above it in the dendrogram. A dendrogram may be plotted by PLOTDG. % % DENDROGRAM = HCLUST(D,TYPE) % % As in this case no clustering level is supplied, just the entire % dendrogram is returned. % % EXAMPLE % a = gendats([25 25],20,5); % 50 points in 20-dimensional feature space % d = sqrt(distm(a)); % Euclidean distances % dendg = hclust(d,'complete'); % dendrogram % plotdg(dendg) % lab = hclust(d,'complete',2); % labels % confmat(lab,getlabels(a)); % confusion matrix % % SEE ALSO % PLOTDG, KMEANS, KCENTRES, MODESEEK, EMCLUST % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: hclust.m,v 1.3 2008/02/14 11:54:43 duin Exp $ function [labels, dendrogram] = hclust(D,type,k) prtrace(mfilename); if nargin < 3, k = []; end if nargin < 2, type = 's'; end [m,m1] = size(D); if m ~= m1 error('Input matrix should be square') end D = D + diag(inf*ones(1,m)); % set diagonal at infinity. W = [1:m+1]; % starting points of clusters in linear object set. V = [1:m+2]; % positions of objects in final linear object set. F = inf * ones(1,m+1); % distance of next cluster to previous cluster to be stored at first point of second cluster Z = ones(1,m); % number of samples in a cluster (only for average linkage) for n = 1:m-1 % find minimum distance D(i,j) i<j [di,I] = min(D); [dj,j] = min(di); i = I(j); if i > j, j1 = j; j = i; i = j1; end % combine clusters i,j switch type case {'s','single'} D(i,:) = min(D(i,:),D(j,:)); case {'c','complete'} D(i,:) = max(D(i,:),D(j,:)); case {'a','average'} D(i,:) = (Z(i)*D(i,:) + Z(j)*D(j,:))/(Z(i)+Z(j)); Z(i:j-1) = [Z(i)+Z(j),Z(i+1:j-1)]; Z(j) = []; otherwise error('Unknown clustertype desired') end D(:,i) = D(i,:)'; D(i,i) = inf; D(j,:) = []; D(:,j) = []; % store cluster distance F(V(j)) = dj; % move second cluster in linear ordering right after first cluster IV = [1:V(i+1)-1,V(j):V(j+1)-1,V(i+1):V(j)-1,V(j+1):m+1]; W = W(IV); F = F(IV); % keep track of object positions and cluster distances V = [V(1:i),V(i+1:j) + V(j+1) - V(j),V(j+2:m-n+3)]; end if ~isempty(k) | nargout == 2 if isempty(k), k = m; end labels = zeros(1,m); [S,J] = sort(-F); % find cluster level I = sort(J(1:k+1)); % find all indices where cluster starts for i = 1:k % find for all objects cluster labels labels(W(I(i):I(i+1)-1)) = i * ones(1,I(i+1)-I(i)); end % compute dendrogram dendrogram = [I(2:k+1) - I(1:k); F(I(1:k))]; labels = labels'; else labels = [W(1:m);F(1:m)]; % full dendrogram end return
github
jacksky64/imageProcessing-master
feat2obj.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/feat2obj.m
420
utf_8
40b24bd841ad312efce9f97e06480b2e
%FEAT2OBJ Transform feature images to object images in dataset % % B = FEAT2OBJ(A) % % INPUT % A Dataset with object images, possible with multiple bands % % OUTPUT % B Dataset with features images % % SEE ALSO % DATASETS, IM2OBJ, IM2FEAT, DATA2IM, OBJ2FEAT function b = feat2obj(a) prtrace(mfilename); isdataset(a) isfeatim(a); im = data2im(a); b = im2feat(im);
github
jacksky64/imageProcessing-master
plotd.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plotd.m
427
utf_8
8dc4baf0dd8f08102e21faafd7850f50
%PLOTD Plot classifiers, outdated, use PLOTC instead % $Id: plotd.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function handle = plotd(varargin) prtrace(mfilename); global PLOTD_REPLACED_BY_PLOTC if isempty(PLOTD_REPLACED_BY_PLOTC) disp([newline 'PLOTD has been replaced by PLOTC, please use it']) PLOTD_REPLACED_BY_PLOTC = 1; end if nargout > 0 handle = plotc(varargin{:}); else plotc(varargin{:}); end return
github
jacksky64/imageProcessing-master
prwarning.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prwarning.m
1,697
utf_8
c0d8edc3c3037c62d44ea9d6c3f46f96
%PRWARNING Show PRTools warning % % PRWARNING(LEVEL,FORMAT,...) % % Shows the message (given as FORMAT and a variable number of arguments), % if the current PRWARNING level is >= LEVEL. Output is written to standard % error ouput (FID = 2). % % PRWARNING(LEVEL) - Set the current PRWARNING level % % Set the PRWARNING level to LEVEL. The default level is 1. % The levels currently in use are: % 0 no warnings % 1 severe warnings (default) % 2 warnings % 3 light warnings % 10 general messages % 20 program flow messages % 30 debugging messages % % PRWARNING OFF - Same as PRWARNING(0) % PRWARNING ON - Same as PRWARNING(1) % PRWARNING - Same as PRWARNING(1) % Copyright: D. de Ridder, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: prwarning.m,v 1.5 2007/11/30 16:29:49 duin Exp $ function lev = prwarning (level, varargin) persistent PRWARNINGGLOBAL; if (isempty (PRWARNINGGLOBAL)) PRWARNINGGLOBAL = 1; end if (nargin == 0) & (nargout == 0) % Set warning level to default PRWARNINGGLOBAL = 1; elseif (nargin == 1) % Set warning level if isstr(level) & strcmp(level,'off') level = 0; elseif isstr(level) & strcmp(level,'on') level = 1; end PRWARNINGGLOBAL = level; elseif nargin > 0 if (level <= PRWARNINGGLOBAL) [st,i] = dbstack; % Find and display calling function (if any) if (length(st) > 1) caller = st(2).name; [paths,name] = fileparts(caller); fprintf (2, 'PR_Warning: %s: ', name); end; fprintf (2, varargin{:}); fprintf (2, '\n'); end end if nargout > 0 lev = PRWARNINGGLOBAL; end return
github
jacksky64/imageProcessing-master
is_scalar.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/is_scalar.m
408
utf_8
6714336395873cf354df615113a965da
%IS_SCALAR Test on scalar (size = [1,1]) % % N = IS_SCALAR(P); % % INPUT % P Input argument % % OUTPUT % N 1/0 if A is/isn't scalar % % DESCRIPTION % The function IS_SCALAR tests if P is scalar. function n = is_scalar(p) prtrace(mfilename); n = all(size(p) == ones(1,length(size(p)))); if (nargout == 0) & (n == 0) error([newline 'Scalar variable expected.']) end return;
github
jacksky64/imageProcessing-master
compute_kernel.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/compute_kernel.m
502
utf_8
e17f2af48790f6d9308283c48906dab5
function K = compute_kernel(a,s,kernel) % compute a kernel matrix for the objects a w.r.t. the support objects s % given a kernel description if isstr(kernel) % routine supplied to compute kernel K = feval(kernel,a,s); elseif iscell(kernel) K = feval(kernel{1},a,s,kernel{2:end}); elseif ismapping(kernel) K = a*map(s,kernel); elseif kernel == 0 % we have already a kernel K = a; else error('Do not know how to compute kernel matrix') end K = +K; return
github
jacksky64/imageProcessing-master
im_moments.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_moments.m
10,678
utf_8
43751390d5cb45c351dcb6db219ffaa6
%IM_MOMENTS PRTools routine for computing central moments of object images % % M = IM_MOMENTS(A,TYPE,MOMENTS) % M = A*IM_MOMENTS([],TYPE,MOMENTS) % % INPUT % A Dataset with object images dataset (possibly multi-band) % TYPE Desired type of moments % MOMENTS Desired moments % % OUTPUT % M Dataset with moments replacing images (poosibly multi-band) % % DESCRIPTION % Computes for all images in A a (1*N) vector M moments as defined by TYPE % and MOMENTS. The following types are supported: % % TYPE = 'none' Standard moments as specified in the Nx2 array MOMENTS. % Moments are computed with respect to the image center. % This is the default for TYPE. % Default MOMENTS = [1 0; 0 1]; % TYPE = 'central' Central moments as specified in the Nx2 array MOMENTS. % Moments are computed with respect to the image mean % Default MOMENTS = [2 0; 1 1; 0 2], which computes % the variance in the x-direction (horizontal), the % covariance between x and y and the variance in the % y-direction (vertical). % TYPE = 'scaled' Scale-invariant moments as specified in the Nx2 array % MOMENTS. Default MOMENTS = [2 0; 1 1; 0 2]. % After: M. Sonka et al., % Image processing, analysis and machine vision. % TYPE = 'hu' Calculates 7 moments of Hu, invariant to translation, % rotation and scale. % After: M. Sonka et al., % Image processing, analysis and machine vision. % TYPE = 'zer' Calculates the Zernike moments up to the order as % specified in the scalar MOMENTS (1 <= MOMENTS <= 12). % MOMENTS = 12 generates in total 47 moments. % After: A. Khotanzad and Y.H. Hong, Invariant image % recognition by Zernike moments, IEEE-PAMI, vol. 12, % no. 5, 1990, 489-497. % % SEE ALSO % DATASETS, DATAFILES % Copyright: D. de Ridder, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_moments(a,type,mom) prtrace(mfilename); if nargin < 3, mom = []; end if nargin < 2 | isempty(type), type = 'none'; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{type,mom}); b = setname(b,'Image moments'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename,{type,mom}); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image if isa(a,'dip_image'), a = double(a); end switch type case {'none'} if isempty(mom) mom = [1 0; 0 1]; end b = moments(a,mom(:,1),mom(:,2),0,0); case {'central'} if isempty(mom) mom = [2 0; 1 1; 0 2]; end b = moments(a,mom(:,1),mom(:,2),1,0); case {'scaled'} if isempty(mom) mom = [2 0; 1 1; 0 2]; end b = moments(a,mom(:,1)',mom(:,2)',1,1); case {'hu' 'Hu'} b = hu_moments(a); case {'zer' 'zernike' 'Zernike'} if isempty(mom) mom = 12; end b = zernike_moments(a,mom); otherwise error('Moments should be of type none, central, scaled, hu or zer') end else error('Illegal datatype for input') end return % M = MOMENTS (IM, P, Q, CENTRAL, SCALED) % % Calculates moments of order (P+Q) (can be arrays of indentical length) % on image IM. If CENTRAL is set to 1 (default: 0), returns translation- % invariant moments; if SCALED is set to 1 (default: 0), returns scale- % invariant moments. % % After: M. Sonka et al., Image processing, analysis and machine vision. function m = moments (im,p,q,central,scaled) if (nargin < 5), scaled = 0; end; if (nargin < 4), central = 0; end; if (nargin < 3) error ('Insufficient number of parameters.'); end; if (length(p) ~= length(q)) error ('Arrays P and Q should have equal length.'); end; if (scaled & ~central) error ('Scale-invariant moments should always be central.'); end; % xx, yy are grids with co-ordinates [xs,ys] = size(im); [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2); if (central) % Calculate zeroth and first order moments m00 = sum(sum(im)); m10 = sum(sum(im.*xx)); m01 = sum(sum(im.*yy)); % This gives the center of gravity xc = m10/m00; yc = m01/m00; % Subtract this from the grids to center the object xx = xx - xc; yy = yy - yc; end; % Calculate moment(s) (p,q). for i = 1:length(p) m(i) = sum(sum((xx.^p(i)).*(yy.^q(i)).*im)); end; if (scaled) c = 1 + (p+q)/2; % m00 should be known, as scaled moments are always central m = m ./ (m00.^c); end; return; % M = HU_MOMENTS (IM) % % Calculates 7 moments of Hu on image IM, invariant to translation, % rotation and scale. % % After: M. Sonka et al., Image processing, analysis and machine vision. function m = hu_moments (im) p = [ 1 0 2 1 2 0 3 ]; q = [ 1 2 0 2 1 3 0 ]; n = moments(im,p,q,1,1); m(1) = n(2) + n(3); m(2) = (n(3) - n(2))^2 + 4*n(1)^2; m(3) = (n(7) - 3*n(4))^2 + (3*n(5) - n(6))^2; m(4) = (n(7) + n(4))^2 + ( n(5) + n(6))^2; m(5) = ( n(7) - 3*n(4)) * (n(7) + n(4)) * ... ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) + ... (3*n(5) - n(6)) * (n(5) + n(6)) * ... (3*(n(7) + n(4))^2 - (n(5) + n(6))^2); m(6) = (n(3) - n(2)) * ((n(7) + n(4))^2 - (n(5) + n(6))^2) + ... 4*n(1) * (n(7)+n(4)) * (n(5)+n(6)); m(7) = (3*n(5) - n(6)) * (n(7) + n(4)) * ... ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) - ... ( n(7) - 3*n(4)) * (n(5) + n(6)) * ... (3*(n(7) + n(4))^2 - (n(5) + n(6))^2); return; % M = ZERNIKE_MOMENTS (IM, ORDER) % % Calculates Zernike moments up to and including ORDER (<= 12) on image IM. % Default: ORDER = 12. function m = zernike_moments (im, order) if (nargin < 2), order = 12; end; if (order < 1 | order > 12), error ('order should be 1..12'); end; % xx, yy are grids with co-ordinates [xs,ys] = size(im); [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2); % Calculate center of mass and distance of any pixel to it m = moments (im,[0 1 0],[0 0 1],0,0); xc = m(2)/m(1); yc = m(3)/m(1); xx = xx - xc; yy = yy - yc; len = sqrt(xx.^2+yy.^2); max_len = max(max(len)); % Map pixels to unit circle; prevent divide by zero. rho = len/max_len; rho_tmp = rho; rho_tmp(find(rho==0)) = 1; theta = acos((xx/max_len)./rho_tmp); % Flip angle for pixels above center of mass yneg = length(find(yy(:,1)<0)); theta(:,1:yneg) = 2*pi - theta(:,1:yneg); % Calculate coefficients c = zeros(order,order); s = zeros(order,order); i = 1; for n = 2:order for l = n:-2:0 r = polynomial (n,l,rho); c = sum(sum(r.*cos(l*theta)))*((n+1)/(pi*max_len^2)); s = sum(sum(r.*sin(l*theta)))*((n+1)/(pi*max_len^2)); m(i) = sqrt(c^2+s^2); i = i + 1; end; end; return function p = polynomial (n,l,rho) switch (n) case 2, switch (l) case 0, p = 2*(rho.^2)-1; case 2, p = (rho.^2); end; case 3, switch (l) case 1, p = 3*(rho.^3)-2*rho; case 3, p = (rho.^3); end; case 4, switch (l) case 0, p = 6*(rho.^4)-6*(rho.^2)+1; case 2, p = 4*(rho.^4)-3*(rho.^2); case 4, p = (rho.^4); end; case 5, switch (l) case 1, p = 10*(rho.^5)-12*(rho.^3)+3*rho; case 3, p = 5*(rho.^5)- 4*(rho.^3); case 5, p = (rho.^5); end; case 6, switch (l) case 0, p = 20*(rho.^6)-30*(rho.^4)+12*(rho.^2)-1; case 2, p = 15*(rho.^6)-20*(rho.^4)+ 6*(rho.^2); case 4, p = 6*(rho.^6)- 5*(rho.^4); case 6, p = (rho.^6); end; case 7, switch (l) case 1, p = 35*(rho.^7)-60*(rho.^5)+30*(rho.^3)-4*rho; case 3, p = 21*(rho.^7)-30*(rho.^5)+10*(rho.^3); case 5, p = 7*(rho.^7)- 6*(rho.^5); case 7, p = (rho.^7); end; case 8, switch (l) case 0, p = 70*(rho.^8)-140*(rho.^6)+90*(rho.^4)-20*(rho.^2)+1; case 2, p = 56*(rho.^8)-105*(rho.^6)+60*(rho.^4)-10*(rho.^2); case 4, p = 28*(rho.^8)- 42*(rho.^6)+15*(rho.^4); case 6, p = 8*(rho.^8)- 7*(rho.^6); case 8, p = (rho.^8); end; case 9, switch (l) case 1, p = 126*(rho.^9)-280*(rho.^7)+210*(rho.^5)-60*(rho.^3)+5*rho; case 3, p = 84*(rho.^9)-168*(rho.^7)+105*(rho.^5)-20*(rho.^3); case 5, p = 36*(rho.^9)- 56*(rho.^7)+ 21*(rho.^5); case 7, p = 9*(rho.^9)- 8*(rho.^7); case 9, p = (rho.^9); end; case 10, switch (l) case 0, p = 252*(rho.^10)-630*(rho.^8)+560*(rho.^6)-210*(rho.^4)+30*(rho.^2)-1; case 2, p = 210*(rho.^10)-504*(rho.^8)+420*(rho.^6)-140*(rho.^4)+15*(rho.^2); case 4, p = 129*(rho.^10)-252*(rho.^8)+168*(rho.^6)- 35*(rho.^4); case 6, p = 45*(rho.^10)- 72*(rho.^8)+ 28*(rho.^6); case 8, p = 10*(rho.^10)- 9*(rho.^8); case 10, p = (rho.^10); end; case 11, switch (l) case 1, p = 462*(rho.^11)-1260*(rho.^9)+1260*(rho.^7)-560*(rho.^5)+105*(rho.^3)-6*rho; case 3, p = 330*(rho.^11)- 840*(rho.^9)+ 756*(rho.^7)-280*(rho.^5)+ 35*(rho.^3); case 5, p = 165*(rho.^11)- 360*(rho.^9)+ 252*(rho.^7)- 56*(rho.^5); case 7, p = 55*(rho.^11)- 90*(rho.^9)+ 36*(rho.^7); case 9, p = 11*(rho.^11)- 10*(rho.^9); case 11, p = (rho.^11); end; case 12, switch (l) case 0, p = 924*(rho.^12)-2772*(rho.^10)+3150*(rho.^8)-1680*(rho.^6)+420*(rho.^4)-42*(rho.^2)+1; case 2, p = 792*(rho.^12)-2310*(rho.^10)+2520*(rho.^8)-1260*(rho.^6)+280*(rho.^4)-21*(rho.^2); case 4, p = 495*(rho.^12)-1320*(rho.^10)+1260*(rho.^8)- 504*(rho.^6)+ 70*(rho.^4); case 6, p = 220*(rho.^12)- 495*(rho.^10)+ 360*(rho.^8)- 84*(rho.^6); case 8, p = 66*(rho.^12)- 110*(rho.^10)+ 45*(rho.^8); case 10, p = 12*(rho.^12)- 11*(rho.^10); case 12, p = (rho.^12); end; end; return
github
jacksky64/imageProcessing-master
svc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/svc.m
5,562
utf_8
86dd8221e27b55319d8d9001503e5f92
%SVC Support Vector Classifier % % [W,J] = SVC(A,KERNEL,C) % [W,J] = SVC(A,TYPE,PAR,C) % W = A*SVC([],KERNEL,C) % W = A*SVC([],TYPE,PAR,C) % % INPUT % A Dataset % KERNEL - Untrained mapping to compute kernel by A*(A*KERNEL) during % training, or B*(A*KERNEL) during testing with dataset B. % - String to compute kernel matrices by FEVAL(KERNEL,B,A) % Default: linear kernel (PROXM([],'p',1)); % TYPE Kernel type (see PROXM) % PAR Kernel parameter (see PROXM) % C Regularization parameter (optional; default: 1) % % OUTPUT % W Mapping: Support Vector Classifier % J Object indices of support objects % % DESCRIPTION % Optimizes a support vector classifier for the dataset A by quadratic % programming. The non-linearity is determined by the kernel. % If KERNEL = 0 it is assumed that A is already the kernelmatrix (square). % In this case also a kernel matrix B should be supplied at evaluation by % B*W or MAP(B,W). % % There are several ways to define KERNEL, e.g. PROXM([],'r',1) for a % radial basis kernel or by USERKERNEL for a user defined kernel. % % If C is NaN this regularisation parameter is optimised by REGOPTC. % % See for more possibilties SVCINFO % % SEE ALSO % MAPPINGS, DATASETS, PROXM, USERKERNEL, NUSVC, RBSVC, REGOPTC % Copyright: D. de Ridder, D. Tax, S. Verzakov, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: svc.m,v 1.11 2009/07/22 19:29:41 duin Exp $ function [W,J,C,nu,alginf] = svc(a,kernel,par1,par2) prtrace(mfilename); if nargin > 1 & ~isempty(kernel) & isstr(kernel) & exist(kernel) ~= 2 % old call: svc(a,type,par,C) Options = []; if nargin == 4 C = par2; end if nargin < 4 | isempty(par2) C = 1; prwarning(3,'Regularization parameter C set to 1\n'); end if nargin < 3 | isempty(par1) par1 = 1; prwarning(3,'Kernel parameter par set to 1\n'); end kernel = proxm([],kernel,par1); else % new call if nargin < 4 Options = []; else Options = par2; end if nargin >= 3 C = par1; end if nargin < 3 | isempty(par1) C = 1; end if nargin < 2 | isempty(kernel) kernel = proxm([],'p',1); end end DefOptions.mean_centering = 1; DefOptions.pd_check = 1; DefOptions.bias_in_admreg = 1; DefOptions.pf_on_failure = 1; DefOptions.multiclass_mode = 'single'; Options = updstruct(DefOptions,Options,1); if nargin < 1 | isempty(a) W = mapping(mfilename,{kernel,C}); W = setname(W,'Support Vector Classifier'); elseif (~ismapping(kernel) | isuntrained(kernel)) % training islabtype(a,'crisp'); isvaldfile(a,1,2); % at least 1 object per class, 2 classes a = testdatasize(a,'objects'); [m,k,c] = getsize(a); nlab = getnlab(a); % The SVC is basically a 2-class classifier. More classes are % handled by mclassc. if c == 2 % two-class classifier if (isnan(C))|length(C)>1 % optimize trade-off parameter defs = {proxm([],'p',1),1,[]}; if isnan(C) % use a default range of C values parmin_max = [0,0;1e-2,1e2;0,0]; % kernel and Options can not be optimised else % use the range that is supplied by the user parmin_max = [0 0; min(C) max(C); 0 0]; C = NaN; end [W,J,C,nu,alginf] = regoptc(a,mfilename,{kernel,C,Options},defs,[2],parmin_max,testc([],'soft')); else % Compute the parameters for the optimization: y = 3 - 2*nlab; if ~isequal(kernel,0) if Options.mean_centering u = mean(a); % shift origin for better accuracy b = a - repmat(u,[m,1]); else b = a; u = []; end K = b*(b*kernel); K = min(K,K'); % make sure kernel matrix is symmetric % Perform the optimization: [v,J,C,nu] = svo(+K,y,C,Options); s = b(J,:); insize = k; else % kernel is already given! K = min(a,a'); % make sure kernel matrix is symmetric % Perform the optimization: [v,J,C,nu] = svo(+K,y,C,Options); s = []; u = []; insize = size(K,2); % ready for kernel inputs end % Store the results: W = mapping(mfilename,'trained',{u,s,v,kernel,J},getlablist(a),insize,2); % Note: even in case kernel is a mapping, we store the untrained % mapping, as training is just administration W = cnormc(W,a); W = setcost(W,a); alginf.svc_type = 'C-SVM'; alginf.kernel = kernel; alginf.C = C; alginf.nu = nu; alginf.nSV = length(J); alginf.classsizes = [nnz(y==1), nnz(y==-1)]; alginf.pf = isnan(nu); W = setname(W,'Support Vector Classifier'); end else % multi-class classifier: [W,J,C,nu,alginf] = mclassc(a,mapping(mfilename,{kernel,C,Options}),Options.multiclass_mode); end W = setname(W,'Support Vector Classifier'); else % execution v = kernel; w = +v; m = size(a,1); if isempty(w{2}) K = a; % user supplied testkernel J = w{5}; if size(K,2) > length(J) & size(K,2) >= max(J) K = K(:,J); % probably full test kernel elseif size(K,2) ~= length(J) error('Wrong test kernel supplied') end else % The first parameter w{1} stores the mean of the dataset. When it % is supplied, remove it from the dataset to improve the numerical % precision. Then compute the kernel matrix using proxm: if isempty(w{1}) K = a*(w{2}*w{4}); else K = (a-ones(m,1)*w{1})*(w{2}*w{4}); end end % Data is mapped by the kernel, now we just have a linear % classifier w*x+b: d = [K ones(m,1)] * w{3}; W = setdat(a,[d -d],v); end return
github
jacksky64/imageProcessing-master
rblibsvc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rblibsvc.m
1,915
utf_8
d62453cf819c693d66f8887bf17adde8
%RBSVC Automatic radial basis Support Vector Classifier using LIBSVM % % [W,KERNEL,NU] = RBLIBSVC(A) % % INPUT % A Dataset % % OUTPUT % W Mapping: Radial Basis Support Vector Classifier % KERNEL Untrained mapping, representing the optimised kernel % NU Resulting value for NU from NUSVC % % DESCRIPTION % This routine computes a classifier by NULIBSVC using a radial basis kernel % with an optimised standard deviation by REGOPTC. The resulting classifier % W is identical to NULIBSVC(A,KERNEL,NU). As the kernel optimisation is based % on internal cross-validation the dataset A should be sufficiently large. % Moreover it is very time-consuming as the kernel optimisation needs % about 100 calls to LIBSVC. % % SEE ALSO % MAPPINGS, DATASETS, PROXM, LIBSVC, NULIBSVC, REGOPTC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [w,kernel,nu] = rblibsvc(a,sig) if nargin < 2 | isempty(sig) sig = NaN; end if nargin < 1 | isempty(a) w = mapping(mfilename,{sig}); else islabtype(a,'crisp'); isvaldfile(a,2,2); % at least 1 object per class, 2 classes a = testdatasize(a,'objects'); c = getsize(a,3); if isnan(sig) % optimise sigma % find upper bound d = sqrt(+distm(a)); sigmax = min(max(d)); % max: smallest furthest neighbor distance % find lower bound d = d + 1e100*eye(size(a,1)); sigmin = max(min(d)); % min: largest nearest neighbor distance % call optimiser defs = {1}; parmin_max = [sigmin,sigmax]; [w,kernel,nu] = regoptc(a,mfilename,{sig},defs,[1],parmin_max,testc([],'soft')); else % kernel is given kernel = proxm([],'r',sig); [w,J,nu] = nulibsvc(a,kernel); end end w = setname(w,'RB LIBSVM Classifier'); return
github
jacksky64/imageProcessing-master
im_bpropagation.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_bpropagation.m
2,387
utf_8
c75c17355488eceb9ea5baddea69c6ff
%IM_BPROPAGATION Binary propagation of images stored in a dataset (DIP_Image) % % B = IM_BPROPAGATION(A1,A2,N,CONNECTIVITY,EDGE_CONDITION) % % INPUT % A1 Dataset with binary object images dataset (possibly multi-band) % to be treated as seed for the propagation % A2 Dataset with binary object images dataset (possibly multi-band) % to be treated as mask for the propagation % N Number of iterations (default inf) % CONNECTIVITY See BPROPAGATION % EDGE_CONDITION Value of edge, default 1 % % OUTPUT % B Dataset with propagated images % % DESCRIPTION % The binary images in A1 are dilated under the condition that the result % stays inside the components stored in A2. % % EXAMPLE % a = delft_idb; a = seldat(a,9); delfigs % mask = a*im_gray*im_threshold; figure, show(mask) % seed = mask*im_berosion; figure, show(seed) % cleaned = im_bpropagation(seed,mask); figure, show(cleaned) % showfigs % % SEE ALSO % DATASETS, DATAFILES, DIP_IMAGE, BPROPAGATION % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_bpropagation(a1,a2,n,connect,edgecon) prtrace(mfilename); if nargin < 5 | isempty(edgecon), edgecon = 1; end if nargin < 4 | isempty(connect), connect = 2; end if nargin < 3 | isempty(n), n = inf; end if isdataset(a1) if ~isdataset(a2) error('Seed and mask images should be both datasets') end fsize = getfeatsize(a1); if any(getfeatsize(a2) ~= fsize) error('Image structures of seed and mask images should be identical') end if length(fsize) == 2, fsize = [fsize 1]; end if size(a1,1) ~= size(a2,1) error('Same number of seed and mask images expected') end out = []; seed = data2im(a1); mask = data2im(a2); for i=1:size(a1,1) for j=1:fsize(3) f = feval(mfilename,seed(:,:,j,i),mask(:,:,j,i),n,connect,edgecon); seed(:,:,j,i) = f; end end b = setdat(a,im2obj); elseif isdatafile(a1) if ~isdatafile(a2) error('Seed and mask images should be both datafiles') end b = dyadic(a1,mfilename,a2,{n,connect,edgecon}); elseif isa(a1,'double') | isa(a2,'dip_image') % here we have a single image a1 = dip_image(a1,'bin'); a2 = dip_image(a2,'bin'); b = bpropagation(a1,a2,n,connect,edgecon); end return
github
jacksky64/imageProcessing-master
im_unif.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_unif.m
1,204
utf_8
7f05e468c2eabcdf937dabf7598b1738
%IM_UNIF Uniform filter of images stored in a dataset/datafile % % B = IM_UNIF(A,SX,SY) % B = A*IM_UNIF([],SX,SY) % % INPUT % A Dataset with object images dataset (possibly multi-band) % SX Desired horizontal width for filter, default SX = 3 % SY Desired vertical width for filter, default SY = SX % % OUTPUT % B Dataset/datafile with Gaussian filtered images % % SEE ALSO % DATASETS, DATAFILES, IM_GAUSSF, FILTIM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_gauss(a,sx,sy) prtrace(mfilename); if nargin < 3, sy = []; end if nargin < 2 | isempty(sx), sx = 3; end if isempty(sy), sy = sx; end if (sx<1 | sy<1) error('Filter width should be at least 1') end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{sx,sy}); b = setname(b,'Uniform filter'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); b = filtim(a,mfilename,{sx,sy}); elseif isa(a,'double') % here we have a single image rx = round(sx); fx = [1:rx]/rx; ry = round(sy); fy = [1:ry]/ry; b = conv2(fy,fx,a,'same'); end return
github
jacksky64/imageProcessing-master
newfig.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/newfig.m
942
utf_8
88e9e3d9057179f2294f97a98ab73c79
%NEWFIG Create new figure on given position % % NEWFIG(FIGURE_NUMBER,FIGURE_PER_ROW) % % INPUT % FIGURE_NUMBER Number of the figure % FIGURE_PER_ROW Figures per row (default: 4) % % OUTPUT % % DESCRIPTION % Creates figure number FIGURE_NUMBER and places it on the screen, % such that (when sufficient figures are created), the screen is % covered by an array of figures, with FIGURE_PER_ROW figures per row. % % SEE ALSO % SCATTERD, PLOTC % $Id: newfig.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function newfig(fign,n); if nargin < 2, n=4; end if nargin < 1, fign=gcf+1; end % if the figure already exist, kill it! if any(get(0,'children') == fign) delete(fign); end % Create the figure, figure(fign); set(gcf,'menubar','none'); % and place it in the correct position: ny = 1-ceil(fign/n)/n; nx = (fign -1 - n*floor((fign-1)/n))/n; d = 1/n; set(gcf,'units','normalized','position',[nx ny d*0.95 d*0.85]); return
github
jacksky64/imageProcessing-master
scalem.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/scalem.m
3,471
utf_8
ea9e240e095bc805e8a74b190c3b73f7
%SCALEM Compute scaling map % % W = SCALEM(A,T) % % INPUT % A Dataset % T Type of scaling (optional; default: the class priors weighted mean of A % is shifted to the origin) % % OUTPUT % W Scaling mapping % % DESCRIPTION % Computes a scaling map W, whose type depends on the parameter T: % % [], 'c-mean' - The mean of A is shifted to the origin. Class priors are taken % into account. % 'mean' - The mean of A is shifted to the origin. This is computed for % the data as given in A, neglecting class priors. % 'c-variance' - The mean of A is shifted to the origin and the average class % variances (within-scatter) are normalized. Class priors are % taken into account. % 'variance' - The mean of A is shifted to the origin and the total variances % of all features are scaled to 1. This is computed for the % data as given in A, neglecting class priors. % '2-sigma' - For each feature f, the 2-sigma interval, [f-2*std(f),f+2*std(f)] % is rescaled to [0,1]. Values outside this domain are clipped. % Class priors are taken into account. % 'domain' - The domain for all features in the dataset A is set to [0,1]. % This is computed for the data as given in A, neglecting class priors. % % The map W may be applied to a new dataset B by B*W. % % SEE ALSO % MAPPING, DATASET % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: scalem.m,v 1.9 2009/11/27 08:52:02 duin Exp $ function W = scalem(a,t) prtrace(mfilename); if nargin < 2 prwarning(4,'No mapping type specified. The class priors weighted mean of A is shifted to the origin.'); t = ''; elseif isempty(t) t = ''; end %DXD Make the naming even better: dname = 'Scaling mapping'; switch t case 'mean' dname = 'zero-mean'; case {'','c-mean'} dname = 'zero-mean (+class priors)'; case 'variance' dname = 'unit-var'; case 'c-variance' dname = 'unit-var (+class priors)'; case '2-sigma' dname = '0-1 scaling (+-2 standard dev.)'; case 'domain' dname = '0-1 scaling'; end % No data, return an untrained mapping. if (nargin < 1) | isempty(a) W = mapping('scalem',{t}); W = setname(W,dname); return; end [a,c,lablist] = cdats(a,1); [m,k] = size(a); switch t case {'','c-mean'} u = meancov(a); u =getprior(a)*(+u); s = ones(1,k); clip = 0; case 'mean' a = remclass(a); u = mean(a,1); s = ones(1,k); clip = 0; case 'c-variance' p = getprior(a); U = meancov(a); u = p*(+U); s = zeros(1,k); for j=1:c s = s + p(j)*var(seldat(a,j)*cmapm(+U(j,:),'shift')); end s = sqrt(s); clip = 0; case 'variance' %[u,G] = meancov(+a); %s = sqrt(diag(G))'; u = mean(a,1); s = std(a,0,1); clip = 0; case '2-sigma' p = getprior(a); U = meancov(a); u = p*(+U); s = zeros(1,k); for j=1:c s = s + p(j)*var(seldat(a,j)); end s = sqrt(s); s = 4*s; u = u-0.5*s; clip = 1; case 'domain' mx = max(a,[],1)+eps; mn = min(a,[],1)-eps; u = mn; s = (mx - mn)*(1+eps); clip = 0; otherwise error('Unknown option') end J = find(s==0); s(J) = ones(size(J)); % No scaling for zero variances. W = cmapm({u,s,clip},'scale'); W.size_out = a.featsize; W = setlabels(W,getfeatlab(a)); return;
github
jacksky64/imageProcessing-master
mclassm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/mclassm.m
2,458
utf_8
dfa95c18e9a18bd2606c311f0d9acf3e
%MCLASSM Computation of a combined, multi-class based mapping % % W = MCLASSM(A,MAPPING,MODE,PAR) % % INPUT % A Dataset % MAPPING Untrained mapping % MODE Combining mode (optional; default: 'weight') % PAR Parameter needed for the combining % % OUTPUT % W Combined mapping % % DESCRIPTION % If A is a unlabeled dataset or double matrix, it is converted to a % one-class dataset. For one-class datasets A, the mapping is computed, % calling the untrained MAPPING using the labeled samples of A only. % For multi-class datasets separate mappings are determined for each class % in A. They are combined as defined by MODE and PAR. The following % combining rules are supported: % 'weight': weight the mapping outcome for class j by PAR(j) and sum % over the classes. This is useful for densities in which case % PAR is typically the set of class priors (these are in fact % the defaults if MODE = 'weight'). % 'mean' : combine by averaging. % 'min' : combine by the minimum rule. % 'max' : combine by the maximum rule. % % This routine is only defined for datasets with crisp labels. % % SEE ALSO % DATASETS, MAPPINGS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function w = mclassm(a,mapp,mode,par); prtrace(mfilename); if nargin < 4, par = []; end if nargin < 3, mode = 'weight'; end if nargin < 2, mapp = []; end if nargin < 1 | isempty(a) w = mapping(mfilename,{classf,mode}); return end if ~isa(mapp,'mapping') | ~isuntrained(mapp) error('Second parameter should be untrained mapping') end [a,c,lablist,p] = cdats(a); %islabtype(a,'crisp'); if c == 1 w = a*mapp; else w = []; for j=1:c b = seldat(a,j); w = [w,b*mapp]; end if ismapping(mode) w = w*mode elseif isstr(mode) switch mode case 'mean' w = w*meanc; case 'min' w = w*minc; case 'max' w = w*maxc; case 'weight' if size(w{1},2) ~= 1 error('Weighted combining only implemented for K to 1 mappings') end if isempty(par) par = p; end lenw = length(w.data); if length(par) ~= lenw error(['Wrong number of weights. It should be ' num2str(lenw)]) end w = w*affine(par(:)); otherwise error('Unknown combining mode') end end w = setsize(w,[size(a,2),1]); w = setlabels(w,lablist); end return
github
jacksky64/imageProcessing-master
cdats.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/cdats.m
1,958
utf_8
2686ee521a7698c29fa5e642699dbd21
%CDATS Support routine for checking datasets % % [B,C,LABLIST,P] = CDATS(A,REDUCE) % % INPUT % A Dataset or double % REDUCE 0/1, Reduce A to labeled samples (1) or not (0, default), optional. % % OUTPUT % B Dataset % C Number of classes % LABLIST Label list of A % P Priors % % DESCRIPTION % This routine supports dataset checking and conversion for mappings % and density estimators. If A is double it is converted to a one-class % dataset with all labels set to 1. The same holds if A is an entirely % unlabeled dataset. The label list of A is returned in LABLIST, but % for multi-class datasets LABLIST is set to 1. C is the number of classes % in A. The priors are returned in P (length C), the dataset itself in B. % If REDUCE is 1, all unlabeled objects are removed. % % If A has soft labels, B = A. % If A does not have labels but targets: C = 1, LABLIST = [], P = 1. % % SEE ALSO % DATASETS, MAPPINGS function [a,c,lablist,p] = cdats(a,red) prtrace(mfilename); if (nargin < 2), red = 0; end if (isdataset(a) & islabtype(a,'targets')) c = 1; lablist = []; p = 1; elseif (isdataset(a) & islabtype(a,'soft')) c = getsize(a,3); lablist = getlablist(a); if nargout > 3, p = getprior(a); end else if ~isvaldfile(a) a = dataset(a); end c = getsize(a,3); if nargout > 3 % avoid unnecessary warnings p = getprior(a); end if (c == 0) a = setlabels(a,1); p = 1; c = 1; lablist = 1; prwarning(4,'Dataset unlabeled: all objects will be used') elseif (c == 1) p = 1; if (red == 1) a = seldat(a); % remove unlabeled objects end lablist = getlablist(a); else prwarning(4,'Multiclass dataset will be combined using priors') if (red == 1) a = seldat(a); % remove unlabeled objects end lablist = 1; end isvaldfile(a,1,1); % at least one object per class end; return
github
jacksky64/imageProcessing-master
proxm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/proxm.m
5,944
utf_8
87c619ec24866c3bd3663663f102710f
%PROXM Proximity mapping % % W = PROXM(A,TYPE,P,WEIGHTS) % W = A*PROXM([],TYPE,P,WEIGHTS) % % INPUT % A Dataset % TYPE Type of the proximity (optional; default: 'distance') % P Parameter of the proximity (optional; default: 1) % WEIGHTS Weights (optional; default: all 1) % % OUTPUT % W Proximity mapping % % DESCRIPTION % Computation of the [K x M] proximity mapping (or kernel) defined by % the [M x K] dataset A. Unlabeled objects in A are neglected. % If B is an [N x K] dataset, then D=B*W is the [N x M] proximity matrix % between B and A. The proximities can be defined by the following types: % % 'POLYNOMIAL' | 'P': SIGN(A*B'+1).*(A*B'+1).^P % 'HOMOGENEOUS' | 'H': SIGN(A*B').*(A*B').^P % 'EXPONENTIAL' | 'E': EXP(-(||A-B||)/P) % 'RADIAL_BASIS' | 'R': EXP(-(||A-B||.^2)/(P*P)) % 'SIGMOID' | 'S': SIGM((SIGN(A*B').*(A*B'))/P) % 'DISTANCE' | 'D': ||A-B||.^P % 'MINKOWSKI' | 'M': SUM(|A-B|^P).^(1/P) % 'CITY-BLOCK' | 'C': SUM(|A-B|) % 'COSINE' | 'O': 1 - (A*B')/||A||*||B|| % % In the polynomial case for a non-integer P, the proximity is computed % as D = SIGN(S+1).*ABS(S+1).^P, in order to avoid problems with negative % inner products S = A*B'. The features of the objects in A and B may be % weighted by the weights in the vector WEIGHTS. % % SEE ALSO % MAPPINGS, DATASETS % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % 27-11-2008, Marc Hulsman, MR1 % Added kernel normalization. % $Id: proxm.m,v 1.10 2010/01/15 13:39:01 duin Exp $ function W = proxm(A,type,s,weights) prtrace(mfilename); if (nargin < 4) weights = []; prwarning(4,'Weights are not supplied, assuming all 1.'); end if (nargin < 3) | (isempty(s)) s = 1; prwarning(4,'The proximity parameter is not supplied, assuming 1.'); end if (nargin < 2) | (isempty(type)) type = 'd'; prwarning(4,'Type of the proximity is not supplied, assuming ''DISTANCE''.'); end % No data, return an untrained mapping. if (nargin < 1) | (isempty(A)) W = mapping(mfilename,{type,s,weights}); W = setname(W,'Proximity mapping'); return; end [m,k] = size(A); if (isstr(type)) % Definition of the mapping, just store parameters. all = char('polynomial','p','homogeneous','h','exponential','e','radial_basis','r', ... 'sigmoid','s','distance','d','minkowski','m','city-block','c',... 'cosine','o','uniform','u','ndiff'); if (~any(strcmp(cellstr(all),type))) error(['Unknown proximity type: ' type]) end A = cdats(A,1); [m,k] = size(A); %if (isa(A,'dataset')) if (isdataset(A)) A = testdatasize(A); W = mapping(mfilename,'trained',{A,type,s,weights},getlab(A), ... getfeatsize(A),getobjsize(A)); else W = mapping(mfilename,'trained',{A,type,s,weights},[],k,m); end W = setname(W,'Proximity mapping'); elseif isa(type,'mapping') % Execution of the mapping: compute a proximity matrix % between the input data A and B; output stored in W. w = type; [B,type,s,weights] = deal(w.data{1},w.data{2},w.data{3},w.data{4}); [kk,n] = size(w); if (k ~= kk) error('Mismatch in sizes between the mapping and its data stored internally.'); end if (~isempty(weights)) if (length(weights) ~= k), error('Weight vector has a wrong length.'); end A = A.*(ones(m,1)*weights(:)'); B = B.*(ones(n,1)*weights(:)'); end switch type case {'polynomial','p'} D = +(A*B'); D = D + ones(m,n); if (s ~= round(s)) D = +sign(D).*abs(D).^s; elseif (s ~= 1) D = D.^s; end case {'homogeneous','h'} D = +(A*B'); if (s ~= round(s)) D = +sign(D).*abs(D).^s; elseif (s ~= 1) D = D.^s; end case {'sigmoid','s'} D = +(A*B'); D = sigm(D/s); case {'city-block','c'} D = zeros(m,n); t = sprintf('Processing %i objects: ',n); prwaitbar(n,t); for j=1:n prwaitbar(n,j,[t int2str(j)]); D(:,j) = sum(abs(A - repmat(+B(j,:),m,1)),2); end prwaitbar(0); case {'minkowski','m'} D = zeros(m,n); t = sprintf('Processing %i objects: ',n); prwaitbar(n,t); for j=1:n prwaitbar(n,j,[t int2str(j)]); D(:,j) = sum(abs(A - repmat(+B(j,:),m,1)).^s,2).^(1/s); end prwaitbar(0); case {'exponential','e'} D = dist2(B,A); D = exp(-sqrt(D)/s); case {'radial_basis','r'} D = dist2(B,A); D = exp(-D/(s*s)); case {'distance','d'} D = dist2(B,A); if s ~= 2 D = sqrt(D).^s; end case {'cosine','o'} D = +(A*B'); lA = sqrt(sum(A.*A,2)); lB = sqrt(sum(B.*B,2)); D = 1 - D./(lA*lB'); case {'ndiff'} D = zeros(m,n); t = sprintf('Processing %i objects: ',n); prwaitbar(n,t); for j=1:n prwaitbar(n,j,[t int2str(j)]); D(:,j) = sum(+A ~= repmat(+B(j,:),m,1),2); end prwaitbar(0); otherwise error('Unknown proximity type') end W = setdat(A,D,w); else error('Illegal TYPE argument.') end return; function D = dist2(B,A) % Computes square Euclidean distance, avoiding large matrices for a high % dimensionality data ma = size(A,1); mb = size(B,1); if isdatafile(A) D = zeros(ma,mb); next = 1; while next > 0 [a,next,J] = readdatafile(A,next); D(J,:) = +dist2(a,B); end elseif isdatafile(B) D = zeros(ma,mb); next = 1; while next > 0 % we need another version of readdatafile here, as due [b,next,J] = readdatafile2(B,next); % to persistent variables double D(:,J) = +dist2(A,b); % looping can not be handled correctly end else % A and B are not datafiles D = ones(ma,1)*sum(B'.*B',1); D = D + sum(A.*A,2)*ones(1,mb); D = D - 2 .* (+A)*(+B)'; % Clean result. J = find(D<0); D(J) = zeros(size(J)); end return
github
jacksky64/imageProcessing-master
createdatafile.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/createdatafile.m
8,747
utf_8
8012e1f74bccfd7b83ae3557a6a3c0c5
%CREATEDATAFILE Create datafile on disk % % B = CREATEDATAFILE(A,DIR,ROOT,TYPE,CMD,FMT) % % INPUT % A Datafile % DIR Name of datafile, default: name of A % ROOT Root directory in which datafile should be created % default: present directory % TYPE Datafile type ('raw' (default) or 'cell') % CMD Command for writing files, default: IMWRITE % FMT Format, default 'bmp' % % OUTPUT % B New datafile % % DESCRIPTION % The existing datafile A is recreated on disk, one file per object, % including all preprocessing. The IDENT.IDENT field and the class priors % of A are copied. All other addional information of A is lost. % The order of objects in A and B may differ. % % Raw datafiles are stored as integer images, use TYPE = 'cell' to store % floats. % % The difference between CREATEDATAFILE and SAVEDATAFILE is that the latter % assumes that the datafile after completion by preprocessing can be converted % into a dataset and the data is stored as such and as compact as possible. % CREATEDATAFILE saves every object in a separate file and is thereby % useful in case preprocessing does not yield a proper dataset with the % same number of features for every object. % % SEE ALSO DATAFILES, DATASETS, SAVEDATAFILE % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = createdatafile(a,dirr,root,type,par1,par2) prtrace(mfilename,1); isdatafile(a); if nargin < 6, par2 = []; end if nargin < 5, par1 = []; end if nargin < 4, type = 'raw'; end if nargin < 3 | isempty(root), root = pwd; end if nargin < 2, dirr = getname(a); end if ~any(strcmp(type,{'raw','cell'})) error('Type of datafile is wrong or not supported'); end actdir = cd; cd(root); if exist(dirr) == 7 % if datafile already exists cd(dirr); % go to it fclose('all'); delete *.mat % make it empty delete file* else [success,mess] = mkdir(dirr); if ~success error(mess) end cd(dirr) end if strcmp(type,'raw') % construct standard raw datafile if isempty(par1), par1 = 'imwrite'; end if isempty(par2), par2 = 'bmp'; end cmd = par1; fmt = par2; subdirs = getlablist(a,'string'); nlab = getnlab(a); m = length(nlab); s = sprintf('Creating %i files: ',m); prwaitbar(m,s); n = 0; if ~isempty(subdirs) for j=1:size(subdirs,1) % run over all classes sname = deblank(subdirs(j,:)); [success,mess] = mkdir(sname); if ~success error(mess); end cd(sname) J = find(nlab==j); p = floor(log10(length(J)))+1; form = ['%' int2str(p) '.' int2str(p) 'i']; for j = 1:length(J) n = n+1; prwaitbar(m,n,[s int2str(n)]); im = data2im(a(J(j),:)); feval(cmd,im,['file_' num2str(j,form)],fmt); end cd .. end end J = find(nlab == 0); if ~isempty(J) p = floor(log10(length(J)))+1; form = ['%' int2str(p) '.' int2str(p) 'i']; for j = 1:length(J) n = n+1; prwaitbar(m,n,[s int2str(n)]); im = data2im(a(J(j),:)); feval(cmd,im,['file_' num2str(j,form)],fmt); end end prwaitbar(0); cd .. b = datafile(dirr); if ~isempty(a,'prior') b = setprior(b,getprior(a)); end id = getident(a); b = setident(b,id); cd(dirr); save([dirr '.mat'],'b'); cd(actdir); elseif strcmp(type,'cell') %store datafiles in cells if isempty(par1) % maximum nr of elements in datafile par1 = 1000000; end if isempty(par2) % default: no conversion par2 = 0; end filesize = par1; nbits = par2; % reorder datafile for faster retrieval file_index = getident(a.dataset,'file_index'); [jj,R] = sort(file_index(:,1)+file_index(:,2)/(max(file_index(:,2),[],1)+1)); a = a(R,:); [RR,S] = sort(R); % to reconstruct order later dirname = fullfile(root,dirr); m = length(R); file_index = zeros(m,2); % initialise structure with file information % skip this for the time being % cfiles = struct('name',cell(1),'nbits',[], ... % 'offsetd',[],'scaled',[],'offsett',[],'scalet',[]); nobjects = 1; files = {}; s = sprintf('Storing %i objects: ',m); prwaitbar(m,s) prwaitbar(m,nobjects,[s int2str(nobjects)]); im = data2im(a(1,:)); imsize = prod(size(im)); nfiles = 0; while (nobjects <= m) nfiles = nfiles+1; obj1 = nobjects; fsize = imsize; imcells = {im}; sizefit = 1; mm = 0; nobjects = nobjects+1; prwaitbar(m,nobjects,[s int2str(nobjects)]); while (nobjects <= m) & sizefit im = data2im(a(nobjects,:)); % convert single object imsize = prod(size(im)); nobjects = nobjects+1; mm = mm+1; if (fsize+imsize < filesize) & (mm < m/50) % store data in same file as long as size fits % and never more than 2% of the objects % (this is just to keep better track of progress) fsize = fsize+imsize; imcells = {imcells{:} im}; sizefit = 1; obj2 = nobjects; else sizefit = 0; obj2 = nobjects-1; nobjects = obj2; end end obj2 = min(obj2,m); % [imcells,scaled,offsetd,scalet,offsett,prec] = convert(imcells,nbits); % convert precision filej = ['file_' num2str(nfiles,'%4.4i')]; fname = fullfile(dirname,filej); files = {files{:} filej}; save(fname,'imcells'); % disp([filej ' ' int2str(length(imcells))]); % save(fname,'imcells','scaled','offsetd','scalet','offsett','prec'); % cfiles(j).name = filej; % name of the file % cfiles(j).prec = prec; % precision % cfiles(j).scaled = scaled; % scaling for datafield % cfiles(j).offsetd = offsetd; % offset for datafield % cfiles(j).scalet = scalet; % scaling for target field % cfiles(j).offsett = offsett; % offset for target field % cfiles(j).sized = a.featsize; % feature (image) size % cfiles(j).sizet = size(a.targets,2); % size target field % % create file_index file_index(obj1:obj2,1) = repmat(nfiles,obj2-obj1+1,1); file_index(obj1:obj2,2) = [1:obj2-obj1+1]'; end % finalise datafile definition b = datafile; b.files = files; % file information b.rootpath = dirname; b.type = 'cell'; % cell datafile preproc.preproc = []; preproc.pars = {}; b.preproc = preproc; % no preprocessing b.dataset = setident(a.dataset,file_index,'file_index'); % store file_index b.dataset = setname(b.dataset,dirr); b = b(S,:); % reconstruct order of objects save(fullfile(dirname,dirr),'b'); % store the datafile as mat-file for fast retrieval prwaitbar(0); cd(actdir); end return function [a,scaled,offsetd,scalet,offsett,prec] = convert(a,nbits) % handle precision data and target fields if nbits == 0 % no conversion scaled = []; offsetd = []; scalet = []; offsett = []; prec = 'double'; return; end % compute data field conversion pars data = +a; maxd = max(max(data)); mind = min(min(data)); scaled = (2^nbits)/(maxd-mind); offsetd = -mind; data = (data+offsetd)*scaled; % compute target field conversion pars targ = gettargets(a); if isempty(targ) % no targets set scalet = []; offsett = []; else maxt = max(max(targ)); mint = min(min(targ)); scalet = (2^nbits)/(maxt-mint); offsett = -mint; targ = (targ+offsett)*scalet; end % execute conversion switch nbits case 8 data = uint8(data); targ = uint8(targ); prec = 'uint8'; case 16 data = uint16(data); targ = uint16(targ); prec = 'uint16'; case 32 data = uint32(data); targ = uint32(targ); prec = 'uint32'; otherwise error('Desired conversion type not found') end % store results a.data = data; a.targets = targ; return return
github
jacksky64/imageProcessing-master
chernoffm.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/chernoffm.m
2,908
utf_8
f68913a263bb7296e579bd8fe2007935
%CHERNOFFM Suboptimal discrimination linear mapping (Chernoff mapping) % % W = CHERNOFFM(A,N,R) % % INPUT % A Dataset % N Number of dimensions to map to, N < C, where C is the number of classes % (default: min(C,K)-1, where K is the number of features in A) % R Regularization variable, 0 <= r <= 1, default is r = 0, for r = 1 the % Chernoff mapping is (should be) equal to the Fisher mapping % % OUTPUT % W Chernoff mapping % % DESCRIPTION % Finds a mapping of the labeled dataset A onto an N-dimensional linear % subspace such that it maximizes the heteroscedastic Chernoff criterion % (also called the Chernoff mapping). % % REFERENCE % M. Loog and R.P.W. Duin, Linear Dimensionality Reduction via a Heteroscedastic % Extension of LDA: The Chernoff Criterion, IEEE Transactions on pattern % analysis and machine intelligence, vol. PAMI-26, no. 6, 2004, 732-739. % % SEE ALSO % MAPPINGS, DATASETS, FISHERM, NLFISHERM, KLM, PCA % Copyright: M. Loog, [email protected] % Image Sciences Institute, University Medical Center Utrecht % P.O. Box 85500, 3508 GA Utrecht, The Netherlands % $Id: chernoffm.m,v 1.3 2010/02/08 15:31:48 duin Exp $ function W = chernoffm(a,n,r) prtrace(mfilename); if (nargin < 3) r = 0; end if (nargin < 2) prwarning (4, 'number of dimensions to map to not specified, assuming min(C,K)-1'); n = []; end % If no arguments are specified, return an untrained mapping. if (nargin < 1) | (isempty(a)) W = mapping('chernoffm',{n,r}); W = setname(W,'Chernoff mapping'); return end isvaldset(a,2,2); % at least 2 objects per class, 2 classes % If N is not given, set it. [m,k,c] = getsize(a); if (isempty(n)), n = min(k,c)-1; end if (n >= m) error('The dataset is too small for the requested dimensionality') end % To simplify computations, the within scatter W is set to the identity matrix % therefore A is centered and sphered by KLMS. v = klms(a); a = a*v; k = size(v,2); % dimensionalities may have changed for small training sets % Now determine a solution to the Chernoff criterion [U,G] = meancov(a); CHERNOFF = zeros(k); p = getprior(a); for i = 1:c-1 % loop over all class pairs for j = i+1:c p_i = p(i)/(p(i)+p(j)); p_j = p(j)/(p(i)+p(j)); G_i = (1-r)*G(:,:,i) + r*eye(k); G_j = (1-r)*G(:,:,j) + r*eye(k); G_ij = p_i*G_i + p_j*G_j; m_ij = sqrtm(real(prinv(G_ij)))*(U(i,:) - U(j,:))'; CHERNOFF = CHERNOFF + p(i) * p(j) * ... ( m_ij * m_ij' ... + 1/(p_i*p_j) * ( logm(G_ij) ... - p_i * logm(G_i) - p_j * logm(G_j) ) ); end end [F,V] = preig(CHERNOFF); [dummy,I] = sort(-diag(V)); I = I(1:n); rot = F(:,I); off = -mean(a*F(:,I)); preW = affine(rot,off,a); W = v*preW; % Construct final mapping. W = setname(W,'Chernoff mapping'); return
github
jacksky64/imageProcessing-master
band2obj.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/band2obj.m
2,883
utf_8
19a57f14d1c5f11326b820a3fb24691f
%BAND2OBJ Mapping image bands to objects % % B = BAND2OBJ(A,N) % W = BAND2OBJ([],N) % B = A*W % % INPUT % A Dataset or datafile with multiband image objects. % N Number of successive bands to be combined in an object. % The number of image bands in A should be multiple of N. % Default N = 1. % % OUTPUT % W Mapping performing the band selection % B Output dataset or datafile. % % DESCRIPTION % If the objects in a dataset or datafile A are multi-band images, e.g. RGB % images, or the result of IM_PATCH, then the featsize of A is [C,R,L] for % for L bands of a C x R image. This routine combines sets of N successive % bands as separate objects. The total number of objects is thereby % enlarged by a factor L/N. All information of the constituting objects % like labels, is copied to the newly created objects. % % Note: BAND2OBJ cannot be applied to datafiles for which already a % bandselection (BANDSEL) has been defined. % % SEE ALSO % DATASETS, DATAFILES, BANDSEL, IM2OBJ, DATA2IM % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = band2obj(a,N) mapname = 'Bands to Objects'; if nargin < 2, N = []; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',{N}); b = setname(b,mapname); else isvaldfile(a); %isobjim(a); % datafiles have object images m = size(a,1); if isempty(N) % all needed for treating variable numbers of bands bandnames = getident(a,'bandnames'); if ~isempty(bandnames) K = zeros(m,1); for j=1:m, K(j,:) = size(bandnames{j},1); end if any(K~=K(1)) N = zeros(m,max(K)); for j=1:m, N(j,1:K(j)) = [1:K(j)]; end else N = 1; end else N = 1; end end if size(N,1) == m & m > 1 % per object all bands to be selected are given k = max(N(:)); b = []; s = sprintf('Checking %i bands: ',k); prwaitbar(k,s); for j=1:k prwaitbar(k,j,[s int2str(j)]); [I,J] = find(N==j); % Finds all objects for which we have to select band j if ~isempty(I) b = [b; bandsel(a(I,:),repmat(j,length(I),1))]; % wrong !!!! bandsel expects something else, solve there! end end prwaitbar(0); elseif size(N,1) == 1 % N is number of successive objects to be combined k = getfeatsize(a,3); % We assume that all objects have the same number of bands if k > 1 if N*round(k/N) ~= k error('Number of images bands should be multiple of N') end s = sprintf('Checking %i bands: ',k); prwaitbar(k,s); prwaitbar(k,1,[s '1']); b = bandsel(a,1:N); for j=2:round(k/N) prwaitbar(k,j,[s int2str(j)]); b = [b; bandsel(a,(j-1)*N+1:j*N)]; end prwaitbar(0); else b = a; end else error('Second parameter has wrong size') end end return
github
jacksky64/imageProcessing-master
libsvmcheck.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/libsvmcheck.m
474
utf_8
403ba4e83ee91c67c682c9edc2565eac
%LIBSVMCHECK Check whether the LIBSVM toolbox is in the path function libsvmcheck if exist('svmpredict','file') ~= 3 & exist('svmpredict.dll','file') ~= 2 error([newline 'The LIBSVM package is not found. Download and install it from' ... newline 'http://www.csie.ntu.edu.tw/~cjlin/libsvm/']) else p = which('svmtrain'); if ~isempty(strfind(p,'biolearn')) error('The bioinfo toolbox is in the way, please remove it from the path') end end
github
jacksky64/imageProcessing-master
labcmp.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/labcmp.m
1,172
utf_8
bfc40e4bb42265de6ee75522b63e650f
%LABCMP Compare label sets % % [JNE,JEQ] = LABCMP(LABELS1,LABELS2) % % INPUT % LABELS1 - list of labels (strings or numeric) % LABELS2 - list of labels (strings or numeric) % % OUTPUT % JNE - Indices of non-matching labels % JEQ - indices of matching labels % % DESCRIPTION % The comparison of two label sets is particular useful to find % erroneaously classified objects. For example, if W is a trained % classifier and A a labeled testset, then the estimated labels are % given by LAB_EST = A*W*LABELD, while the true labels can be found % by LAB_TRUE = GETLABELS(A). The erroneously and correctly classfied % objects can be found by [JNE,JEQ] = LABCMP(LAB_EST,LAB_TRUE). % % See also MAPPINGS, DATASETS, LABELD, TESTC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [Jne,Jeq] = labcmp(lab1,lab2); prtrace(mfilename); [m1,n1] = size(lab1); [m2,n2] = size(lab2); if (m1 ~= m2) error('Label sets should have equal sizes') end [nn,J] = nlabcmp(lab1,lab2); Jne = find(~J); Jeq = find(J); return
github
jacksky64/imageProcessing-master
testd.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testd.m
1,602
utf_8
bf21d1853b98c052c9eafb4cbdd51fef
%TESTD Find classification error of dataset applied to given classifier % % [E,C] = TESTD(A,W) % [E,C] = TESTD(A*W) % E = A*W*TESTD % % INPUT % A Dataset % W Classifier % % OUTPUT % E Fraction of labeled objects in A that is erroneously classified % C Vector with numbers of erroneously classified objects per class. % They are sorted according to A.LABLIST % % DESCRIPTION % This routine performs a straightforward testing of the labeled objects % in A by the classifier W. Unlabeled objects are neglected. Just a % fraction of the erroneously classified objects is returned. Not all % classes have to be present in A and class priors are neglected. TESTD % thereby essentially differs from TESTC which tests the classifier instead % of the dataset. Labels found for the individual objects by the classifier % W may be retrieved by LABELD % % SEE ALSO % DATASETS, MAPPINGS, TESTD, LABELD % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [error,class_errors] = testd(a,w) if nargin < 2, w = []; end if nargin < 1 | isempty(a) error = mapping(mfilename,'fixed',{w}); error = setname(error,'testd'); class_errors = []; elseif isempty(w) s = classsizes(a); c = getsize(a,3); class_errors = zeros(1,c); n = 0; for j=1:c b = seldat(a,j); if ~isempty(b) class_errors(j) = nlabcmp(getlabels(b),b*labeld); end n = n+size(b,1); end error = sum(class_errors)/n; else [error,class_errors] = testd(a*w); end return
github
jacksky64/imageProcessing-master
im_stat.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_stat.m
2,355
utf_8
c9d64e86fc06111f67c8b0dae44e983c
%IM_STAT Computation of some image statistics % % B = IM_STAT(A,STAT) % B = A*IM_STAT([],STAT) % % INPUT % A Dataset with object images dataset (possibly multi-band) % STAT String cell array or series of statistics % % OUTPUT % B Dataset with statistics replacing images (possibly multi-band) % % DESCRIPTION % For all images in the dataset A the statistics as defined in the % cell array STAT are computed. The following statistics are supported: % (order is arbitrary) % % 'mean', 'row_mean', 'col_mean', 'std', 'row_std','col_std', % 'min', 'row_min', 'col_min, 'max', 'row_max','col_max, % 'median','row_median','col_median','size','sum' % % Default STAT = {'mean','var','min','max','size'} % % SEE ALSO % DATASETS, DATAFILES % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = im_stat(a,varargin) prtrace(mfilename); if nargin < 2 | isempty(varargin) stats = {'mean','std','min','max','size'}; else stats = varargin; end if iscell(stats{1}) stats = stats{1}; end if nargin < 1 | isempty(a) b = mapping(mfilename,'fixed',stats); b = setname(b,'Image statistics'); elseif isa(a,'dataset') % allows datafiles too isobjim(a); outsize = [size(stats,1)*getfeatsize(a,3)]; b = filtim(a,mfilename,{stats},outsize); elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image if isa(a,'dip_image'), a = double(a); end n = length(stats); b = []; for i=1:n switch stats{i} case 'mean' b = [b mean(a(:))]; case 'std' b = [b std(a(:))]; case 'min' b = [b min(a(:))]; case 'max' b = [b max(a(:))]; case 'median' b = [b median(a(:))]; case 'row_mean' b = [b mean(a,2)']; case 'row_std' b = [b std(a,2)']; case 'row_min' b = [b min(a,[],2)']; case 'row_max' b = [b max(a,[],2)']; case 'row_median' b = [b median(a,2)']; case 'col_mean' b = [b mean(a,1)]; case 'col_std' b = [b std(a,1)]; case 'col_min' b = [b min(a,[],1)]; case 'col_max' b = [b max(a,[],1)]; case 'col_median' b = [b median(a,1)]; case 'size' b = [b size(a)]; case 'sum' b = [b sum(a(:))]; otherwise error('Desired statistics not supported') end end end return
github
jacksky64/imageProcessing-master
cnormc.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/cnormc.m
2,947
utf_8
556f4711a78ff297eba70268c848f9dd
%CNORMC Classifier normalisation for ML posterior probabilities % % W = CNORMC(W,A) % % INPUT % W Classifier mapping % A Labeled dataset % % OUTPUT % W Scaled classifier mapping % % DESCRIPTION % The mapping W is scaled such that the likelihood of the posterior % probabilities of the samples in A, estimated by A*W*SIGM, are maximized. % This is particularly suitable for two-class discriminants. To obtain % consistent classifiers in PRTools, it is necessary to call CNORMC in the % construction of all classifiers that output distances instead of densities % or posterior probability estimates. % % If A has soft labels or target labels, W is returned without change. % % SEE ALSO % MAPPINGS, DATASETS, CLASSC % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Sciences, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands % $Id: cnormc.m,v 1.5 2008/07/03 09:14:02 duin Exp $ function w = cnormc (w,a) prtrace(mfilename); % Parameters reg = 1e-7; % Regularization, important for non-overlapping classes. epsilon = 1e-6; % Stop when change in likelihood falls below this. % Check arguments. if (~ismapping(w)) error('first argument should be a mapping'); end if (islabtype(a,'targets')) prwarning(4,'Dataset has target labels, not taking any action.'); return; end if (islabtype(a,'soft')) prwarning(4,'Dataset has soft labels, scaling optimization is not yet implemented.'); w = setscale(w,0.01); % just a trial w = setout_conv(w,1); return; end [m,k,c] = getsize(a); nlab = getnlab(a); p = getprior(a,0); mapped = double(a*w); % Calculate mapping outputs. if (c == 2) & (size(mapped,2) == 1) mapped = [mapped -mapped]; % Old (perhaps unnecessary) transformation % for classifiers that give distances. end mapped = mapped(m*(nlab-1)+[1:m]'); % Select output corresponding to label % (uses 1D matrix addressing). % Initialise variables. scale = 1e-10; likelihood = -inf; likelihood_new = -realmax; % Iteratively update scale to maximize likelihood of outputs. while (abs(likelihood_new - likelihood) > epsilon) % Class A is, for each object, the class the object is classified as; % class B stands for all other classes. pax = sigm(mapped*scale,1); % Estimate of P(class A|x). pbx = 1 - pax; % Estimate of P(class B|x). likelihood = likelihood_new; likelihood_new = mean(p(nlab)'.*log(pax + realmin)) - reg*log(scale+1); % Gradient step to maximize likelihood. scale = scale + ((p(nlab)'.*pbx)' * mapped - reg*m/(scale+1)) / ... ((p(nlab)'.*mapped.*pax)'*(mapped.*pbx) - ... m*reg/((scale+1)*(scale+1)) + realmin); end % Dirty trick to avoid 0 and inf. scale = min(max(scale,0.1/(std(mapped)+1e-16)),1e16); % Adjust mapping: set scale and set output conversion to SIGM(1). w = setscale(w,scale); w = setout_conv(w,1); return;
github
jacksky64/imageProcessing-master
immoments.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/immoments.m
10,334
utf_8
1b7a586afad05f118e8011c8bf59958a
%IMMOMENTS PRTools routine for computing central moments of object images % % M = IMMOMENTS(A,TYPE,MOMENTS) % % INPUT % A Dataset with object images dataset % TYPE Desired type of moments % MOMENTS Desired moments % % OUTPUT % M Dataset with moments replacing images % % DESCRIPTION % Computes for the image A a (1*N) vector M moments as defined by TYPE % and MOMENTS. The following types are supported: % % TYPE = 'none' Standard moments as specified in the Nx2 array MOMENTS. % Moments are computed with respect to the image center. % This is the default for TYPE. % Default MOMENTS = [1 0; 0 1]; % TYPE = 'central' Central moments as specified in the Nx2 array MOMENTS. % Moments are computed with respect to the image mean % Default MOMENTS = [2 0; 1 1; 0 2], which computes % the variance in the x-direction (horizontal), the % covariance between x and y and the variance in the % y-direction (vertical). % TYPE = 'scaled' Scale-invariant moments as specified in the Nx2 array % MOMENTS. Default MOMENTS = [2 0; 1 1; 0 2]. % After: M. Sonka et al., % Image processing, analysis and machine vision. % TYPE = 'hu' Calculates 7 moments of Hu, invariant to translation, % rotation and scale. % After: M. Sonka et al., % Image processing, analysis and machine vision. % TYPE = 'zer' Calculates the Zernike moments up to the order as % specified in the scalar MOMENTS (1 <= MOMENTS <= 12). % MOMENTS = 12 generates in total 47 moments. % After: A. Khotanzad and Y.H. Hong, Invariant image % recognition by Zernike moments, IEEE-PAMI, vol. 12, % no. 5, 1990, 489-497. % % See DATASETS % Copyright: D. de Ridder, R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function b = immoments(a,type,mom) if nargin < 3, mom = []; end if nargin < 2 | isempty(type), type = 'none'; end isobjim(a); [m,k] = size(a); im = data2im(a); for i = 1:m imi = im(:,:,i); switch type case {'none'} if isempty(mom) mom = [1 0; 0 1]; end mout = moments(imi,mom(:,1),mom(:,2),0,0); case {'central'} if isempty(mom) mom = [2 0; 1 1; 0 2]; end mout = moments(imi,mom(:,1),mom(:,2),1,0); case {'scaled'} if isempty(mom) mom = [2 0; 1 1; 0 2]; end mout = moments(imi,mom(:,1)',mom(:,2)',1,1); case {'hu' 'Hu'} mout = hu_moments(imi); case {'zer' 'zernike' 'Zernike'} if isempty(mom) mom = 12; end mout = zernike_moments(imi,mom); otherwise error('Moments should be of type none, central, scaled, hu or zer') end if i==1 b = zeros(m,length(mout)); end b(i,:) = mout; end b = setdata(a,b); % M = MOMENTS (IM, P, Q, CENTRAL, SCALED) % % Calculates moments of order (P+Q) (can be arrays of indentical length) % on image IM. If CENTRAL is set to 1 (default: 0), returns translation- % invariant moments; if SCALED is set to 1 (default: 0), returns scale- % invariant moments. % % After: M. Sonka et al., Image processing, analysis and machine vision. function m = moments (im,p,q,central,scaled) if (nargin < 5), scaled = 0; end; if (nargin < 4), central = 0; end; if (nargin < 3) error ('Insufficient number of parameters.'); end; if (length(p) ~= length(q)) error ('Arrays P and Q should have equal length.'); end; if (scaled & ~central) error ('Scale-invariant moments should always be central.'); end; % xx, yy are grids with co-ordinates [xs,ys] = size(im); [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2); if (central) % Calculate zeroth and first order moments m00 = sum(sum(im)); m10 = sum(sum(im.*xx)); m01 = sum(sum(im.*yy)); % This gives the center of gravity xc = m10/m00; yc = m01/m00; % Subtract this from the grids to center the object xx = xx - xc; yy = yy - yc; end; % Calculate moment(s) (p,q). for i = 1:length(p) m(i) = sum(sum((xx.^p(i)).*(yy.^q(i)).*im)); end; if (scaled) c = 1 + (p+q)/2; % m00 should be known, as scaled moments are always central m = m ./ (m00.^c); end; return; % M = HU_MOMENTS (IM) % % Calculates 7 moments of Hu on image IM, invariant to translation, % rotation and scale. % % After: M. Sonka et al., Image processing, analysis and machine vision. function m = hu_moments (im) p = [ 1 0 2 1 2 0 3 ]; q = [ 1 2 0 2 1 3 0 ]; n = moments(im,p,q,1,1); m(1) = n(2) + n(3); m(2) = (n(3) - n(2))^2 + 4*n(1)^2; m(3) = (n(7) - 3*n(4))^2 + (3*n(5) - n(6))^2; m(4) = (n(7) + n(4))^2 + ( n(5) + n(6))^2; m(5) = ( n(7) - 3*n(4)) * (n(7) + n(4)) * ... ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) + ... (3*n(5) - n(6)) * (n(5) + n(6)) * ... (3*(n(7) + n(4))^2 - (n(5) + n(6))^2); m(6) = (n(3) - n(2)) * ((n(7) + n(4))^2 - (n(5) + n(6))^2) + ... 4*n(1) * (n(7)+n(4)) * (n(5)+n(6)); m(7) = (3*n(5) - n(6)) * (n(7) + n(4)) * ... ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) - ... ( n(7) - 3*n(4)) * (n(5) + n(6)) * ... (3*(n(7) + n(4))^2 - (n(5) + n(6))^2); return; % M = ZERNIKE_MOMENTS (IM, ORDER) % % Calculates Zernike moments up to and including ORDER (<= 12) on image IM. % Default: ORDER = 12. function m = zernike_moments (im, order) if (nargin < 2), order = 12; end; if (order < 1 | order > 12), error ('order should be 1..12'); end; % xx, yy are grids with co-ordinates [xs,ys] = size(im); [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2); % Calculate center of mass and distance of any pixel to it m = moments (im,[0 1 0],[0 0 1],0,0); xc = m(2)/m(1); yc = m(3)/m(1); xx = xx - xc; yy = yy - yc; len = sqrt(xx.^2+yy.^2); max_len = max(max(len)); % Map pixels to unit circle; prevent divide by zero. rho = len/max_len; rho_tmp = rho; rho_tmp(find(rho==0)) = 1; theta = acos((xx/max_len)./rho_tmp); % Flip angle for pixels above center of mass yneg = length(find(yy(:,1)<0)); theta(:,1:yneg) = 2*pi - theta(:,1:yneg); % Calculate coefficients c = zeros(order,order); s = zeros(order,order); i = 1; for n = 2:order for l = n:-2:0 r = polynomial (n,l,rho); c = sum(sum(r.*cos(l*theta)))*((n+1)/(pi*max_len^2)); s = sum(sum(r.*sin(l*theta)))*((n+1)/(pi*max_len^2)); m(i) = sqrt(c^2+s^2); i = i + 1; end; end; return function p = polynomial (n,l,rho) switch (n) case 2, switch (l) case 0, p = 2*(rho.^2)-1; case 2, p = (rho.^2); end; case 3, switch (l) case 1, p = 3*(rho.^3)-2*rho; case 3, p = (rho.^3); end; case 4, switch (l) case 0, p = 6*(rho.^4)-6*(rho.^2)+1; case 2, p = 4*(rho.^4)-3*(rho.^2); case 4, p = (rho.^4); end; case 5, switch (l) case 1, p = 10*(rho.^5)-12*(rho.^3)+3*rho; case 3, p = 5*(rho.^5)- 4*(rho.^3); case 5, p = (rho.^5); end; case 6, switch (l) case 0, p = 20*(rho.^6)-30*(rho.^4)+12*(rho.^2)-1; case 2, p = 15*(rho.^6)-20*(rho.^4)+ 6*(rho.^2); case 4, p = 6*(rho.^6)- 5*(rho.^4); case 6, p = (rho.^6); end; case 7, switch (l) case 1, p = 35*(rho.^7)-60*(rho.^5)+30*(rho.^3)-4*rho; case 3, p = 21*(rho.^7)-30*(rho.^5)+10*(rho.^3); case 5, p = 7*(rho.^7)- 6*(rho.^5); case 7, p = (rho.^7); end; case 8, switch (l) case 0, p = 70*(rho.^8)-140*(rho.^6)+90*(rho.^4)-20*(rho.^2)+1; case 2, p = 56*(rho.^8)-105*(rho.^6)+60*(rho.^4)-10*(rho.^2); case 4, p = 28*(rho.^8)- 42*(rho.^6)+15*(rho.^4); case 6, p = 8*(rho.^8)- 7*(rho.^6); case 8, p = (rho.^8); end; case 9, switch (l) case 1, p = 126*(rho.^9)-280*(rho.^7)+210*(rho.^5)-60*(rho.^3)+5*rho; case 3, p = 84*(rho.^9)-168*(rho.^7)+105*(rho.^5)-20*(rho.^3); case 5, p = 36*(rho.^9)- 56*(rho.^7)+ 21*(rho.^5); case 7, p = 9*(rho.^9)- 8*(rho.^7); case 9, p = (rho.^9); end; case 10, switch (l) case 0, p = 252*(rho.^10)-630*(rho.^8)+560*(rho.^6)-210*(rho.^4)+30*(rho.^2)-1; case 2, p = 210*(rho.^10)-504*(rho.^8)+420*(rho.^6)-140*(rho.^4)+15*(rho.^2); case 4, p = 129*(rho.^10)-252*(rho.^8)+168*(rho.^6)- 35*(rho.^4); case 6, p = 45*(rho.^10)- 72*(rho.^8)+ 28*(rho.^6); case 8, p = 10*(rho.^10)- 9*(rho.^8); case 10, p = (rho.^10); end; case 11, switch (l) case 1, p = 462*(rho.^11)-1260*(rho.^9)+1260*(rho.^7)-560*(rho.^5)+105*(rho.^3)-6*rho; case 3, p = 330*(rho.^11)- 840*(rho.^9)+ 756*(rho.^7)-280*(rho.^5)+ 35*(rho.^3); case 5, p = 165*(rho.^11)- 360*(rho.^9)+ 252*(rho.^7)- 56*(rho.^5); case 7, p = 55*(rho.^11)- 90*(rho.^9)+ 36*(rho.^7); case 9, p = 11*(rho.^11)- 10*(rho.^9); case 11, p = (rho.^11); end; case 12, switch (l) case 0, p = 924*(rho.^12)-2772*(rho.^10)+3150*(rho.^8)-1680*(rho.^6)+420*(rho.^4)-42*(rho.^2)+1; case 2, p = 792*(rho.^12)-2310*(rho.^10)+2520*(rho.^8)-1260*(rho.^6)+280*(rho.^4)-21*(rho.^2); case 4, p = 495*(rho.^12)-1320*(rho.^10)+1260*(rho.^8)- 504*(rho.^6)+ 70*(rho.^4); case 6, p = 220*(rho.^12)- 495*(rho.^10)+ 360*(rho.^8)- 84*(rho.^6); case 8, p = 66*(rho.^12)- 110*(rho.^10)+ 45*(rho.^8); case 10, p = 12*(rho.^12)- 11*(rho.^10); case 12, p = (rho.^12); end; end; return
github
jacksky64/imageProcessing-master
treec.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/treec.m
16,984
utf_8
29eeede09436dd3d3938e71eb5adf663
%TREEC Build a decision tree classifier % % W = TREEC(A,CRIT,PRUNE,T) % % Computation of a decision tree classifier out of a dataset A using % a binary splitting criterion CRIT: % INFCRIT - information gain % MAXCRIT - purity (default) % FISHCRIT - Fisher criterion % % Pruning is defined by prune: % PRUNE = -1 pessimistic pruning as defined by Quinlan. % PRUNE = -2 testset pruning using the dataset T, or, if not % supplied, an artificially generated testset of 5 x size of % the training set based on parzen density estimates. % see PARZENML and GENDATP. % PRUNE = 0 no pruning (default). % PRUNE > 0 early pruning, e.g. prune = 3 % PRUNE = 10 causes heavy pruning. % % If CRIT or PRUNE are set to NaN they are optimised by REGOPTC. % % see also DATASETS, MAPPINGS, TREE_MAP, REGOPTC % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: treec.m,v 1.9 2009/07/26 18:52:08 duin Exp $ function w = treec(a,crit,prune,t) prtrace(mfilename); % When no input data is given, an empty tree is defined: if nargin == 0 | isempty(a) if nargin <2, w = mapping('treec'); elseif nargin < 3, w = mapping('treec',{crit}); elseif nargin < 4, w = mapping('treec',{crit,prune}); else, w = mapping('treec',{crit,prune,t}); end w = setname(w,'Decision Tree'); return end if nargin < 3, prune = []; end if nargin < 2, crit = []; end parmin_max = [1,3;-1,10]; optcrit = inf; if isnan(crit) & isnan(prune) % optimize criterion and pruning, grid search global REGOPT_OPTCRIT REGOPT_PARS for n = 1:3 defs = {n,0}; v = regoptc(a,mfilename,{crit,prune},defs,[2],parmin_max,testc([],'soft'),[0,0]); if REGOPT_OPTCRIT < optcrit w = v; optcrit = REGOPT_OPTCRIT; regoptpars = REGOPT_PARS; end end REGOPT_PARS = regoptpars; elseif isnan(crit) % optimize criterion defs = {1,0}; w = regoptc(a,mfilename,{crit,prune},defs,[1],parmin_max,testc([],'soft'),[0,0]); elseif isnan(prune) % optimize pruning defs = {1,0}; w = regoptc(a,mfilename,{crit,prune},defs,[2],parmin_max,testc([],'soft'),[0,0]); else % training for given parameters islabtype(a,'crisp'); isvaldfile(a,1,2); % at least 1 object per class, 2 classes %a = testdatasize(a); a = dataset(a); % First get some useful parameters: [m,k,c] = getsize(a); nlab = getnlab(a); % Define the splitting criterion: if nargin == 1 | isempty(crit), crit = 2; end if ~isstr(crit) if crit == 0 | crit == 1, crit = 'infcrit'; elseif crit == 2, crit = 'maxcrit'; elseif crit == 3, crit = 'fishcrit'; else, error('Unknown criterion value'); end end % Now the training can really start: if (nargin == 1) | (nargin == 2) tree = maketree(+a,nlab,c,crit); elseif nargin > 2 % We have to apply a pruning strategy: if prune == -1, prune = 'prunep'; end if prune == -2, prune = 'prunet'; end % The strategy can be prunep/prunet: if isstr(prune) tree = maketree(+a,nlab,c,crit); if prune == 'prunep' tree = prunep(tree,a,nlab); elseif prune == 'prunet' if nargin < 4 t = gendatp(a,5*sum(nlab==1)); end tree = prunet(tree,t); else error('unknown pruning option defined'); end else % otherwise the tree is just cut after level 'prune' tree = maketree(+a,nlab,c,crit,prune); end else error('Wrong number of parameters') end % Store the results: w = mapping('tree_map','trained',{tree,1},getlablist(a),k,c); w = setname(w,'Decision Tree'); w = setcost(w,a); end return %MAKETREE General tree building algorithm % % tree = maketree(A,nlab,c,crit,stop) % % Constructs a binary decision tree using the criterion function % specified in the string crit ('maxcrit', 'fishcrit' or 'infcrit' % (default)) for a set of objects A. stop is an optional argument % defining early stopping according to the Chi-squared test as % defined by Quinlan [1]. stop = 0 (default) gives a perfect tree % (no pruning) stop = 3 gives a pruned version stop = 10 a heavily % pruned version. % % Definition of the resulting tree: % % tree(n,1) - feature number to be used in node n % tree(n,2) - threshold t to be used % tree(n,3) - node to be processed if value <= t % tree(n,4) - node to be processed if value > t % tree(n,5:4+c) - aposteriori probabilities for all classes in % node n % % If tree(n,3) == 0, stop, class in tree(n,1) % % This is a low-level routine called by treec. % % See also infstop, infcrit, maxcrit, fishcrit and mapt. % Authors: Guido te Brake, TWI/SSOR, Delft University of Technology % R.P.W. Duin, TN/PH, Delft University of Technology % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function tree = maketree(a,nlab,c,crit,stop) prtrace(mfilename); [m,k] = size(a); if nargin < 5, stop = 0; end; if nargin < 4, crit = []; end; if isempty(crit), crit = 'infcrit'; end; % Construct the tree: % When all objects have the same label, create an end-node: if all([nlab == nlab(1)]) % Avoid giving 0-1 probabilities, but 'regularize' them a bit using % a 'uniform' Bayesian prior: p = ones(1,c)/(m+c); p(nlab(1)) = (m+1)/(m+c); tree = [nlab(1),0,0,0,p]; else % now the tree is recursively constructed further: [f,j,t] = feval(crit,+a,nlab); % use desired split criterion if isempty(t) crt = 0; else crt = infstop(+a,nlab,j,t); % use desired early stopping criterion end p = sum(expandd(nlab),1); if length(p) < c, p = [p,zeros(1,c-length(p))]; end % When the stop criterion is not reached yet, we recursively split % further: if crt > stop % Make the left branch: J = find(a(:,j) <= t); tl = maketree(+a(J,:),nlab(J),c,crit,stop); % Make the right branch: K = find(a(:,j) > t); tr = maketree(+a(K,:),nlab(K),c,crit,stop); % Fix the node labelings before the branches can be 'glued' % together to a big tree: [t1,t2] = size(tl); tl = tl + [zeros(t1,2) tl(:,[3 4])>0 zeros(t1,c)]; [t3,t4] = size(tr); tr = tr + (t1+1)*[zeros(t3,2) tr(:,[3 4])>0 zeros(t3,c)]; % Make the complete tree: the split-node and the branches: tree= [[j,t,2,t1+2,(p+1)/(m+c)]; tl; tr]; else % We reached the stop criterion, so make an end-node: [mt,cmax] = max(p); tree = [cmax,0,0,0,(p+1)/(m+c)]; end end return %MAXCRIT Maximum entropy criterion for best feature split. % % [f,j,t] = maxcrit(A,nlabels) % % Computes the value of the maximum purity f for all features over % the data set A given its numeric labels. j is the optimum feature, % t its threshold. This is a low level routine called for constructing % decision trees. % % [1] L. Breiman, J.H. Friedman, R.A. Olshen, and C.J. Stone, % Classification and regression trees, Wadsworth, California, 1984. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function [f,j,t] = maxcrit(a,nlab) prtrace(mfilename); [m,k] = size(a); c = max(nlab); % -variable T is an (2c)x k matrix containing: % minimum feature values class 1 % maximum feature values class 1 % minimum feature values class 2 % maximum feature values class 2 % etc. % -variable R (same size) contains: % fraction of objects which is < min. class 1. % fraction of objects which is > max. class 1. % fraction of objects which is < min. class 2. % fraction of objects which is > max. class 2. % etc. % These values are collected and computed in the next loop: T = zeros(2*c,k); R = zeros(2*c,k); for j = 1:c L = (nlab == j); if sum(L) == 0 T([2*j-1:2*j],:) = zeros(2,k); R([2*j-1:2*j],:) = zeros(2,k); else T(2*j-1,:) = min(a(L,:),[],1); R(2*j-1,:) = sum(a < ones(m,1)*T(2*j-1,:),1); T(2*j,:) = max(a(L,:),[],1); R(2*j,:) = sum(a > ones(m,1)*T(2*j,:),1); end end % From R the purity index for all features is computed: G = R .* (m-R); % and the best feature is found: [gmax,tmax] = max(G,[],1); [f,j] = max(gmax); Tmax = tmax(j); if Tmax ~= 2*floor(Tmax/2) t = (T(Tmax,j) + max(a(find(a(:,j) < T(Tmax,j)),j)))/2; else t = (T(Tmax,j) + min(a(find(a(:,j) > T(Tmax,j)),j)))/2; end if isempty(t) [f,j,t] = infcrit(a,nlab); prwarning(3,'Maxcrit not feasible for decision tree, infcrit is used') end return %INFCRIT The information gain and its the best feature split. % % [f,j,t] = infcrit(A,nlabels) % % Computes over all features the information gain f for its best % threshold from the dataset A and its numeric labels. For f=1: % perfect discrimination, f=0: complete mixture. j is the optimum % feature, t its threshold. This is a lowlevel routine called for % constructing decision trees. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function [g,j,t] = infcrit(a,nlab) prtrace(mfilename); [m,k] = size(a); c = max(nlab); mininfo = ones(k,2); % determine feature domains of interest [sn,ln] = min(a,[],1); [sx,lx] = max(a,[],1); JN = (nlab(:,ones(1,k)) == ones(m,1)*nlab(ln)') * realmax; JX = -(nlab(:,ones(1,k)) == ones(m,1)*nlab(lx)') * realmax; S = sort([sn; min(a+JN,[],1); max(a+JX,[],1); sx]); % S(2,:) to S(3,:) are interesting feature domains P = sort(a); Q = (P >= ones(m,1)*S(2,:)) & (P <= ones(m,1)*S(3,:)); % these are the feature values in those domains for f=1:k, % repeat for all features af = a(:,f); JQ = find(Q(:,f)); SET = P(JQ,f)'; if JQ(1) ~= 1 SET = [P(JQ(1)-1,f), SET]; end n = length(JQ); if JQ(n) ~= m SET = [SET, P(JQ(n)+1,f)]; end n = length(SET) -1; T = (SET(1:n) + SET(2:n+1))/2; % all possible thresholds L = zeros(c,n); R = L; % left and right node object counts per class for j = 1:c J = find(nlab==j); mj = length(J); if mj == 0 L(j,:) = realmin*ones(1,n); R(j,:) = L(j,:); else L(j,:) = sum(repmat(af(J),1,n) <= repmat(T,mj,1)) + realmin; R(j,:) = sum(repmat(af(J),1,n) > repmat(T,mj,1)) + realmin; end end infomeas = - (sum(L .* log10(L./(ones(c,1)*sum(L)))) ... + sum(R .* log10(R./(ones(c,1)*sum(R))))) ... ./ (log10(2)*(sum(L)+sum(R))); % criterion value for all thresholds [mininfo(f,1),j] = min(infomeas); % finds the best mininfo(f,2) = T(j); % and its threshold end g = 1-mininfo(:,1)'; [finfo,j] = min(mininfo(:,1)); % best over all features t = mininfo(j,2); % and its threshold return %FISHCRIT Fisher's Criterion and its best feature split % % [f,j,t] = fishcrit(A,nlabels) % % Computes the value of the Fisher's criterion f for all features % over the dataset A with given numeric labels. Two classes only. j % is the optimum feature, t its threshold. This is a lowlevel % routine called for constructing decision trees. % Copyright R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function [f,j,t] = fishcrit(a,nlab) prtrace(mfilename); [m,k] = size(a); c = max(nlab); if c > 2 error('Not more than 2 classes allowed for Fisher Criterion') end % Get the mean and variances of both the classes: J1 = find(nlab==1); J2 = find(nlab==2); u = (mean(a(J1,:),1) - mean(a(J2,:),1)).^2; s = std(a(J1,:),0,1).^2 + std(a(J2,:),0,1).^2 + realmin; % The Fisher ratio becomes: f = u ./ s; % Find then the best feature: [ff,j] = max(f); % Given the feature, compute the threshold: m1 = mean(a(J1,j),1); m2 = mean(a(J2,j),1); w1 = m1 - m2; w2 = (m1*m1-m2*m2)/2; if abs(w1) < eps % the means are equal, so the Fisher % criterion (should) become 0. Let us set the thresold % halfway the domain t = (max(a(J1,j),[],1) + min(a(J2,j),[],1)) / 2; else t = w2/w1; end return %INFSTOP Quinlan's Chi-square test for early stopping % % crt = infstop(A,nlabels,j,t) % % Computes the Chi-square test described by Quinlan [1] to be used % in maketree for forward pruning (early stopping) using dataset A % and its numeric labels. j is the feature used for splitting and t % the threshold. % % [1] J.R. Quinlan, Simplifying Decision Trees, % Int. J. Man - Machine Studies, vol. 27, 1987, pp. 221-234. % % See maketree, treec, classt, prune % Guido te Brake, TWI/SSOR, TU Delft. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function crt = infstop(a,nlab,j,t) prtrace(mfilename); [m,k] = size(a); c = max(nlab); aj = a(:,j); ELAB = expandd(nlab); L = sum(ELAB(aj <= t,:),1) + 0.001; R = sum(ELAB(aj > t,:),1) + 0.001; LL = (L+R) * sum(L) / m; RR = (L+R) * sum(R) / m; crt = sum(((L-LL).^2)./LL + ((R-RR).^2)./RR); return %PRUNEP Pessimistic pruning of a decision tree % % tree = prunep(tree,a,nlab,num) % % Must be called by giving a tree and the training set a. num is the % starting node, if omitted pruning starts at the root. Pessimistic % pruning is defined by Quinlan. % % See also maketree, treec, mapt % Guido te Brake, TWI/SSOR, TU Delft. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function tree = prunep(tree,a,nlab,num) prtrace(mfilename); if nargin < 4, num = 1; end; [N,k] = size(a); c = size(tree,2)-4; if tree(num,3) == 0, return, end; w = mapping('treec','trained',{tree,num},[1:c]',k,c); ttt=tree_map(dataset(a,nlab),w); J = testc(ttt)*N; EA = J + nleaves(tree,num)./2; % expected number of errors in tree P = sum(expandd(nlab,c),1); % distribution of classes %disp([length(P) c]) [pm,cm] = max(P); % most frequent class E = N - pm; % errors if substituted by leave SD = sqrt((EA * (N - EA))/N); if (E + 0.5) < (EA + SD) % clean tree while removing nodes [mt,kt] = size(tree); nodes = zeros(mt,1); nodes(num) = 1; n = 0; while sum(nodes) > n; % find all nodes to be removed n = sum(nodes); J = find(tree(:,3)>0 & nodes==1); nodes(tree(J,3)) = ones(length(J),1); nodes(tree(J,4)) = ones(length(J),1); end tree(num,:) = [cm 0 0 0 P/N]; nodes(num) = 0; nc = cumsum(nodes); J = find(tree(:,3)>0);% update internal references tree(J,[3 4]) = tree(J,[3 4]) - reshape(nc(tree(J,[3 4])),length(J),2); tree = tree(~nodes,:);% remove obsolete nodes else K1 = find(a(:,tree(num,1)) <= tree(num,2)); K2 = find(a(:,tree(num,1)) > tree(num,2)); tree = prunep(tree,a(K1,:),nlab(K1),tree(num,3)); tree = prunep(tree,a(K2,:),nlab(K2),tree(num,4)); end return %PRUNET Prune tree by testset % % tree = prunet(tree,a) % % The test set a is used to prune a decision tree. % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function tree = prunet(tree,a) prtrace(mfilename); [m,k] = size(a); [n,s] = size(tree); c = s-4; erre = zeros(1,n); deln = zeros(1,n); w = mapping('treec','trained',{tree,1},[1:c]',k,c); [f,lab,nn] = tree_map(a,w); % bug, this works only if a is dataset, labels ??? [fmax,cmax] = max(tree(:,[5:4+c]),[],2); nngood = nn([1:n]'+(cmax-1)*n); errn = sum(nn,2) - nngood;% errors in each node sd = 1; while sd > 0 erre = zeros(n,1); deln = zeros(1,n); endn = find(tree(:,3) == 0)'; % endnodes pendl = max(tree(:,3*ones(1,length(endn)))' == endn(ones(n,1),:)'); pendr = max(tree(:,4*ones(1,length(endn)))' == endn(ones(n,1),:)'); pend = find(pendl & pendr); % parents of two endnodes erre(pend) = errn(tree(pend,3)) + errn(tree(pend,4)); deln = pend(find(erre(pend) >= errn(pend))); % nodes to be leaved sd = length(deln); if sd > 0 tree(tree(deln,3),:) = -1*ones(sd,s); tree(tree(deln,4),:) = -1*ones(sd,s); tree(deln,[1,2,3,4]) = [cmax(deln),zeros(sd,3)]; end end return %NLEAVES Computes the number of leaves in a decision tree % % number = nleaves(tree,num) % % This procedure counts the number of leaves in a (sub)tree of the % tree by using num. If num is omitted, the root is taken (num = 1). % % This is a utility used by maketree. % Guido te Brake, TWI/SSOR, TU Delft % Copyright: R.P.W. Duin, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands function number = nleaves(tree,num) prtrace(mfilename); if nargin < 2, num = 1; end if tree(num,3) == 0 number = 1 ; else number = nleaves(tree,tree(num,3)) + nleaves(tree,tree(num,4)); end return
github
jacksky64/imageProcessing-master
getfeat.m
.m
imageProcessing-master/Matlab PRTools/prtools_com/prtools/getfeat.m
855
utf_8
d0e5811fcde6732e0e08c00c43e50989
%GETFEAT Get feature labels of a dataset or a mapping % % LABELS = GETFEAT(A) % LABELS = GETFEAT(W) % % INPUT % A,W Dataset or mapping % % OUTPUT % LABELS Label vector with feature labels % % DESCRIPTION % Returns the labels of the features in the dataset A or the labels % assigned by the mapping W. % % Note that for a mapping W, getfeat(W) is effectively the same as GETLAB(W). % % SEE ALSO % DATASETS, MAPPINGS, GETLAB % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: getfeat.m,v 1.2 2006/03/08 22:06:58 duin Exp $ function labels = getfeat(par) if isdataset(par) | isdatafile(par) labels = getfeatlab(par); elseif isa(par,'mapping') labels = getlabels(par); else error([newline 'Dataset or mapping expected.']) end return;