├── scriptfcn.m~ ├── scriptdisc.m ├── .gitattributes ├── liveDemoIS.mlx ├── svmtrain.mexw64 ├── svmpredict.mexw64 ├── .gitignore ├── exampleWeb.m ├── older_scripts ├── instancesProjectionInterfaceWeb.m ├── boundOutliers.m ├── autoNormalize.m ├── checkCorrelation.m ├── unigoodreg.m ├── example_ksm.m ├── run_bifel.m ├── run_bifel[2305843009224844497].m ├── CVNND.m ├── run_regression.m ├── example_maxflow2.m ├── generate_evco2data.m ├── run_timetable.m ├── clusterFeatureSelection.m └── purifyInst.m ├── options.json ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── testInterface.m ├── CLOISTER.m ├── scriptweb.m ├── FILTER.m ├── run_quantum.m ├── TRACEtest.m ├── example.m ├── PYTHIAtest.m ├── PRELIM.m ├── PILOT.m ├── scriptcsv.m ├── scriptpng.m ├── SIFTED2.m ├── SIFTED.m ├── PYTHIA2.m ├── scriptfcn.m ├── exploreIS.m ├── PYTHIA.m ├── TRACE.m ├── README.md └── LICENSE /scriptfcn.m~: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /scriptdisc.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andremun/InstanceSpace/HEAD/scriptdisc.m -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /liveDemoIS.mlx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andremun/InstanceSpace/HEAD/liveDemoIS.mlx -------------------------------------------------------------------------------- /svmtrain.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andremun/InstanceSpace/HEAD/svmtrain.mexw64 -------------------------------------------------------------------------------- /svmpredict.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andremun/InstanceSpace/HEAD/svmpredict.mexw64 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.asv 2 | *.zip 3 | *.png 4 | *.pdf 5 | *.mat 6 | *.db 7 | *.csv 8 | old_versions/*.* 9 | old_versions 10 | *.json 11 | -------------------------------------------------------------------------------- /exampleWeb.m: -------------------------------------------------------------------------------- 1 | function exampleWeb(rootdir) 2 | 3 | try 4 | model = trainIS(rootdir); 5 | catch ME 6 | disp('EOF:ERROR'); 7 | rethrow(ME) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /older_scripts/instancesProjectionInterfaceWeb.m: -------------------------------------------------------------------------------- 1 | function instancesProjectionInterfaceWeb(rootdir) 2 | try 3 | testIS(rootdir); 4 | catch ME 5 | disp('EOF:ERROR'); 6 | rethrow(ME) 7 | end 8 | end -------------------------------------------------------------------------------- /older_scripts/boundOutliers.m: -------------------------------------------------------------------------------- 1 | function [X, out] = boundOutliers(X) 2 | 3 | disp('-> Removing extreme outliers from the feature values.'); 4 | out.medval = nanmedian(X, 1); 5 | out.iqrange = iqr(X, 1); 6 | out.hibound = out.medval + 5.*out.iqrange; 7 | out.lobound = out.medval - 5.*out.iqrange; 8 | himask = bsxfun(@gt,X,out.hibound); 9 | lomask = bsxfun(@lt,X,out.lobound); 10 | X = X.*~(himask | lomask) + bsxfun(@times,himask,out.hibound) + ... 11 | bsxfun(@times,lomask,out.lobound); 12 | 13 | end -------------------------------------------------------------------------------- /options.json: -------------------------------------------------------------------------------- 1 | {"perf":{"MaxPerf":false,"AbsPerf":false,"epsilon":0.05},"general":{"betaThreshold":0.55},"auto":{"preproc":true,"featsel":true},"bound":{"flag":true},"norm":{"flag":true},"diversity":{"flag":false,"threshold":0.3},"corr":{"flag":true,"threshold":3},"clust":{"flag":true,"KDEFAULT":10,"SILTHRESHOLD":0.45,"NTREES":50,"MaxIter":1000,"Replicates":100},"pbldr":{"analytic":false,"ntries":10},"sbound":{"pval":0.05,"cthres":0.7},"oracle":{"cvgrid":10,"maxcvgrid":5,"mincvgrid":-5,"cvfolds":5},"footprint":{"usesim":false,"RHO":10,"PI":0.75,"PCTILE":0.3},"selvars":{"smallscaleflag":false,"smallscale":0.3,"fileidxflag":false,"fileidx":""},"outputs":{"csv":true,"web":false,"png":true}} -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /older_scripts/autoNormalize.m: -------------------------------------------------------------------------------- 1 | function [X,Y,out] = autoNormalize(X, Y) 2 | 3 | nfeats = size(X,2); 4 | nalgos = size(Y,2); 5 | disp('-> Auto-normalizing the data using Box-Cox and Z transformations.'); 6 | out.minX = min(X,[],1); 7 | X = bsxfun(@minus,X,out.minX)+1; 8 | out.lambdaX = zeros(1,nfeats); 9 | out.muX = zeros(1,nfeats); 10 | out.sigmaX = zeros(1,nfeats); 11 | for i=1:nfeats 12 | aux = X(:,i); 13 | idx = isnan(aux); 14 | [aux, out.lambdaX(i)] = boxcox(aux(~idx)); 15 | [aux, out.muX(i), out.sigmaX(i)] = zscore(aux); 16 | X(~idx,i) = aux; 17 | end 18 | 19 | out.minY = min(Y(:)); 20 | Y = (Y-out.minY)+eps; 21 | out.lambdaY = zeros(1,nalgos); 22 | out.muY = zeros(1,nalgos); 23 | out.sigmaY = zeros(1,nalgos); 24 | for i=1:nalgos 25 | aux = Y(:,i); 26 | idx = isnan(aux); 27 | [aux, out.lambdaY(i)] = boxcox(aux(~idx)); 28 | [aux, out.muY(i), out.sigmaY(i)] = zscore(aux); 29 | Y(~idx,i) = aux; 30 | end 31 | 32 | end -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /testInterface.m: -------------------------------------------------------------------------------- 1 | try 2 | rootdir = 'E:/InstanceSpace_Classification/MATILDA_trial/'; 3 | testingDir = strcat(rootdir, 'test/'); 4 | status = mkdir(testingDir); 5 | if status == 0 6 | error('Can not create sub-directory to store testing results. '); 7 | else 8 | source_metadata = fullfile(rootdir, 'metadata_test.csv'); 9 | source_model = fullfile(rootdir, 'model.mat'); 10 | status = copyfile(source_metadata, testingDir); 11 | if status == 0 12 | error('Error: Please place metadata_test inside %s', rootdir ); 13 | end 14 | status = copyfile(source_model, testingDir); 15 | if status == 0 16 | error('Error: could not find model.mat inside %s', rootdir ); 17 | end 18 | 19 | source_options = fullfile(rootdir, 'options.json'); 20 | status = copyfile(source_options, testingDir); 21 | if status == 0 22 | error('Error: could not find options.json inside %s', rootdir ); 23 | end 24 | 25 | testIS(testingDir); 26 | end 27 | catch ME 28 | disp('EOF:ERROR'); 29 | rethrow(ME) 30 | end -------------------------------------------------------------------------------- /older_scripts/checkCorrelation.m: -------------------------------------------------------------------------------- 1 | function [X, out] = checkCorrelation(X,Y,opts) 2 | 3 | [~,nfeats] = size(X); 4 | if nfeats>2 5 | disp('-> Checking for feature correlation with performance.'); 6 | [out.rho,out.p] = corr(X,Y,'rows','pairwise'); 7 | rho = out.rho; 8 | rho(isnan(rho) | (out.p>0.05)) = 0; 9 | [~,row] = sort(abs(rho),1,'descend'); 10 | out.selvars = false(1,nfeats); 11 | testTreshold = false; 12 | while sum(out.selvars)<3 13 | if testTreshold 14 | warning('Feature selection using correlation was too strict. The threshold value was increased automatically by one.') 15 | end 16 | out.selvars(unique(row(1:min(opts.threshold,nfeats),:))) = true; 17 | opts.threshold = opts.threshold + 1; 18 | testTreshold = true; 19 | end 20 | X = X(:,out.selvars); 21 | disp(['-> Keeping ' num2str(size(X,2)) ' out of ' num2str(nfeats) ' features (correlation).']); 22 | else 23 | disp('-> There are less than 3 features to do selection (correlation). Skipping.') 24 | out.p = ones(nfeats,size(Y,2)); 25 | out.rho = NaN.*out.p; 26 | out.selvars = true(1,nfeats); 27 | end 28 | 29 | end -------------------------------------------------------------------------------- /older_scripts/unigoodreg.m: -------------------------------------------------------------------------------- 1 | % probgood = mean(model.data.Ybin,1)'; 2 | % [pgoodsort,idx] = sort(probgood,'descend'); 3 | % model.data.algolabels(idx(pgoodsort>0.1))'; 4 | % 5 | % puniquegood = mean(model.data.Ybin & (sum(model.data.Ybin,2)<=1))'; 6 | % [puniquegoodsort,idx] = sort(puniquegood,'descend'); 7 | % model.data.algolabels(idx(puniquegoodsort>0.01))'; 8 | % 9 | % 10 | % numgoodalgos = sum(model.data.Ybin,2); 11 | % percgoodalgos = mean(bsxfun(@eq,numgoodalgos,1:nalgos)); 12 | % 13 | % 14 | % 15 | % 16 | % model = load('C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Regression\trial\results_r1_main_paper_results\model.mat'); 17 | % scriptfcn; 18 | clf; 19 | h = drawSources(model.pilot.Z,model.data.S); 20 | line([0 0],[-100 100],'LineStyle', '--', 'color', [0.6 0.6 0.6]); 21 | line([-100 100],[0 0],'LineStyle', '--', 'color', [0.6 0.6 0.6]); 22 | text(3.5, 3,'Q1'); 23 | text(-4, 3,'Q2'); 24 | text(3.5,-3,'Q4'); 25 | text(-4,-3,'Q3'); 26 | legend(h, {'BlackBoxData','EvolvedBlackBox','M3C','Repositories'}) 27 | % print(gcf,'-dpng',[rootdir 'distribution_sources_quadrants.png']); 28 | % 29 | % 30 | 31 | rootdir = 'C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Regression\trial\results_r1_main_paper_results\'; 32 | h = zeros(1,3); 33 | for ii=1:length(model.data.algolabels) 34 | clf; 35 | alpha = 0.4; 36 | blue = [0.0 0.0 1.0]; 37 | h(1:2) = drawBinaryPerformance(model.pilot.Z, model.data.Ybin(:,ii), ... 38 | strrep(model.data.algolabels{ii},'_',' ')); 39 | h(3) = drawFootprint(model.trace.good{ii}, blue, alpha); 40 | legend(h,{'GOOD','BAD','FTPRN'}); 41 | print(gcf,'-dpng',[rootdir 'footprint_' model.data.algolabels{ii} '.png']); 42 | end 43 | 44 | 45 | ii = 3; clf; drawBinaryPerformance(model.pilot.Z, presult.Yhat(:,ii), strrep(model.data.algolabels{ii},'_',' ')); -------------------------------------------------------------------------------- /CLOISTER.m: -------------------------------------------------------------------------------- 1 | function out = CLOISTER(X, A, opts) 2 | % ------------------------------------------------------------------------- 3 | % CLOISTER.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | disp(' -> CLOISTER is using correlation to estimate a boundary for the space.'); 15 | 16 | nfeats = size(X,2); 17 | [rho,pval] = corr(X); 18 | rho = rho.*(pvalopts.cthres && sign(Xedge(i,j))~=sign(Xedge(i,k)) 35 | remove(i) = true; 36 | elseif rho(j,k)<-opts.cthres && sign(Xedge(i,j))==sign(Xedge(i,k)) 37 | remove(i) = true; 38 | end 39 | if remove(i) 40 | break; 41 | end 42 | end 43 | if remove(i) 44 | break; 45 | end 46 | end 47 | end 48 | Zedge = Xedge*A'; 49 | Kedge = convhull(Zedge(:,1),Zedge(:,2)); 50 | out.Zedge = Zedge(Kedge,:); 51 | 52 | try 53 | Xecorr = Xedge(~remove,:); 54 | Zecorr = Xecorr*A'; 55 | Kecorr = convhull(Zecorr(:,1),Zecorr(:,2)); 56 | out.Zecorr = Zecorr(Kecorr,:); 57 | catch 58 | disp(' -> The acceptable correlation threshold was too strict.'); 59 | disp(' -> The features are weakely correlated.') 60 | disp(' -> Please consider increasing it.'); 61 | out.Zecorr = out.Zedge; 62 | end 63 | disp('-------------------------------------------------------------------------'); 64 | disp(' -> CLOISTER has completed.'); 65 | 66 | -------------------------------------------------------------------------------- /scriptweb.m: -------------------------------------------------------------------------------- 1 | function scriptweb(container,rootdir) 2 | % ------------------------------------------------------------------------- 3 | % webscript.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | scriptfcn; 15 | 16 | disp('========================================================================='); 17 | disp('-> Writing the data for the web interfase.'); 18 | % ------------------------------------------------------------------------- 19 | writetable(array2table(uint8(255.*parula(256)), ... 20 | 'VariableNames', {'R','G','B'}), ... 21 | [rootdir 'color_table.csv']); 22 | writeArray2CSV(colorscale(container.data.Xraw(:,container.featsel.idx)), ... 23 | container.data.featlabels, ... 24 | container.data.instlabels, ... 25 | [rootdir 'feature_raw_color.csv']); 26 | writeArray2CSV(colorscale(container.data.Yraw), ... 27 | container.data.algolabels, ... 28 | container.data.instlabels, ... 29 | [rootdir 'algorithm_raw_single_color.csv']); 30 | writeArray2CSV(colorscale(container.data.X), ... 31 | container.data.featlabels, ... 32 | container.data.instlabels, ... 33 | [rootdir 'feature_process_color.csv']); 34 | writeArray2CSV(colorscale(container.data.Y), ... 35 | container.data.algolabels, ... 36 | container.data.instlabels, ... 37 | [rootdir 'algorithm_process_single_color.csv']); 38 | writeArray2CSV(colorscaleg(container.data.Yraw), ... 39 | container.data.algolabels, ... 40 | container.data.instlabels, ... 41 | [rootdir 'algorithm_raw_color.csv']); 42 | writeArray2CSV(colorscaleg(container.data.Y), ... 43 | container.data.algolabels, ... 44 | container.data.instlabels, ... 45 | [rootdir 'algorithm_process_color.csv']); 46 | writeArray2CSV(colorscaleg(container.data.numGoodAlgos), ... 47 | {'NumGoodAlgos'}, ... 48 | container.data.instlabels, ... 49 | [rootdir 'good_algos_color.csv']); -------------------------------------------------------------------------------- /FILTER.m: -------------------------------------------------------------------------------- 1 | function [subsetIndex,isDissimilar,isVISA] = FILTER(X,Y,Ybin,opts) 2 | 3 | [ninst,nalgos] = size(Y); 4 | nfeats = size(X,2); 5 | 6 | subsetIndex = false(ninst,1); 7 | isDissimilar = true(ninst,1); 8 | isVISA = false(ninst,1); 9 | gamma = sqrt(nalgos/nfeats)*opts.mindistance; 10 | 11 | for ii=1:ninst 12 | if ~subsetIndex(ii) 13 | for jj=ii+1:ninst 14 | if ~subsetIndex(jj) 15 | Dx = pdist2(X(ii,:),X(jj,:)); 16 | Dy = pdist2(Y(ii,:),Y(jj,:)); 17 | Db = all(Ybin(ii,:) & Ybin(jj,:)); 18 | if Dx <= opts.mindistance 19 | isDissimilar(jj) = false; 20 | switch opts.type 21 | case 'Ftr' 22 | subsetIndex(jj) = true; 23 | case 'Ftr&AP' 24 | if Dy <= gamma 25 | subsetIndex(jj) = true; 26 | isVISA(jj) = false; 27 | else 28 | isVISA(jj) = true; 29 | end 30 | case 'Ftr&Good' 31 | if Db 32 | subsetIndex(jj) = true; 33 | isVISA(jj) = false; 34 | else 35 | isVISA(jj) = true; 36 | end 37 | case 'Ftr&AP&Good' 38 | if Db 39 | if Dy <= gamma 40 | subsetIndex(jj) = true; 41 | isVISA(jj) = false; 42 | else 43 | isVISA(jj) = true; 44 | end 45 | else 46 | isVISA(jj) = true; 47 | end 48 | otherwise 49 | disp('Invalid flag!') 50 | end 51 | end 52 | end 53 | end 54 | end 55 | end 56 | 57 | % Assess the uniformity of the data 58 | D = squareform(pdist(X(~subsetIndex,:))); 59 | ninst = size(D,1); 60 | D(eye(ninst,'logical')) = NaN; 61 | nearest = min(D,[],2,'omitnan'); 62 | model.data.unif = 1-(std(nearest)./mean(nearest)); 63 | disp(['Uniformity of the instance subset: ' num2str(model.data.unif,4)]); 64 | 65 | end -------------------------------------------------------------------------------- /run_quantum.m: -------------------------------------------------------------------------------- 1 | rootdir = './trial_quantum/'; 2 | 3 | opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 4 | opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure 5 | opts.perf.epsilon = 0.25; % Threshold of good performance 6 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 7 | 8 | opts.parallel.flag = false; 9 | opts.parallel.ncores = 2; 10 | 11 | opts.auto.preproc = false; % Automatic preprocessing on. Set to false if you don't want any preprocessing 12 | opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't 13 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 14 | 15 | opts.sifted.flag = false; % Automatic feature selectio on. Set to false if you don't want any feature selection. 16 | opts.sifted.K = 10; 17 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 18 | opts.sifted.MaxIter = 1000; 19 | opts.sifted.Replicates = 100; 20 | 21 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 22 | opts.pilot.ntries = 5; % Number of attempts carried out by PBLDR 23 | 24 | opts.cloister.pval = 0.05; 25 | opts.cloister.cthres = 0.7; 26 | 27 | opts.pythia.cvfolds = 2; 28 | opts.pythia.ispolykrnl = false; 29 | opts.pythia.useweights = false; 30 | opts.pythia.uselibsvm = false; 31 | 32 | opts.trace.usesim = false; % Use the actual or simulated data to calculate the footprints 33 | opts.trace.PI = 0.55; % Purity threshold 34 | 35 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 36 | opts.selvars.smallscale = 1; % Percentage of instances to be kept for a small scale experiment 37 | % You can also provide a file with the indexes of the instances to be used. 38 | % This should be a csvfile with a single column of integer numbers that 39 | % should be lower than the number of instances 40 | opts.selvars.fileidxflag = false; 41 | opts.selvars.fileidx = ''; 42 | 43 | opts.selvars.densityflag = false; 44 | opts.selvars.mindistance = 0.1; 45 | 46 | opts.outputs.csv = true; % 47 | opts.outputs.web = false; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 48 | opts.outputs.png = true; % 49 | 50 | % Saving all the information as a JSON file 51 | fid = fopen([rootdir 'options.json'],'w+'); 52 | fprintf(fid,'%s',jsonencode(opts)); 53 | fclose(fid); 54 | 55 | try 56 | model = buildIS(rootdir); 57 | catch ME 58 | disp('EOF:ERROR'); 59 | rethrow(ME) 60 | end -------------------------------------------------------------------------------- /TRACEtest.m: -------------------------------------------------------------------------------- 1 | function model = TRACEtest(model, Z, Ybin, P, beta, algolabels) 2 | 3 | nalgos = length(model.best); 4 | disp('-------------------------------------------------------------------------'); 5 | disp(' -> TRACE is calculating the algorithm footprints.'); 6 | model.test.best = zeros(nalgos,5); 7 | model.test.good = zeros(nalgos,5); 8 | % model.test.bad = zeros(nalgos,5); 9 | % Use the actual data to calculate the footprints 10 | for i=1:nalgos 11 | model.test.best(i,:) = TRACEtestsummary(model.best{i}, Z, P==i, model.space.area, model.space.density); 12 | model.test.good(i,:) = TRACEtestsummary(model.good{i}, Z, Ybin(:,i), model.space.area, model.space.density); 13 | % model.test.bad(i,:) = TRACEtestsummary(model.bad{i}, Z, ~Ybin(:,i), model.space.area, model.space.density); 14 | end 15 | 16 | % ------------------------------------------------------------------------- 17 | % Beta hard footprints. First step is to calculate them. 18 | disp('-------------------------------------------------------------------------'); 19 | disp(' -> TRACE is calculating the beta-footprints.'); 20 | % model.test.easy = TRACEtestsummary(model.easy, Z, beta, model.space.area, model.space.density); 21 | model.test.hard = TRACEtestsummary(model.hard, Z, ~beta, model.space.area, model.space.density); 22 | % ------------------------------------------------------------------------- 23 | % Calculating performance 24 | disp('-------------------------------------------------------------------------'); 25 | disp(' -> TRACE is preparing the summary table.'); 26 | model.summary = cell(nalgos+1,11); 27 | model.summary(1,2:end) = {'Area_Good',... 28 | 'Area_Good_Normalized',... 29 | 'Density_Good',... 30 | 'Density_Good_Normalized',... 31 | 'Purity_Good',... 32 | 'Area_Best',... 33 | 'Area_Best_Normalized',... 34 | 'Density_Best',... 35 | 'Density_Best_Normalized',... 36 | 'Purity_Best'}; 37 | model.summary(2:end,1) = algolabels(1:nalgos); 38 | model.summary(2:end,2:end) = num2cell([model.test.good model.test.best]); 39 | 40 | disp(' -> TRACE has completed. Footprint analysis results:'); 41 | disp(' '); 42 | disp(model.summary); 43 | 44 | end 45 | % ========================================================================= 46 | function out = TRACEtestsummary(footprint, Z, Ybin, spaceArea, spaceDensity) 47 | % 48 | if isempty(footprint.polygon) || all(~Ybin) 49 | out = zeros(5,1); 50 | else 51 | elements = sum(isinterior(footprint.polygon, Z)); 52 | goodElements = sum(isinterior(footprint.polygon, Z(Ybin,:))); 53 | density = elements./footprint.area; 54 | purity = goodElements./elements; 55 | 56 | out = [footprint.area,... 57 | footprint.area/spaceArea,... 58 | density,... 59 | density/spaceDensity,... 60 | purity]; 61 | end 62 | out(isnan(out)) = 0; 63 | end 64 | % ========================================================================= -------------------------------------------------------------------------------- /older_scripts/example_ksm.m: -------------------------------------------------------------------------------- 1 | rootdir = './trial_ksm/'; 2 | 3 | opts.parallel.flag = false; 4 | opts.parallel.ncores = 2; 5 | 6 | opts.perf.MaxPerf = true; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 7 | opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure 8 | opts.perf.epsilon = 0.05; % Threshold of good performance 9 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 10 | opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing 11 | opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't 12 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 13 | 14 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 15 | opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment 16 | % You can also provide a file with the indexes of the instances to be used. 17 | % This should be a csvfile with a single column of integer numbers that 18 | % should be lower than the number of instances 19 | opts.selvars.fileidxflag = false; 20 | opts.selvars.fileidx = ''; 21 | opts.selvars.densityflag = false; 22 | opts.selvars.mindistance = 0.1; 23 | 24 | opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. 25 | opts.sifted.rho = 0.1; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 26 | opts.sifted.K = 10; % Number of final features. Ideally less than 10. 27 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 28 | opts.sifted.MaxIter = 1000; 29 | opts.sifted.Replicates = 100; 30 | 31 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 32 | opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR 33 | 34 | opts.cloister.pval = 0.05; 35 | opts.cloister.cthres = 0.7; 36 | 37 | opts.pythia.cvfolds = 5; 38 | opts.pythia.ispolykrnl = false; 39 | opts.pythia.useweights = false; 40 | opts.pythia.uselibsvm = true; 41 | 42 | opts.trace.usesim = false; % Use the actual or simulated data to calculate the footprints 43 | opts.trace.PI = 0.55; % Purity threshold 44 | 45 | opts.outputs.csv = true; % 46 | opts.outputs.web = true; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 47 | opts.outputs.png = true; % 48 | 49 | % Saving all the information as a JSON file 50 | fid = fopen([rootdir 'options.json'],'w+'); 51 | fprintf(fid,'%s',jsonencode(opts)); 52 | fclose(fid); 53 | 54 | try 55 | model = buildIS(rootdir); 56 | catch ME 57 | disp('EOF:ERROR'); 58 | rethrow(ME) 59 | end 60 | -------------------------------------------------------------------------------- /older_scripts/run_bifel.m: -------------------------------------------------------------------------------- 1 | rootdir = './trial_bifidel/'; 2 | 3 | opts.parallel.flag = false; 4 | opts.parallel.ncores = 2; 5 | 6 | opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 7 | opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure 8 | opts.perf.epsilon = 0.05; % Threshold of good performance 9 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 10 | opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing 11 | opts.bound.flag = false; % Bound the outliers. True if you want to bound the outliers, false if you don't 12 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 13 | 14 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 15 | opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment 16 | % You can also provide a file with the indexes of the instances to be used. 17 | % This should be a csvfile with a single column of integer numbers that 18 | % should be lower than the number of instances 19 | opts.selvars.fileidxflag = false; 20 | opts.selvars.fileidx = ''; 21 | opts.selvars.densityflag = false; 22 | opts.selvars.mindistance = 0.1; 23 | 24 | opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. 25 | opts.sifted.rho = 0.0; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 26 | opts.sifted.K = 10; % Number of final features. Ideally less than 10. 27 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 28 | opts.sifted.MaxIter = 1000; 29 | opts.sifted.Replicates = 100; 30 | 31 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 32 | opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR 33 | 34 | opts.cloister.pval = 0.05; 35 | opts.cloister.cthres = 0.7; 36 | 37 | opts.pythia.cvfolds = 10; 38 | opts.pythia.ispolykrnl = false; 39 | opts.pythia.useweights = false; 40 | opts.pythia.uselibsvm = true; 41 | 42 | opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints 43 | opts.trace.PI = 0.55; % Purity threshold 44 | 45 | opts.outputs.csv = true; % 46 | opts.outputs.web = false; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 47 | opts.outputs.png = true; % 48 | 49 | % Saving all the information as a JSON file 50 | fid = fopen([rootdir 'options.json'],'w+'); 51 | fprintf(fid,'%s',jsonencode(opts)); 52 | fclose(fid); 53 | 54 | try 55 | model = buildIS(rootdir); 56 | catch ME 57 | disp('EOF:ERROR'); 58 | rethrow(ME) 59 | end -------------------------------------------------------------------------------- /older_scripts/run_bifel[2305843009224844497].m: -------------------------------------------------------------------------------- 1 | rootdir = './trial_bifidel/'; 2 | 3 | opts.parallel.flag = false; 4 | opts.parallel.ncores = 2; 5 | 6 | opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 7 | opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure 8 | opts.perf.epsilon = 0.05; % Threshold of good performance 9 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 10 | opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing 11 | opts.bound.flag = false; % Bound the outliers. True if you want to bound the outliers, false if you don't 12 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 13 | 14 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 15 | opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment 16 | % You can also provide a file with the indexes of the instances to be used. 17 | % This should be a csvfile with a single column of integer numbers that 18 | % should be lower than the number of instances 19 | opts.selvars.fileidxflag = false; 20 | opts.selvars.fileidx = ''; 21 | opts.selvars.densityflag = false; 22 | opts.selvars.mindistance = 0.1; 23 | 24 | opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. 25 | opts.sifted.rho = 0.0; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 26 | opts.sifted.K = 10; % Number of final features. Ideally less than 10. 27 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 28 | opts.sifted.MaxIter = 1000; 29 | opts.sifted.Replicates = 100; 30 | 31 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 32 | opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR 33 | 34 | opts.cloister.pval = 0.05; 35 | opts.cloister.cthres = 0.7; 36 | 37 | opts.pythia.cvfolds = 10; 38 | opts.pythia.ispolykrnl = false; 39 | opts.pythia.useweights = false; 40 | opts.pythia.uselibsvm = true; 41 | 42 | opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints 43 | opts.trace.PI = 0.55; % Purity threshold 44 | 45 | opts.outputs.csv = true; % 46 | opts.outputs.web = false; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 47 | opts.outputs.png = true; % 48 | 49 | % Saving all the information as a JSON file 50 | fid = fopen([rootdir 'options.json'],'w+'); 51 | fprintf(fid,'%s',jsonencode(opts)); 52 | fclose(fid); 53 | 54 | try 55 | model = buildIS(rootdir); 56 | catch ME 57 | disp('EOF:ERROR'); 58 | rethrow(ME) 59 | end -------------------------------------------------------------------------------- /older_scripts/CVNND.m: -------------------------------------------------------------------------------- 1 | function CVNND_Single(Net) 2 | 3 | %% Descriptions 4 | % CVNND stands for cofficient varioation of the nearest neighbor distances (NNDs). 5 | % For each point in the instance space, this function calculates its distance 6 | % form its nearest neighbor point. Then, claculates the coefficinet variation 7 | % of all such distances. CVNND is used as a measure of distribution 8 | % uniformuity (evenness) for non-classified samples. In fact, uniformity 9 | % can be calculated as 1-CVNND. 10 | 11 | % Depending on the flag, we might regard NND for both features and 12 | % algorithm prefromnces (APs). In such cases, NNDs of features and APs are 13 | % calculated with different scales, which concide with the scalses that 14 | % data sets are purified with the corresponding flags in 15 | % purifyInstIS_Cmp(Net, epsilon, flag) function. 16 | 17 | % The argument of this function is: 18 | % Net: is the name of metadata file including the instances and their features 19 | % ========================================================================= 20 | % Code by: Hossein Alipour 21 | % School of Mathematics and Statistics 22 | % The University of Melbourne 23 | % Australia 24 | % 2020 25 | % Email: h.alipour@unimelb.edu.au 26 | 27 | % Copyright: Hossein Alipour 28 | % 29 | 30 | %% 31 | 32 | TblHeader_CVNND = {'InstNumb' 'CV_All' 'Uniformity_All' }; 33 | 34 | textHeader_CVNND = strjoin(TblHeader_CVNND, ','); 35 | 36 | NewFileName = sprintf('CVNND_%s.csv', Net); 37 | fid = fopen(sprintf('%s',NewFileName),'w'); 38 | fprintf(fid,'%s\n',textHeader_CVNND); 39 | fclose(fid); 40 | clear fid* 41 | 42 | Xbar = readtable(sprintf('%s.csv', Net)); 43 | 44 | %% 45 | 46 | 47 | varlabels = Xbar.Properties.VariableNames; 48 | isfeat = strncmpi(varlabels,'feature_',8); 49 | isalgo = strncmpi(varlabels,'algo_',5); 50 | numFtr = sum(isfeat); 51 | numAlgo = sum(isalgo); 52 | X = Xbar{:,isfeat}; 53 | Y = Xbar{:,isalgo}; 54 | 55 | 56 | opts.norm.flag = true; 57 | [X, Y, model.norm] = autoNormalize(X, Y, opts.norm); 58 | 59 | 60 | 61 | 62 | %% The loop to calculate CVNND and Uniformity (Evenness); 63 | 64 | nearestDist = zeros(length(X),1); 65 | for ii=1:length(X) 66 | Xtmp = X; 67 | Xtmp(ii,:)=[]; 68 | allDiff = bsxfun(@minus,Xtmp,X(ii,:)); 69 | EucDist = cellfun(@norm,num2cell(allDiff,2)); 70 | nearestDist(ii) = min(EucDist); 71 | end 72 | 73 | CV = std(nearestDist)/mean(nearestDist) % coefficient of variation of the nearest neighbor distance 74 | Uniformity = 1- CV 75 | 76 | 77 | 78 | %% Wrtie data on the table 79 | % TblHeader_CVNND = {'Epsilon' 'InstNumb' 'NoViSANumb' 'ViSANumb' 'RViSA' 'CV_All' 'Uniformity_All' 'CV_NoViSA' 'Uniformity_NoViSA' }; 80 | Current_data_CVNND = [ length(X), CV, Uniformity]; 81 | fid = fopen(sprintf('%s',NewFileName),'a'); 82 | fprintf(fid,'%f,%f,%f\n', Current_data_CVNND); 83 | fclose(fid); 84 | clear fid* 85 | 86 | %% 87 | clear Xbar; 88 | clear X; 89 | clear XbarNoViSA; 90 | clear XNoViSA; 91 | clear XbarViSA 92 | end 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /example.m: -------------------------------------------------------------------------------- 1 | rootdir = './trial/'; 2 | 3 | opts.parallel.flag = false; 4 | opts.parallel.ncores = 18; 5 | 6 | opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 7 | opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure 8 | opts.perf.epsilon = 0.20; % Threshold of good performance 9 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 10 | opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing 11 | opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't 12 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 13 | 14 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 15 | opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment 16 | % You can also provide a file with the indexes of the instances to be used. 17 | % This should be a csvfile with a single column of integer numbers that 18 | % should be lower than the number of instances 19 | opts.selvars.fileidxflag = false; 20 | opts.selvars.fileidx = ''; 21 | opts.selvars.densityflag = false; 22 | opts.selvars.mindistance = 0.1; 23 | opts.selvars.type = 'Ftr&Good'; 24 | 25 | opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. 26 | opts.sifted.rho = 0.1; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 27 | opts.sifted.K = 10; % Number of final features. Ideally less than 10. 28 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 29 | opts.sifted.MaxIter = 1000; 30 | opts.sifted.Replicates = 100; 31 | 32 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 33 | opts.pilot.ntries = 5; % Number of attempts carried out by PBLDR 34 | 35 | opts.cloister.pval = 0.05; 36 | opts.cloister.cthres = 0.7; 37 | 38 | opts.pythia.flag = true; 39 | opts.pythia.useknn = true; 40 | opts.pythia.cvfolds = 5; 41 | opts.pythia.ispolykrnl = false; 42 | opts.pythia.useweights = false; 43 | opts.pythia.uselibsvm = false; 44 | 45 | opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints 46 | opts.trace.PI = 0.55; % Purity threshold 47 | 48 | opts.outputs.csv = true; % 49 | opts.outputs.web = false; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 50 | opts.outputs.png = true; % 51 | 52 | % Saving all the information as a JSON file 53 | fid = fopen([rootdir 'options.json'],'w+'); 54 | fprintf(fid,'%s',jsonencode(opts)); 55 | fclose(fid); 56 | 57 | try 58 | model = buildIS(rootdir); 59 | catch ME 60 | disp('EOF:ERROR'); 61 | rethrow(ME) 62 | end -------------------------------------------------------------------------------- /older_scripts/run_regression.m: -------------------------------------------------------------------------------- 1 | rootdir = 'C:/Users/mariom1/OneDrive - The University of Melbourne/Documents/MATLAB/InstanceSpace_Regression/trial/'; 2 | 3 | optsfile = [rootdir 'options_bkup.json']; 4 | opts = jsondecode(fileread(optsfile)); 5 | opts.auto.featsel = false; 6 | opts.corr.flag = true; 7 | opts.corr.threshold = 5; 8 | opts.clust.flag = false; 9 | 10 | opts.pilot = opts.pbldr; 11 | opts.pilot.ntries = 30; 12 | opts.pilot.alpha = [0.565534791861630;0.530308089016240;-0.158055472179465;0.441925817765667;-0.388131680786894;-0.115897084892352;0.318031215594259;-0.252996348043433;-0.413799852670937;-0.0986568416066856;0.288430949599239;-0.451900231482780;0.0920288306088186;0.210208754444068;0.501893783783401;-0.514585346888767;-0.511216943113022;0.423274119894000;-0.454752084097749;0.265861589776303;0.401368888352203;-0.310344678529976;-0.349567685663719;-0.236589491913245;-0.287934053324859;-0.395479208893403;-0.484583421210239;-0.492561449063099;-0.335035242672287;0.482304931836019;0.261015742474904;-0.146334495978856;-0.421128618719782;-0.0470575423262341;-0.808393669073297;0.644318607634159;-0.304705280866874;-0.441763092040982;-0.292545080896145;-0.325736819687666;-0.526130539808091;-0.368615647760456;-0.424904810984364;-0.411911985220851]; 13 | opts.cloister = opts.sbound; 14 | opts.pythia = opts.oracle; 15 | opts.pythia.useweights = false; 16 | opts.trace = opts.footprint; 17 | opts.trace.PI = 0.65; 18 | 19 | opts.selvars.fileidxflag = true; 20 | opts.selvars.fileidx = [rootdir 'indexes.csv']; 21 | opts.selvars.algos = {'algo_grad_boost'; 22 | 'algo_bayesian_ARD'; 23 | 'algo_bagging'; 24 | 'algo_random_forest'; 25 | 'algo_nu_svr'; 26 | 'algo_linear_svr'; 27 | 'algo_adaboost'; 28 | 'algo_decision_tree'}; 29 | 30 | opts.selvars.feats = {'feature_n1'; 31 | 'feature_c2'; 32 | 'feature_c5'; 33 | 'feature_l1_a'; 34 | 'feature_m5'; 35 | 'feature_s1'; 36 | 'feature_t2'}; 37 | 38 | fid = fopen([rootdir 'options.json'],'w+'); 39 | fprintf(fid,'%s',jsonencode(opts)); 40 | fclose(fid); 41 | 42 | try 43 | model = trainIS(rootdir); 44 | PI=0:0.05:0.95; 45 | nalgos = length(model.data.algolabels); 46 | summaryExp = zeros(nalgos,10,length(PI)); 47 | summarySim = zeros(nalgos,10,length(PI)); 48 | for i=1:length(PI) 49 | opts.trace.PI = PI(i); 50 | model.trace.exper{i} = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); 51 | model.trace.simul{i} = TRACE(model.pilot.Z, model.pythia.Yhat, model.pythia.selection0, model.data.beta, model.data.algolabels, opts.trace); 52 | summaryExp(:,:,i) = cell2mat(model.trace.exper{i}.summary(2:end,2:end)); 53 | summarySim(:,:,i) = cell2mat(model.trace.simul{i}.summary(2:end,2:end)); 54 | end 55 | summary{1} = [PI' squeeze(mean(summaryExp(:,[2 4 5 7 9 10],:),1))']; 56 | summary{2} = [PI' squeeze(mean(summarySim(:,[2 4 5 7 9 10],:),1))']; 57 | catch ME 58 | disp('EOF:ERROR'); 59 | rethrow(ME) 60 | end 61 | 62 | -------------------------------------------------------------------------------- /PYTHIAtest.m: -------------------------------------------------------------------------------- 1 | function out = PYTHIAtest(model, Z, Y, Ybin, Ybest, algolabels) 2 | 3 | Z = (Z-model.mu)./model.sigma; 4 | nalgos = length(model.svm); 5 | Y = Y(:,1:nalgos); 6 | Ybin = Ybin(:,1:nalgos); 7 | out.Yhat = false(size(Ybin)); 8 | out.Pr0hat = 0.*Ybin; 9 | out.cvcmat = zeros(nalgos,4); 10 | for ii=1:nalgos 11 | if isstruct(model.svm{ii}) 12 | Yin = double(Ybin(:,ii))+1; 13 | [aux,~,out.Pr0hat(:,ii)] = svmpredict(Yin, Z, model.svm{ii}, '-q'); 14 | out.Yhat(:,ii) = aux==2; 15 | elseif isa(model.svm{ii},'ClassificationSVM') 16 | [out.Yhat(:,ii),aux] = model.svm{ii}.predict(Z); 17 | out.Pr0hat(:,ii) = aux(:,1); 18 | else 19 | disp('There is no model for this algorithm'); 20 | out.Yhat(:,ii) = NaN; 21 | out.Pr0hat(:,ii) = NaN; 22 | end 23 | aux = confusionmat(Ybin(:,ii),out.Yhat(:,ii)); 24 | out.cvcmat(ii,:) = aux(:); 25 | end 26 | tn = out.cvcmat(:,1); 27 | fp = out.cvcmat(:,3); 28 | fn = out.cvcmat(:,2); 29 | tp = out.cvcmat(:,4); 30 | out.precision = tp./(tp+fp); 31 | out.recall = tp./(tp+fn); 32 | out.accuracy = (tp+tn)./sum(out.cvcmat(1,:)); 33 | 34 | [best,out.selection0] = max(bsxfun(@times,out.Yhat,model.precision'),[],2); 35 | [~,default] = max(mean(Ybin)); 36 | out.selection1 = out.selection0; 37 | out.selection0(best<=0) = 0; 38 | out.selection1(best<=0) = default; 39 | 40 | sel0 = bsxfun(@eq,out.selection0,1:nalgos); 41 | sel1 = bsxfun(@eq,out.selection1,1:nalgos); 42 | avgperf = nanmean(Y); 43 | stdperf = nanstd(Y); 44 | Yfull = Y; 45 | Ysvms = Y; 46 | Y(~sel0) = NaN; 47 | Yfull(~sel1) = NaN; 48 | Ysvms(~out.Yhat) = NaN; 49 | 50 | pgood = mean(any( Ybin & sel1,2)); 51 | fb = sum(any( Ybin & ~sel0,2)); 52 | fg = sum(any(~Ybin & sel0,2)); 53 | tg = sum(any( Ybin & sel0,2)); 54 | precisionsel = tg./(tg+fg); 55 | recallsel = tg./(tg+fb); 56 | 57 | disp(' -> PYTHIA is preparing the summary table.'); 58 | out.summary = cell(nalgos+3, 9); 59 | out.summary{1,1} = 'Algorithms '; 60 | out.summary(2:end-2, 1) = algolabels(1:nalgos); 61 | out.summary(end-1:end, 1) = {'Oracle','Selector'}; 62 | out.summary(1, 2:9) = {'Avg_Perf_all_instances'; 63 | 'Std_Perf_all_instances'; 64 | 'Probability_of_good'; 65 | 'Avg_Perf_selected_instances'; 66 | 'Std_Perf_selected_instances'; 67 | 'CV_model_accuracy'; 68 | 'CV_model_precision'; 69 | 'CV_model_recall'}; 70 | out.summary(2:end, 2) = num2cell(round([avgperf nanmean(Ybest) nanmean(Yfull(:))],3)); 71 | out.summary(2:end, 3) = num2cell(round([stdperf nanstd(Ybest) nanstd(Yfull(:))],3)); 72 | out.summary(2:end, 4) = num2cell(round([mean(Ybin) 1 pgood],3)); 73 | out.summary(2:end, 5) = num2cell(round([nanmean(Ysvms) NaN nanmean(Y(:))],3)); 74 | out.summary(2:end, 6) = num2cell(round([nanstd(Ysvms) NaN nanstd(Y(:))],3)); 75 | out.summary(2:end, 7) = num2cell(round(100.*[out.accuracy' NaN NaN],1)); 76 | out.summary(2:end, 8) = num2cell(round(100.*[out.precision' NaN precisionsel],1)); 77 | out.summary(2:end, 9) = num2cell(round(100.*[out.recall' NaN recallsel],1)); 78 | out.summary(cellfun(@(x) all(isnan(x)),out.summary)) = {[]}; % Clean up. Not really needed 79 | disp(' -> PYTHIA has completed! Performance of the models:'); 80 | disp(' '); 81 | disp(out.summary); 82 | 83 | end -------------------------------------------------------------------------------- /older_scripts/example_maxflow2.m: -------------------------------------------------------------------------------- 1 | rootdir = './trial_maxflow2/'; 2 | 3 | opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 4 | opts.perf.AbsPerf = false; % True if an absolute performance measure, False if a relative performance measure 5 | opts.perf.epsilon = 0.05; % Threshold of good performance 6 | 7 | opts.perf.betaThreshold = 0.55; % Beta-easy threshold 8 | 9 | opts.parallel.flag = true; 10 | opts.parallel.ncores = 6; 11 | 12 | opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing 13 | opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't 14 | opts.norm.flag = true; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 15 | 16 | opts.sifted.flag = true; % Run feature selection by correlation between performance and features (Step 2) 17 | opts.sifted.rho = 0.3; 18 | opts.sifted.K = 7; % Default maximum number of clusters 19 | opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) 20 | opts.sifted.MaxIter = 1000; 21 | opts.sifted.Replicates = 100; 22 | 23 | opts.pilot.analytic = false; % Calculate the analytical or numerical solution 24 | opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR 25 | 26 | opts.cloister.pval = 0.05; 27 | opts.cloister.cthres = 0.7; 28 | 29 | opts.pythia.cvfolds = 5; 30 | opts.pythia.ispolykrnl = true; 31 | opts.pythia.useweights = false; 32 | opts.pythia.uselibsvm = true; 33 | 34 | opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints 35 | opts.trace.PI = 0.55; % Purity threshold 36 | 37 | opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances 38 | opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment 39 | % You can also provide a file with the indexes of the instances to be used. 40 | % This should be a csvfile with a single column of integer numbers that 41 | % should be lower than the number of instances 42 | opts.selvars.fileidxflag = false; 43 | opts.selvars.fileidx = ''; 44 | 45 | opts.selvars.densityflag = false; 46 | opts.selvars.mindistance = 0.1; 47 | 48 | opts.outputs.csv = true; % 49 | opts.outputs.web = false; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 50 | opts.outputs.png = true; % 51 | 52 | % Saving all the information as a JSON file 53 | fid = fopen([rootdir 'options.json'],'w+'); 54 | fprintf(fid,'%s',jsonencode(opts)); 55 | fclose(fid); 56 | 57 | try 58 | model = buildIS(rootdir); 59 | %The trained model can be tested using testing routine 60 | %"testInterface.m". Make sure to place test data "metadata_test.csv" 61 | %inside root directory specified at the top (rootdir). 62 | % model = testIS(rootdir); 63 | catch ME 64 | disp('EOF:ERROR'); 65 | rethrow(ME) 66 | end -------------------------------------------------------------------------------- /PRELIM.m: -------------------------------------------------------------------------------- 1 | function [X,Y,Ybest,Ybin,P,numGoodAlgos,beta,out] = PRELIM(X,Y,opts) 2 | 3 | Yraw = Y; 4 | nalgos = size(Y,2); 5 | % ------------------------------------------------------------------------- 6 | % Determine whether the performance of an algorithm is a cost measure to 7 | % be minimized or a profit measure to be maximized. Moreover, determine 8 | % whether we are using an absolute threshold as good peformance (the 9 | % algorithm has a performance better than the threshold) or a relative 10 | % performance (the algorithm has a performance that is similar that the 11 | % best algorithm minus a percentage). 12 | disp('-------------------------------------------------------------------------'); 13 | disp('-> Calculating the binary measure of performance'); 14 | msg = '-> An algorithm is good if its performace is '; 15 | if opts.MaxPerf 16 | Yaux = Y; 17 | Yaux(isnan(Yaux)) = -Inf; 18 | [Ybest,P] = max(Yaux,[],2); 19 | if opts.AbsPerf 20 | Ybin = Yaux>=opts.epsilon; 21 | msg = [msg 'higher than ' num2str(opts.epsilon)]; 22 | else 23 | Ybest(Ybest==0) = eps; 24 | Y(Y==0) = eps; 25 | Y = 1-bsxfun(@rdivide,Y,Ybest); 26 | Ybin = (1-bsxfun(@rdivide,Yaux,Ybest))<=opts.epsilon; 27 | msg = [msg 'within ' num2str(round(100.*opts.epsilon)) '% of the best.']; 28 | end 29 | else 30 | Yaux = Y; 31 | Yaux(isnan(Yaux)) = Inf; 32 | [Ybest,P] = min(Yaux,[],2); 33 | if opts.AbsPerf 34 | Ybin = Yaux<=opts.epsilon; 35 | msg = [msg 'less than ' num2str(opts.epsilon)]; 36 | else 37 | Ybest(Ybest==0) = eps; 38 | Y(Y==0) = eps; 39 | Y = bsxfun(@rdivide,Y,Ybest)-1; 40 | Ybin = (bsxfun(@rdivide,Yaux,Ybest)-1)<=opts.epsilon; 41 | msg = [msg 'within ' num2str(round(100.*opts.epsilon)) '% of the best.']; 42 | end 43 | end 44 | disp(msg); 45 | % ------------------------------------------------------------------------- 46 | % Testing for ties. If there is a tie in performance, we pick an algorithm 47 | % at random. 48 | bestAlgos = bsxfun(@eq,Yraw,Ybest); 49 | multipleBestAlgos = sum(bestAlgos,2)>1; 50 | aidx = 1:nalgos; 51 | for i=1:size(Y,1) 52 | if multipleBestAlgos(i) 53 | aux = aidx(bestAlgos(i,:)); 54 | P(i) = aux(randi(length(aux),1)); % Pick one at random 55 | end 56 | end 57 | disp(['-> For ' num2str(round(100.*mean(multipleBestAlgos))) '% of the instances there is ' ... 58 | 'more than one best algorithm. Random selection is used to break ties.']); 59 | numGoodAlgos = sum(Ybin,2); 60 | beta = numGoodAlgos>(opts.betaThreshold*nalgos); 61 | 62 | if opts.auto 63 | disp('========================================================================='); 64 | disp('-> Auto-pre-processing.'); 65 | disp('========================================================================='); 66 | end 67 | out.medval = nanmedian(X, 1); 68 | out.iqrange = iqr(X, 1); 69 | out.hibound = out.medval + 5.*out.iqrange; 70 | out.lobound = out.medval - 5.*out.iqrange; 71 | if opts.auto && opts.bound 72 | disp('-> Removing extreme outliers from the feature values.'); 73 | himask = bsxfun(@gt,X,out.hibound); 74 | lomask = bsxfun(@lt,X,out.lobound); 75 | X = X.*~(himask | lomask) + bsxfun(@times,himask,out.hibound) + ... 76 | bsxfun(@times,lomask,out.lobound); 77 | end 78 | 79 | nfeats = size(X,2); 80 | nalgos = size(Y,2); 81 | out.minX = min(X,[],1); 82 | out.lambdaX = zeros(1,nfeats); 83 | out.muX = zeros(1,nfeats); 84 | out.sigmaX = zeros(1,nfeats); 85 | out.minY = min(Y(:)); 86 | out.lambdaY = zeros(1,nalgos); 87 | out.muY = zeros(1,nalgos); 88 | out.sigmaY = zeros(1,nalgos); 89 | if opts.auto && opts.norm 90 | disp('-> Auto-normalizing the data using Box-Cox and Z transformations.'); 91 | X = bsxfun(@minus,X,out.minX)+1; 92 | for i=1:nfeats 93 | aux = X(:,i); 94 | idx = isnan(aux); 95 | [aux, out.lambdaX(i)] = boxcox(aux(~idx)); 96 | [aux, out.muX(i), out.sigmaX(i)] = zscore(aux); 97 | X(~idx,i) = aux; 98 | end 99 | 100 | Y = (Y-out.minY)+eps; 101 | for i=1:nalgos 102 | aux = Y(:,i); 103 | idx = isnan(aux); 104 | [aux, out.lambdaY(i)] = boxcox(aux(~idx)); 105 | [aux, out.muY(i), out.sigmaY(i)] = zscore(aux); 106 | Y(~idx,i) = aux; 107 | end 108 | end 109 | 110 | end 111 | -------------------------------------------------------------------------------- /PILOT.m: -------------------------------------------------------------------------------- 1 | function out = PILOT(X, Y, featlabels, opts) 2 | % ------------------------------------------------------------------------- 3 | % PILOT.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | errorfcn = @(alpha,Xbar,n,m) nanmean(nanmean((Xbar-(reshape(alpha((2*n)+1:end),m,2)*... % B,C 15 | reshape(alpha(1:2*n),2,n)... % A 16 | *Xbar(:,1:n)')').^2,1),2); 17 | n = size(X, 2); % Number of features 18 | Xbar = [X Y]; 19 | m = size(Xbar, 2); 20 | Hd = pdist(X)'; 21 | if exist('gcp','file')==2 22 | mypool = gcp('nocreate'); 23 | if ~isempty(mypool) 24 | nworkers = mypool.NumWorkers; 25 | else 26 | nworkers = 0; 27 | end 28 | else 29 | nworkers = 0; 30 | end 31 | 32 | if opts.analytic 33 | disp(' -> PILOT is solving analyticaly the projection problem.'); 34 | disp(' -> This won''t take long.'); 35 | Xbar = Xbar'; 36 | X = X'; 37 | [V,D] = eig(Xbar*Xbar'); 38 | [~,idx] = sort(abs(diag(D)),'descend'); 39 | V = V(:,idx(1:2)); 40 | out.B = V(1:n,:); 41 | out.C = V(n+1:m,:)'; 42 | Xr = X'/(X*X'); 43 | out.A = V'*Xbar*Xr; 44 | out.Z = out.A*X; 45 | Xhat = [out.B*out.Z; out.C'*out.Z]; 46 | out.Z = out.Z'; 47 | out.error = sum(sum((Xbar-Xhat).^2,2)); 48 | out.R2 = diag(corr(Xbar',Xhat')).^2; 49 | else 50 | if isfield(opts,'alpha') && isnumeric(opts.alpha) && ... 51 | size(opts.alpha,1)==2*m+2*n && size(opts.alpha,2)==1 52 | disp(' -> PILOT is using a pre-calculated solution.'); 53 | idx = 1; 54 | out.alpha = opts.alpha; 55 | else 56 | if isfield(opts,'X0') && isnumeric(opts.X0) && ... 57 | size(opts.X0,1)==2*m+2*n && size(opts.X0,2)>=1 58 | disp(' -> PILOT is using a user defined starting points for BFGS.'); 59 | X0 = opts.X0; 60 | opts.ntries = size(opts.X0,2); 61 | else 62 | disp(' -> PILOT is using a random starting points for BFGS.'); 63 | state = rng; 64 | rng('default'); 65 | X0 = 2*rand(2*m+2*n, opts.ntries)-1; 66 | rng(state); 67 | end 68 | alpha = zeros(2*m+2*n, opts.ntries); 69 | eoptim = zeros(1, opts.ntries); 70 | perf = zeros(1, opts.ntries); 71 | disp('-------------------------------------------------------------------------'); 72 | disp(' -> PILOT is solving numerically the projection problem.'); 73 | disp(' -> This may take a while. Trials will not be run sequentially.'); 74 | disp('-------------------------------------------------------------------------'); 75 | parfor (i=1:opts.ntries,nworkers) 76 | [alpha(:,i),eoptim(i)] = fminunc(errorfcn, X0(:,i), ... 77 | optimoptions('fminunc','Algorithm','quasi-newton',... 78 | 'Display','off',... 79 | 'UseParallel',false),... 80 | Xbar, n, m); 81 | aux = alpha(:,i); 82 | A = reshape(aux(1:2*n),2,n); 83 | Z = X*A'; 84 | perf(i) = corr(Hd,pdist(Z)'); 85 | disp([' -> PILOT has completed trial ' num2str(i)]); 86 | end 87 | out.X0 = X0; 88 | out.alpha = alpha; 89 | out.eoptim = eoptim; 90 | out.perf = perf; 91 | [~,idx] = max(out.perf); 92 | end 93 | out.A = reshape(out.alpha(1:2*n,idx),2,n); 94 | out.Z = X*out.A'; 95 | B = reshape(out.alpha((2*n)+1:end,idx),m,2); 96 | Xhat = out.Z*B'; 97 | out.C = B(n+1:m,:)'; 98 | out.B = B(1:n,:); 99 | out.error = sum(sum((Xbar-Xhat).^2,2)); 100 | out.R2 = diag(corr(Xbar,Xhat)).^2; 101 | end 102 | 103 | disp('-------------------------------------------------------------------------'); 104 | disp(' -> PILOT has completed. The projection matrix A is:'); 105 | out.summary = cell(3, n+1); 106 | out.summary(1,2:end) = featlabels; 107 | out.summary(2:end,1) = {'Z_{1}','Z_{2}'}; 108 | out.summary(2:end,2:end) = num2cell(round(out.A,4)); 109 | disp(' '); 110 | disp(out.summary); 111 | 112 | end -------------------------------------------------------------------------------- /older_scripts/generate_evco2data.m: -------------------------------------------------------------------------------- 1 | rootdir = '../InstanceGeneration_BlackBoxOptimisation/'; 2 | datafile = [rootdir 'metadata.csv']; 3 | Xbar = readtable(datafile); 4 | varlabels = Xbar.Properties.VariableNames; 5 | isname = strcmpi(varlabels,'instances'); 6 | isfeat = strncmpi(varlabels,'feature_',8); 7 | isalgo = strncmpi(varlabels,'algo_',5); 8 | issource = strcmpi(varlabels,'source'); 9 | model.data.instlabels = Xbar{:,isname}; 10 | if isnumeric(model.data.instlabels) 11 | model.data.instlabels = num2cell(model.data.instlabels); 12 | model.data.instlabels = cellfun(@(x) num2str(x),model.data.instlabels,'UniformOutput',false); 13 | end 14 | if any(issource) 15 | model.data.S = categorical(Xbar{:,issource}); 16 | end 17 | model.data.featlabels = varlabels(isfeat); 18 | model.data.algolabels = varlabels(isalgo); 19 | 20 | model.data.X = Xbar{:,isfeat}; 21 | model.data.Y = Xbar{:,isalgo}; 22 | model.data.featlabels = strrep(model.data.featlabels,'feature_',''); 23 | model.data.algolabels = strrep(model.data.algolabels,'algo_',''); 24 | Yaux = model.data.Y; 25 | [rankPerf,rankAlgo] = sort(Yaux,2,'ascend'); 26 | model.data.Ybest = rankPerf(:,1); 27 | model.data.P = rankAlgo(:,1); 28 | model.data.Ybin = double(~isinf(Yaux)); 29 | model.data.Ybin(isnan(Yaux)) = NaN; 30 | model.data.numGoodAlgos = sum(model.data.Ybin,2); 31 | 32 | model.pilot.A = [-0.284540475 0.209907328 -0.31958864 -0.463890898 -0.300949587 0.029790169 0.531014437 -0.429196374; 33 | 0.610380182 0.162667986 -0.029267638 0.267385554 -0.438894233 0.533654711 0.017718121 -0.22559721]; 34 | 35 | model.pilot.summary = cell(3, size(model.pilot.A,2)+1); 36 | model.pilot.summary(1,2:end) = model.data.featlabels; 37 | model.pilot.summary(2:end,1) = {'Z_{1}','Z_{2}'}; 38 | model.pilot.summary(2:end,2:end) = num2cell(round(model.pilot.A,4)); 39 | 40 | model.pilot.Z = model.data.X*model.pilot.A'; 41 | 42 | opts.cloister.pval = 0.05; 43 | opts.cloister.cthres = 0.7; 44 | 45 | model.cloist = CLOISTER(model.data.X, model.pilot.A, opts.cloister); 46 | 47 | scriptfcn; 48 | writeArray2CSV(model.pilot.Z, {'z_1','z_2'}, ... 49 | model.data.instlabels, ... 50 | [rootdir 'coordinates.csv']); 51 | if isfield(model,'cloist') 52 | writeArray2CSV(model.cloist.Zedge, {'z_1','z_2'}, ... 53 | makeBndLabels(model.cloist.Zedge), ... 54 | [rootdir 'bounds.csv']); 55 | writeArray2CSV(model.cloist.Zecorr, {'z_1','z_2'}, ... 56 | makeBndLabels(model.cloist.Zecorr), ... 57 | [rootdir 'bounds_prunned.csv']); 58 | end 59 | writeArray2CSV(model.data.X, ... 60 | model.data.featlabels, ... 61 | model.data.instlabels, ... 62 | [rootdir 'feature_process.csv']); 63 | writeArray2CSV(model.data.Y, ... 64 | model.data.algolabels, ... 65 | model.data.instlabels, ... 66 | [rootdir 'algorithm_process.csv']); 67 | writeArray2CSV(model.data.Ybin, ... 68 | model.data.algolabels, ... 69 | model.data.instlabels, ... 70 | [rootdir 'algorithm_bin.csv']); 71 | writeArray2CSV(model.data.numGoodAlgos, {'NumGoodAlgos'}, ... 72 | model.data.instlabels, ... 73 | [rootdir 'good_algos.csv']); 74 | writeArray2CSV(model.data.P, {'Best_Algorithm'}, ... 75 | model.data.instlabels, ... 76 | [rootdir 'portfolio.csv']); 77 | writeCell2CSV(model.pilot.summary(2:end,2:end), ... 78 | model.pilot.summary(1,2:end),... 79 | model.pilot.summary(2:end,1), ... 80 | [rootdir 'projection_matrix.csv']); 81 | 82 | writetable(array2table(uint8(255.*parula(256)), ... 83 | 'VariableNames', {'R','G','B'}), ... 84 | [rootdir 'color_table.csv']); 85 | writeArray2CSV(colorscale(model.data.X), ... 86 | model.data.featlabels, ... 87 | model.data.instlabels, ... 88 | [rootdir 'feature_process_color.csv']); 89 | writeArray2CSV(colorscale(model.data.Y), ... 90 | model.data.algolabels, ... 91 | model.data.instlabels, ... 92 | [rootdir 'algorithm_process_single_color.csv']); 93 | writeArray2CSV(colorscaleg(model.data.Y), ... 94 | model.data.algolabels, ... 95 | model.data.instlabels, ... 96 | [rootdir 'algorithm_process_color.csv']); 97 | writeArray2CSV(colorscaleg(model.data.numGoodAlgos), ... 98 | {'NumGoodAlgos'}, ... 99 | model.data.instlabels, ... 100 | [rootdir 'good_algos_color.csv']); 101 | -------------------------------------------------------------------------------- /scriptcsv.m: -------------------------------------------------------------------------------- 1 | function scriptcsv(container,rootdir) 2 | % ------------------------------------------------------------------------- 3 | % csvscript.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | scriptfcn; 15 | 16 | nalgos = size(container.data.Y,2); 17 | disp('========================================================================='); 18 | disp('-> Writing the data on CSV files for posterior analysis.'); 19 | % ------------------------------------------------------------------------- 20 | for i=1:nalgos 21 | if isfield(container.trace.best{i},'polygon') && ~isempty(container.trace.best{i}.polygon) 22 | writeArray2CSV(container.trace.best{i}.polygon.Vertices, ... 23 | {'z_1','z_2'},... 24 | makeBndLabels(container.trace.best{i}.polygon.Vertices),... 25 | [rootdir 'footprint_' container.data.algolabels{i} '_best.csv']); 26 | end 27 | if isfield(container.trace.good{i},'polygon') && ~isempty(container.trace.good{i}.polygon) 28 | writeArray2CSV(container.trace.good{i}.polygon.Vertices, ... 29 | {'z_1','z_2'},... 30 | makeBndLabels(container.trace.good{i}.polygon.Vertices),... 31 | [rootdir 'footprint_' container.data.algolabels{i} '_good.csv']); 32 | end 33 | % if isfield(container.trace.bad{i},'polygon') && ~isempty(container.trace.bad{i}.polygon) 34 | % writeArray2CSV(container.trace.bad{i}.polygon.Vertices, ... 35 | % {'z_1','z_2'},... 36 | % makeBndLabels(container.trace.bad{i}.polygon.Vertices),... 37 | % [rootdir 'footprint_' container.data.algolabels{i} '_bad.csv']); 38 | % end 39 | end 40 | 41 | writeArray2CSV(container.pilot.Z, {'z_1','z_2'}, ... 42 | container.data.instlabels, ... 43 | [rootdir 'coordinates.csv']); 44 | if isfield(container,'cloist') 45 | writeArray2CSV(container.cloist.Zedge, {'z_1','z_2'}, ... 46 | makeBndLabels(container.cloist.Zedge), ... 47 | [rootdir 'bounds.csv']); 48 | writeArray2CSV(container.cloist.Zecorr, {'z_1','z_2'}, ... 49 | makeBndLabels(container.cloist.Zecorr), ... 50 | [rootdir 'bounds_prunned.csv']); 51 | end 52 | writeArray2CSV(container.data.Xraw(:, container.featsel.idx), ... 53 | container.data.featlabels, ... 54 | container.data.instlabels, ... 55 | [rootdir 'feature_raw.csv']); 56 | writeArray2CSV(container.data.X, ... 57 | container.data.featlabels, ... 58 | container.data.instlabels, ... 59 | [rootdir 'feature_process.csv']); 60 | writeArray2CSV(container.data.Yraw, ... 61 | container.data.algolabels, ... 62 | container.data.instlabels, ... 63 | [rootdir 'algorithm_raw.csv']); 64 | writeArray2CSV(container.data.Y, ... 65 | container.data.algolabels, ... 66 | container.data.instlabels, ... 67 | [rootdir 'algorithm_process.csv']); 68 | writeArray2CSV(container.data.Ybin, ... 69 | container.data.algolabels, ... 70 | container.data.instlabels, ... 71 | [rootdir 'algorithm_bin.csv']); 72 | writeArray2CSV(container.data.numGoodAlgos, {'NumGoodAlgos'}, ... 73 | container.data.instlabels, ... 74 | [rootdir 'good_algos.csv']); 75 | writeArray2CSV(container.data.beta, {'IsBetaEasy'}, ... 76 | container.data.instlabels, ... 77 | [rootdir 'beta_easy.csv']); 78 | writeArray2CSV(container.data.P, {'Best_Algorithm'}, ... 79 | container.data.instlabels, ... 80 | [rootdir 'portfolio.csv']); 81 | writeArray2CSV(container.pythia.Yhat, ... 82 | container.data.algolabels, ... 83 | container.data.instlabels, ... 84 | [rootdir 'algorithm_svm.csv']); 85 | writeArray2CSV(container.pythia.selection0, ... 86 | {'Best_Algorithm'}, ... 87 | container.data.instlabels, ... 88 | [rootdir 'portfolio_svm.csv']); 89 | writeCell2CSV(container.trace.summary(2:end,[3 5 6 8 10 11]), ... 90 | container.trace.summary(1,[3 5 6 8 10 11]),... 91 | container.trace.summary(2:end,1),... 92 | [rootdir 'footprint_performance.csv']); 93 | if isfield(container.pilot,'summary') 94 | writeCell2CSV(container.pilot.summary(2:end,2:end), ... 95 | container.pilot.summary(1,2:end),... 96 | container.pilot.summary(2:end,1), ... 97 | [rootdir 'projection_matrix.csv']); 98 | end 99 | writeCell2CSV(container.pythia.summary(2:end,2:end), ... 100 | container.pythia.summary(1,2:end), ... 101 | container.pythia.summary(2:end,1), ... 102 | [rootdir 'svm_table.csv']); 103 | -------------------------------------------------------------------------------- /older_scripts/run_timetable.m: -------------------------------------------------------------------------------- 1 | % ------ Rephrasing the Timetable data 2 | rdir = '../../InstanceSpace_Timetabling/'; 3 | load([rdir 'workspace.mat']); 4 | % Loading the options 5 | model.opts.perf.MaxPerf = opts.perf.MaxMin; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. 6 | model.opts.perf.AbsPerf = opts.perf.AbsPerf; % True if an absolute performance measure, False if a relative performance measure 7 | model.opts.perf.epsilon = opts.perf.epsilon; % Threshold of good performance 8 | 9 | model.opts.general = opts.general; % Beta-easy threshold 10 | model.opts.auto = opts.auto; % Automatic preprocessing on. Set to false if you don't want any preprocessing 11 | model.opts.bound = opts.bound; % Bound the outliers. True if you want to bound the outliers, false if you don't 12 | model.opts.norm = opts.norm; % Normalize/Standarize the data. True if you want to apply Box-Cox and Z transformations to stabilize the variance and scale N(0,1) 13 | model.opts.corr = opts.corr; 14 | model.opts.clust = opts.clust; 15 | 16 | model.opts.pilot = opts.pbldr; % Calculate the analytical or numerical solution 17 | model.opts.pythia.cvfolds = opts.oracle.cvfolds; 18 | model.opts.pythia.useweights = false; 19 | model.opts.pythia.uselibsvm = true; 20 | model.opts.pythia.params = out.algosel.paramgrid(out.algosel.paramidx,:); 21 | 22 | model.opts.cloister.pval = 0.05; 23 | model.opts.cloister.cthres = 0.7; 24 | 25 | model.opts.trace.usesim = false; % Use the actual or simulated data to calculate the footprints 26 | model.opts.trace.PI = 0.55; % Purity threshold 27 | 28 | model.opts.selvars = opts.selvars; 29 | 30 | model.opts.outputs.csv = true; % 31 | model.opts.outputs.web = true; % NOTE: MAKE THIS FALSE IF YOU ARE USING THIS CODE LOCALY - This flag is only useful if the system is being used 'online' through matilda.unimelb.edu.au 32 | model.opts.outputs.png = true; 33 | 34 | [model.clust.selvars,idx] = sort(out.clust.selvars); 35 | 36 | model.data.X = X(:,idx); 37 | model.data.Y = Y; 38 | model.data.Xraw = Xraw; 39 | model.data.Yraw = Yraw; 40 | model.data.Ybin = Ybin; 41 | model.data.S = S; 42 | model.data.beta = beta; 43 | model.data.bestPerformace = bestPerformace; 44 | model.data.P = portfolio; 45 | model.data.featlabels = featlabels(:,idx); 46 | model.data.algolabels = algolabels; 47 | model.data.instlabels = instlabels; 48 | model.data.numGoodAlgos = sum(model.data.Ybin,2); 49 | 50 | model.pilot = out.pbldr; 51 | model.bound = out.bound; 52 | model.norm = out.norm; 53 | model.corr = out.corr; 54 | model.clust = out.clust; 55 | 56 | % Have to figure out a way to reconstruct the alpha and X0 values 57 | model.pilot.A = model.pilot.A(:,idx); 58 | model.pilot.B = model.pilot.B(idx,:); 59 | 60 | aux = [model.pilot.A(:); model.pilot.B(:); model.pilot.C(:)]; 61 | alpha = 0.*model.pilot.alpha; 62 | X0 = alpha; 63 | for i=1:length(alpha) 64 | [row,col] = find(model.pilot.alpha == aux(i)); 65 | alpha(i,:) = model.pilot.alpha(row,:); 66 | X0(i,:) = model.pilot.X0(row,:); 67 | end 68 | model.pilot.alpha = alpha; 69 | model.pilot.X0 = X0; 70 | 71 | auxclust = false(1,7); 72 | auxclust(out.clust.selvars) = true; 73 | aux = false(1,11); 74 | aux(out.corr.selvars) = auxclust; 75 | 76 | model.featsel.idx = aux; 77 | 78 | save([rdir 'model.mat'],'-struct','model'); % Save the main results 79 | 80 | %% 81 | clearvars; 82 | rdir = '../../InstanceSpace_Timetabling/'; 83 | model = load([rdir 'model.mat']); 84 | 85 | % opts = model.opts; 86 | % model.pilot.summary = cell(3, length(model.data.featlabels)+1); 87 | % model.pilot.summary(1,2:end) = model.data.featlabels; 88 | % model.pilot.summary(2:end,1) = {'Z_{1}','Z_{2}'}; 89 | % model.pilot.summary(2:end,2:end) = num2cell(round(model.pilot.A,4)); 90 | % model.cloist = CLOISTER(model.data.X, model.pilot.A, opts.cloister); 91 | % model.pythia = PYTHIA(model.pilot.Z, model.data.Yraw, model.data.Ybin, model.data.bestPerformace, model.data.algolabels, opts.pythia); 92 | % model.trace = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); 93 | % save([rdir 'model.mat'],'-struct','model'); % Save the main results 94 | % scriptcsv(model,rdir); 95 | scriptpng(model,rdir); 96 | h = drawSources(model.pilot.Z, model.data.S); 97 | nsources = length(h); 98 | h(nsources+1) = line(model.cloist.Zedge(:,1),model.cloist.Zedge(:,2), 'Color', [0.49 0.18 0.56]); 99 | sourcelabels = cellstr(unique(model.data.S)); 100 | sourcelabels{nsources+1} = 'estimated bound'; 101 | legend(h, sourcelabels, 'Location', 'NorthEastOutside'); 102 | axis square; axis([-10 10 -12 12]); 103 | print(gcf,'-dpng',[rdir 'distribution_sources.png']); 104 | 105 | %% 106 | clearvars; 107 | rdir = 'C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Timetabling\'; 108 | model = load([rdir 'model.mat']); 109 | PI=0:0.05:0.95; 110 | nalgos = length(model.data.algolabels); 111 | summaryExp = zeros(nalgos,10,length(PI)); 112 | summarySim = zeros(nalgos,10,length(PI)); 113 | for i=1:length(PI) 114 | opts.trace.PI = PI(i); 115 | model.trace.exp{i} = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); 116 | model.trace.sim{i} = TRACE(model.pilot.Z, model.pythia.Yhat, model.pythia.selection0, model.data.beta, model.data.algolabels, opts.trace); 117 | summaryExp(:,:,i) = cell2mat(model.trace.exp{i}.summary(2:end,2:end)); 118 | summarySim(:,:,i) = cell2mat(model.trace.sim{i}.summary(2:end,2:end)); 119 | end 120 | summary{1} = [PI' squeeze(mean(summaryExp(:,[2 4 5 7 9 10],:),1))']; 121 | summary{2} = [PI' squeeze(mean(summarySim(:,[2 4 5 7 9 10],:),1))']; 122 | 123 | -------------------------------------------------------------------------------- /scriptpng.m: -------------------------------------------------------------------------------- 1 | function scriptpng(container,rootdir) 2 | % ------------------------------------------------------------------------- 3 | % pgnscript.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | % ------------------------------------------------------------------------- 15 | % Preliminaries 16 | scriptfcn; 17 | colormap('parula'); 18 | nfeats = size(container.data.X,2); 19 | nalgos = size(container.data.Y,2); 20 | Xaux = (container.data.X-min(container.data.X,[],1))./range(container.data.X,1); 21 | Yind = (container.data.Yraw-min(container.data.Yraw,[],1))./range(container.data.Yraw,1); 22 | Yglb = log10(container.data.Yraw+1); 23 | Yglb = (Yglb-min(Yglb(:)))./range(Yglb(:)); 24 | if container.opts.trace.usesim 25 | Yfoot = container.pythia.Yhat; 26 | Pfoot = container.pythia.selection0; 27 | else 28 | Yfoot = container.data.Ybin; 29 | Pfoot = container.data.P; 30 | end 31 | % ------------------------------------------------------------------------- 32 | disp('========================================================================='); 33 | disp('-> Producing the plots.'); 34 | % ------------------------------------------------------------------------- 35 | % Drawing feature plots 36 | for i=1:nfeats 37 | clf; 38 | drawScatter(container.pilot.Z, Xaux(:,i),... 39 | strrep(container.data.featlabels{i},'_',' ')); 40 | % line(model.cloist.Zedge(:,1), model.cloist.Zedge(:,2), 'LineStyle', '-', 'Color', 'r'); 41 | print(gcf,'-dpng',[rootdir 'distribution_feature_' container.data.featlabels{i} '.png']); 42 | end 43 | % ------------------------------------------------------------------------- 44 | % Drawing algorithm performance/footprint plots 45 | for i=1:nalgos 46 | % Actual performance, normalized globaly 47 | clf; 48 | drawScatter(container.pilot.Z, Yglb(:,i), ... 49 | strrep(container.data.algolabels{i},'_',' ')); 50 | print(gcf,'-dpng',[rootdir 'distribution_performance_global_normalized_' container.data.algolabels{i} '.png']); 51 | % Actual performance, normalized individualy 52 | clf; 53 | drawScatter(container.pilot.Z, Yind(:,i), ... 54 | strrep(container.data.algolabels{i},'_',' ')); 55 | print(gcf,'-dpng',[rootdir 'distribution_performance_individual_normalized_' container.data.algolabels{i} '.png']); 56 | % Actual binary performance 57 | try 58 | clf; 59 | drawBinaryPerformance(container.pilot.Z, container.data.Ybin(:,i), ... 60 | strrep(container.data.algolabels{i},'_',' ')); 61 | print(gcf,'-dpng',[rootdir 'binary_performance_' container.data.algolabels{i} '.png']); 62 | catch 63 | disp('No binary performance has been calculated'); 64 | end 65 | % Drawing the SVM's predictions of good performance 66 | try 67 | clf; 68 | drawBinaryPerformance(container.pilot.Z, container.pythia.Yhat(:,i), ... 69 | strrep(container.data.algolabels{i},'_',' ')); 70 | print(gcf,'-dpng',[rootdir 'binary_svm_' container.data.algolabels{i} '.png']); 71 | catch 72 | disp('No SVM model has been trained'); 73 | end 74 | % Drawing the footprints for good and bad performance acording to the 75 | % binary measure 76 | try 77 | clf; 78 | drawGoodBadFootprint(container.pilot.Z, ... 79 | container.trace.good{i}, ... 80 | Yfoot(:,i), ... 81 | strrep(container.data.algolabels{i},'_',' ')); 82 | print(gcf,'-dpng',[rootdir 'footprint_' container.data.algolabels{i} '.png']); 83 | catch 84 | disp('No Footprint has been calculated'); 85 | end 86 | end 87 | % --------------------------------------------------------------------- 88 | % Plotting the number of good algos 89 | clf; 90 | drawScatter(container.pilot.Z, container.data.numGoodAlgos./nalgos, 'Percentage of good algorithms'); 91 | print(gcf,'-dpng',[rootdir 'distribution_number_good_algos.png']); 92 | % --------------------------------------------------------------------- 93 | % Drawing the algorithm performance 94 | clf; 95 | drawPortfolioSelections(container.pilot.Z, container.data.P, container.data.algolabels, 'Best algorithm'); 96 | print(gcf,'-dpng',[rootdir 'distribution_portfolio.png']); 97 | % --------------------------------------------------------------------- 98 | % Drawing the SVM's recommendations 99 | clf; 100 | drawPortfolioSelections(container.pilot.Z, container.pythia.selection0, container.data.algolabels, 'Predicted best algorithm'); 101 | print(gcf,'-dpng',[rootdir 'distribution_svm_portfolio.png']); 102 | % --------------------------------------------------------------------- 103 | % Drawing the footprints as portfolio. 104 | clf; 105 | drawPortfolioFootprint(container.pilot.Z, container.trace.best, Pfoot, container.data.algolabels); 106 | print(gcf,'-dpng',[rootdir 'footprint_portfolio.png']); 107 | % --------------------------------------------------------------------- 108 | % Plotting the model.data.beta score 109 | clf; 110 | drawBinaryPerformance(container.pilot.Z, container.data.beta, '\beta score'); 111 | print(gcf,'-dpng',[rootdir 'distribution_beta_score.png']); 112 | % --------------------------------------------------------------------- 113 | % Drawing the sources of the instances if available 114 | if isfield(container.data,'S') 115 | clf; 116 | drawSources(container.pilot.Z, container.data.S); 117 | print(gcf,'-dpng',[rootdir 'distribution_sources.png']); 118 | end -------------------------------------------------------------------------------- /SIFTED2.m: -------------------------------------------------------------------------------- 1 | function [X, out] = SIFTED2(X, Y, Ybin, featlabels, opts) 2 | % ------------------------------------------------------------------------- 3 | % SIFTED.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2021 11 | % 12 | % ------------------------------------------------------------------------- 13 | % Magik numbers 14 | Kfolds = 5; % Number of folds for the CV partition used by KNN within the GA cost function 15 | FitnessLimit = 0; % Minimum possible for the error function 16 | FunctionTolerance = 1e-3; % T 17 | MaxGenerations = 100; % Maximum number of generations for the GA 18 | MaxStallGenerations = 5; % If the GA stall for this number of generations, then exit 19 | PopulationSize = 50; % Population size for the GA 20 | alphaval = 0.05; % pvalue for statistical significance of the correlation 21 | innaceptableClustering = 0.5; % A silhouette less than this value trigers a warning 22 | acceptableClustering = 0.75; % This is a preferable silhouette value 23 | % --------------------------------------------------------------------- 24 | 25 | global mymap 26 | mymap = containers.Map('KeyType','char','ValueType','double'); 27 | 28 | if exist('gcp','file')==2 29 | mypool = gcp('nocreate'); 30 | if ~isempty(mypool) 31 | nworkers = mypool.NumWorkers; 32 | else 33 | nworkers = 0; 34 | end 35 | else 36 | nworkers = 0; 37 | end 38 | 39 | % --------------------------------------------------------------------- 40 | nfeats = size(X,2); 41 | if nfeats<=1 42 | error('-> There is only 1 feature. Stopping space construction.'); 43 | elseif nfeats<=3 44 | disp('-> There are 3 or less features to do selection. Skipping feature selection.') 45 | out.selvars = 1:nfeats; 46 | return; 47 | end 48 | % --------------------------------------------------------------------- 49 | disp('-> Selecting features based on correlation with performance.'); 50 | [out.rho,out.p] = corr(X,Y,'rows','pairwise'); 51 | rho = out.rho; 52 | rho(isnan(rho) | (out.p>alphaval)) = 0; 53 | [rho,row] = sort(abs(rho),1,'descend'); 54 | out.selvars = false(1,nfeats); 55 | % Always take the most correlated feature for each algorithm 56 | out.selvars(unique(row(1,:))) = true; 57 | % Now take any feature that has correlation at least equal to opts.rho 58 | for ii=2:nfeats 59 | out.selvars(unique(row(ii,rho(ii,:)>=opts.rho))) = true; 60 | end 61 | out.selvars = find(out.selvars); 62 | Xaux = X(:,out.selvars); 63 | disp(['-> Keeping ' num2str(size(Xaux,2)) ' out of ' num2str(nfeats) ' features (correlation).']); 64 | % --------------------------------------------------------------------- 65 | nfeats = size(Xaux,2); 66 | if nfeats<=1 67 | error('-> There is only 1 feature. Stopping space construction.'); 68 | elseif nfeats<=3 69 | disp('-> There are 3 or less features to do selection. Skipping correlation clustering selection.'); 70 | X = Xaux; 71 | return; 72 | elseif nfeats<=opts.K 73 | disp('-> There are less or equal features than clusters. Skipping correlation clustering selection.'); 74 | X = Xaux; 75 | return; 76 | end 77 | % --------------------------------------------------------------------- 78 | disp('-> Selecting features based on correlation clustering.'); 79 | state = rng; 80 | rng('default'); 81 | out.eva = evalclusters(Xaux', 'kmeans', 'Silhouette', 'KList', 3:nfeats, ... % minimum of three features 82 | 'Distance', 'correlation'); 83 | disp('-> Average silhouette values for each number of clusters.') 84 | disp([out.eva.InspectedK; out.eva.CriterionValues]); 85 | if out.eva.CriterionValues(out.eva.InspectedK==opts.K) The silhouette value for K=' num2str(opts.K) ... 87 | ' is below ' num2str(innaceptableClustering) '. You should consider increasing K.']); 88 | out.Ksuggested = out.eva.InspectedK(find(out.eva.CriterionValues>acceptableClustering,1)); 89 | if ~isempty(out.Ksuggested) 90 | disp(['-> A suggested value of K is ' num2str(out.Ksuggested)]); 91 | end 92 | end 93 | % --------------------------------------------------------------------- 94 | rng('default'); 95 | out.clust = bsxfun(@eq, kmeans(Xaux', opts.K, 'Distance', 'correlation', ... 96 | 'MaxIter', opts.MaxIter, ... 97 | 'Replicates', opts.Replicates, ... 98 | 'Options', statset('UseParallel', nworkers~=0), ... 99 | 'OnlinePhase', 'on'), 1:opts.K); 100 | rng(state); 101 | disp(['-> Constructing ' num2str(opts.K) ' clusters of features.']); 102 | disp('-> Using a GA+LookUpTable to find an optimal combination.'); 103 | % --------------------------------------------------------------------- 104 | cvpart = cvpartition(size(Xaux,1), 'Kfold', Kfolds); 105 | fcnwrap = @(x) costfcn(x, Xaux, Y, Ybin, out.clust, cvpart, featlabels, nworkers); 106 | gaopts = optimoptions('ga','FitnessLimit', FitnessLimit, 'FunctionTolerance', FunctionTolerance,... 107 | 'MaxGenerations', MaxGenerations, 'MaxStallGenerations', MaxStallGenerations,... 108 | 'PopulationSize', PopulationSize); % This sets the maximum to 1000 combinations 109 | ind = ga(fcnwrap, opts.K, [], [], [], [], ones(1,opts.K), sum(out.clust), [], 1:opts.K, gaopts); 110 | 111 | decoder = false(1,size(Xaux,2)); % Decode the chromosome 112 | for i=1:opts.K 113 | aux = find(out.clust(:,i)); 114 | decoder(aux(ind(i))) = true; 115 | end 116 | out.selvars = out.selvars(decoder); 117 | X = X(:,out.selvars); 118 | disp(['-> Keeping ' num2str(size(X, 2)) ' out of ' num2str(nfeats) ' features (clustering).']); 119 | 120 | end 121 | % ========================================================================= 122 | function y = costfcn(ind,X,Y,Ybin,clust,cvpart,featlabels,nworkers) 123 | global mymap 124 | % Magik numbers 125 | ntries = 5; % Number of trials on PILOT 126 | analytic = false; % Whether the solution to PILOT is analytic or not 127 | kneighbours = 3; % Number of neighbours on KNN (D+1) 128 | 129 | idx = false(1,size(X,2)); 130 | for i=1:length(ind) 131 | aux = find(clust(:,i)); 132 | idx(aux(ind(i))) = true; 133 | end 134 | 135 | key = strrep(num2str(idx),' ',''); 136 | if isKey(mymap,key) 137 | y = values(mymap,{key}); 138 | y = y{1}; 139 | else 140 | out = PILOT(X(:,idx), Y, featlabels(idx), struct('analytic', analytic, 'ntries', ntries)); 141 | Z = out.Z; 142 | rng('default'); 143 | y = -Inf; 144 | parfor (ii=1:size(Y,2),nworkers) 145 | knn = fitcknn(Z, Ybin(:,ii), 'CVPartition', cvpart, 'NumNeighbors', kneighbours); 146 | y = max(y, knn.kfoldLoss); 147 | end 148 | mymap(key) = y; 149 | end 150 | end 151 | % ========================================================================= -------------------------------------------------------------------------------- /older_scripts/clusterFeatureSelection.m: -------------------------------------------------------------------------------- 1 | function [X, out] = clusterFeatureSelection(X, Ybin, opts) 2 | % ------------------------------------------------------------------------- 3 | % clusterFeatureSelection.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2019 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | global comb gacostvals 15 | 16 | if exist('gcp','file')==2 17 | mypool = gcp('nocreate'); 18 | if ~isempty(mypool) 19 | nworkers = mypool.NumWorkers; 20 | else 21 | nworkers = 0; 22 | end 23 | else 24 | nworkers = 0; 25 | end 26 | 27 | nfeats = size(X,2); 28 | disp('-> Selecting features based on correlation clustering.'); 29 | nalgos = size(Ybin,2); 30 | Kmax = min(opts.KDEFAULT, nfeats); 31 | 32 | state = rng; 33 | rng('default'); 34 | out.eva = evalclusters(X', 'kmeans', 'Silhouette', 'KList', 3:Kmax, ... % minimum of three features 35 | 'Distance', 'correlation'); 36 | rng(state); 37 | disp('-> Average silhouette values for each number of clusters.') 38 | disp([3:Kmax; out.eva.CriterionValues]); 39 | 40 | if all(out.eva.CriterionValues Silhouette threshold is too high. Consider using a lower value.'); 42 | disp('-> Using the maximum number of clusters possible.'); 43 | K = Kmax; 44 | elseif all(out.eva.CriterionValues>opts.SILTHRESHOLD) 45 | disp('-> Silhouette threshold is too low. Consider using a higher value.'); 46 | disp('-> Using the minimum number of clusters possible.'); 47 | K = 3; 48 | else 49 | K = out.eva.InspectedK(find(out.eva.CriterionValues>opts.SILTHRESHOLD,1)); % If empty make an error that is more meaningfull 50 | end 51 | 52 | state = rng; 53 | rng('default'); 54 | out.clust = bsxfun(@eq, kmeans(X', K, 'Distance', 'correlation', ... 55 | 'MaxIter', opts.MaxIter, ... 56 | 'Replicates', opts.Replicates, ... 57 | 'Options', statset('UseParallel', nworkers~=0), ... 58 | 'OnlinePhase', 'on'), 1:K); 59 | rng(state); 60 | disp(['-> Constructing ' num2str(K) ' clusters of features.']); 61 | % --------------------------------------------------------------------- 62 | % Using these out.clusters, determine all possible combinations that take one 63 | % feature from each out.cluster. 64 | strcmd = '['; 65 | for i=1:K 66 | strcmd = [strcmd 'X' num2str(i) ]; %#ok<*AGROW> 67 | if i 94 | comb = sort(comb,2); 95 | disp(['-> ' num2str(ncomb) ' valid feature combinations.']); 96 | 97 | maxcomb = 1000; 98 | % --------------------------------------------------------------------- 99 | % Determine which combination produces the best separation while using a 100 | % two dimensional PCA projection. The separation is defined by a Tree 101 | % Bagger. 102 | if ncomb>maxcomb 103 | disp('-> There are over 1000 valid combinations. Using a GA+LookUpTable to find an optimal one.'); 104 | gacostvals = NaN.*ones(ncomb,1); 105 | % gacostvals = spalloc(1,bi2de(ones(1,nfeats)),ncomb); 106 | fcnwrap = @(idx) fcnforga(idx,X,Ybin,opts.NTREES,out.clust); 107 | gaopts = optimoptions('ga','FitnessLimit',0,'FunctionTolerance',1e-3,... 108 | 'MaxGenerations',100,'MaxStallGenerations',5,... 109 | 'PopulationSize',50); % This sets the maximum to 1000 combinations 110 | ind = ga(fcnwrap,K,[],[],[],[],ones(1,K),sum(out.clust),[],1:K,gaopts); 111 | out.selvars = false(1,size(X,2)); % Decode the chromosome 112 | for i=1:K 113 | aux = find(out.clust(:,i)); 114 | out.selvars(aux(ind(i))) = true; 115 | end 116 | out.selvars = find(out.selvars); 117 | elseif ncomb==1 118 | disp('-> There is one valid combination. It will be considered the optimal one.'); 119 | out.selvars = 1:nfeats; 120 | else 121 | disp('-> There are less than 1000 valid combinations. Using brute-force to find an optimal one.'); 122 | out.ooberr = zeros(ncomb,nalgos); 123 | for i=1:ncomb 124 | tic; 125 | out.ooberr(i,:) = costfcn(comb(i,:),X,Ybin,opts.NTREES); 126 | etime = toc; 127 | disp([' -> Combination No. ' num2str(i) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... 128 | 's | Average error : ' num2str(mean(out.ooberr(i,:)))]); 129 | tic; 130 | end 131 | [~,best] = min(sum(out.ooberr,2)); 132 | out.selvars = sort(comb(best,:)); 133 | end 134 | X = X(:,out.selvars); 135 | disp(['-> Keeping ' num2str(size(X, 2)) ' out of ' num2str(nfeats) ' features (clustering).']); 136 | 137 | end 138 | % ========================================================================= 139 | function ooberr = costfcn(comb,X,Ybin,ntrees) 140 | 141 | if exist('gcp','file')==2 142 | mypool = gcp('nocreate'); 143 | if ~isempty(mypool) 144 | nworkers = mypool.NumWorkers; 145 | else 146 | nworkers = 0; 147 | end 148 | else 149 | nworkers = 0; 150 | end 151 | 152 | [~, score] = pca(X(:,comb), 'NumComponents', 2); %#ok<*IDISVAR> % Reduce using PCA 153 | nalgos = size(Ybin,2); 154 | ooberr = zeros(1,nalgos); 155 | for j = 1:nalgos 156 | state = rng; 157 | rng('default'); 158 | tree = TreeBagger(ntrees, score, Ybin(:,j), 'OOBPrediction', 'on', ... 159 | 'Options', statset('UseParallel', nworkers~=0)); 160 | ooberr(j) = mean(Ybin(:,j)~=str2double(oobPredict(tree))); 161 | rng(state); 162 | end 163 | 164 | end 165 | % ========================================================================= 166 | function sumerr = fcnforga(idx,X,Ybin,ntrees,clust) 167 | global gacostvals comb 168 | 169 | tic; 170 | % Decode the chromosome into a binary string representing the selected 171 | % features 172 | ccomb = false(1,size(X,2)); 173 | for i=1:length(idx) 174 | aux = find(clust(:,i)); 175 | ccomb(aux(idx(i))) = true; 176 | end 177 | % Calculate the cost function. Use the lookup table to reduce the amount of 178 | % computation. 179 | ind = find(all(comb==find(ccomb),2)); 180 | if isnan(gacostvals(ind)) 181 | ooberr = costfcn(ccomb,X,Ybin,ntrees); 182 | sumerr = sum(ooberr); 183 | gacostvals(ind) = sumerr; 184 | else 185 | sumerr = gacostvals(ind); 186 | end 187 | 188 | etime = toc; 189 | disp([' -> Combination No. ' num2str(ind) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... 190 | 's | Average error : ' num2str(sumerr./size(Ybin,2))]); 191 | 192 | end 193 | % ========================================================================= -------------------------------------------------------------------------------- /older_scripts/purifyInst.m: -------------------------------------------------------------------------------- 1 | function purifyInst(Net, epsilon, flag) 2 | %% Description 3 | % This script purifies benchmarks problems based on the similarity among them. 4 | % The similarity of two benchmark problems is defined as the Euclidian 5 | % distnace between their features. 6 | % This script regards the similarity of tow benchmarks based on the 7 | % similarity of the algorithm performances (APs) on them too; the simiarity of 8 | % APs can be calculated as th Euclidian distance among the APs or as the 9 | % similarity of their goodness in saolving the similar benchmarks. 10 | % If two benchmarks are similar, then it checks the similarity among 11 | % algorithm performances on these benchmarks. 12 | 13 | % The arguments of this function are: 14 | % Net: is the name of metadata file including the instances and their features 15 | % and APs. 16 | % epsilon: determines the treshhold of the similarity. 17 | % flag: determines which similarity approach must be applied as follows; 18 | % ========================================================================= 19 | % 'Ftr': similarity just based on the features 20 | % 'Ftr&AP': both features and APs with Euclidian distance 21 | % 'Ftr&Good': features with Euclidian distnace and APs based on the goodness 22 | % 'Ftr&AP&Good': features with Euclidian dustance and APs 23 | % with both Euclidian distance and goodness criterion 24 | % ========================================================================= 25 | % In the cases of goodness criterion, we must define a differen threshold 26 | % for the goddness of APs. This is ture about the 27 | % second case too, but since the number of APs are less than the number of 28 | % features, they are purified with different thresholds simlicitly; 29 | 30 | % ========================================================================= 31 | % Code by: Hossein Alipour 32 | % School of Mathematics and Statistics 33 | % The University of Melbourne 34 | % Australia 35 | % 2020 36 | % Email: h.alipour@unimelb.edu.au 37 | 38 | % Copyright: Hossein Alipour 39 | % 40 | 41 | %% Main loop 42 | 43 | for k = 1:length(epsilon) 44 | 45 | Xbar = readtable(sprintf('%s.csv',Net)); 46 | 47 | varlabels = Xbar.Properties.VariableNames; 48 | isfeat = strncmpi(varlabels,'feature_',8); 49 | isalgo = strncmpi(varlabels,'algo_',5); 50 | numFtr = sum(isfeat); 51 | numAlgo = sum(isalgo); 52 | X = Xbar{:,isfeat}; 53 | Y = Xbar{:,isalgo}; 54 | 55 | toPreclude = false((size(X,1)),1); 56 | ViSA_idx = false((size(X,1)),1); 57 | Dissimilar_idx = true((size(X,1)),1); 58 | Tprcl = 0; % counter of the precluded instances 59 | 60 | 61 | ViSA_D = 0; % A counter of the violation from Euclidian distance for APs 62 | ViSA_Good = 0; % A counter of the violation from the goodness criterion for APs 63 | 64 | 65 | 66 | %% The main nested loop to preclude the similar instances according to a 67 | % given tolearnce epsilon, preferably from the interval (0, 1). 68 | Dissimilar_idx(1) = true; 69 | 70 | for i=1:size(X,1) 71 | if (~toPreclude(i)) 72 | for j=i+1:size(X,1) 73 | if (~toPreclude(j)) 74 | dist = sqrt(sum((X(i,:) - X(j,:)) .^ 2)); % Euclidean distance 75 | if (dist <= epsilon(k)) 76 | Dissimilar_idx(j) = false; 77 | switch flag 78 | case 'Ftr' 79 | toPreclude(j) = true; 80 | case 'Ftr&AP' 81 | dist_AP = sqrt(sum((Y(i,:) - Y(j,:)) .^ 2)); 82 | % if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)*(1+0.26)) % 0.26 is the value of CPUN (CPU Noise) 83 | if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)) 84 | toPreclude(j) = true; 85 | ViSA_idx(j) = false; 86 | else 87 | ViSA_idx(j) = true; 88 | end 89 | case 'Ftr&Good' 90 | if (Ybin(i,:) == Ybin(j,:)) 91 | toPreclude(j) = true; 92 | ViSA_idx(j) = false; 93 | else 94 | ViSA_idx(j) = true; 95 | end 96 | case 'Ftr&AP&Good' 97 | if (Ybin(i,:) == Ybin(j,:)) 98 | dist_AP = sqrt(sum((Y(i,:) - Y(j,:)) .^ 2)); 99 | % if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)*(1+0.26)) % epsilon could be different from that given in the function. 100 | if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)) 101 | toPreclude(j) = true; 102 | ViSA_idx(j) = false; 103 | else 104 | ViSA_idx(j) = true; 105 | end 106 | else 107 | ViSA_idx(j) = true; 108 | end 109 | otherwise 110 | disp('Invalid flag!') 111 | end 112 | end 113 | end 114 | end 115 | end 116 | end 117 | 118 | % Xbar = sortrows(Xbar); % This command is useful if you want to apply a random purification. 119 | 120 | PurifiedInst = Xbar; 121 | PrecludedInst = Xbar; 122 | DissimilarPurInst = Xbar; 123 | ViSAPurInst = Xbar; 124 | 125 | PurifiedInst(toPreclude,:) = []; 126 | PrecludedInst(~toPreclude,:) = []; 127 | DissimilarPurInst(~Dissimilar_idx,:) = []; 128 | ViSAPurInst(~ViSA_idx,:) = []; 129 | 130 | switch flag 131 | case 'Ftr' 132 | writetable(PurifiedInst,sprintf('Pur_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); 133 | writetable(PrecludedInst,sprintf('Prec_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); 134 | case 'Ftr&AP' 135 | writetable(PurifiedInst,sprintf('Pur_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); 136 | writetable(PrecludedInst,sprintf('Prec_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); 137 | case 'Ftr&Good' 138 | writetable(PurifiedInst,sprintf('Pur_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 139 | writetable(PrecludedInst,sprintf('Prec_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 140 | writetable(DissimilarPurInst,sprintf('Dissimilar_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 141 | writetable(ViSAPurInst,sprintf('ViSA_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 142 | case 'Ftr&AP&Good' 143 | writetable(PurifiedInst,sprintf('Pur_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 144 | writetable(PrecludedInst,sprintf('Prec_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 145 | writetable(DissimilarPurInst,sprintf('Dissimilar_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 146 | writetable(ViSAPurInst,sprintf('ViSA_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); 147 | end 148 | 149 | %% 150 | clear Xbar; 151 | clear X; 152 | clear Y; 153 | clear Ybin; 154 | clear toPreclude; 155 | fclose('all'); 156 | end 157 | 158 | -------------------------------------------------------------------------------- /SIFTED.m: -------------------------------------------------------------------------------- 1 | function [X, out] = SIFTED(X, Y, Ybin, opts) 2 | % ------------------------------------------------------------------------- 3 | % SIFTED.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2021 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | global comb gacostvals 15 | 16 | if exist('gcp','file')==2 17 | mypool = gcp('nocreate'); 18 | if ~isempty(mypool) 19 | nworkers = mypool.NumWorkers; 20 | else 21 | nworkers = 0; 22 | end 23 | else 24 | nworkers = 0; 25 | end 26 | 27 | % --------------------------------------------------------------------- 28 | nfeats = size(X,2); 29 | if nfeats<=1 30 | error('-> There is only 1 feature. Stopping space construction.'); 31 | elseif nfeats<=3 32 | disp('-> There are 3 or less features to do selection. Skipping feature selection.') 33 | out.selvars = 1:nfeats; 34 | return; 35 | end 36 | % --------------------------------------------------------------------- 37 | disp('-> Selecting features based on correlation with performance.'); 38 | [out.rho,out.p] = corr(X,Y,'rows','pairwise'); 39 | rho = out.rho; 40 | rho(isnan(rho) | (out.p>0.05)) = 0; 41 | [rho,row] = sort(abs(rho),1,'descend'); 42 | out.selvars = false(1,nfeats); 43 | % Always take the most correlated feature for each algorithm 44 | out.selvars(unique(row(1,:))) = true; 45 | % Now take any feature that has correlation at least equal to opts.rho 46 | for ii=2:nfeats 47 | out.selvars(unique(row(ii,rho(ii,:)>=opts.rho))) = true; 48 | end 49 | out.selvars = find(out.selvars); 50 | Xaux = X(:,out.selvars); 51 | disp(['-> Keeping ' num2str(size(Xaux,2)) ' out of ' num2str(nfeats) ' features (correlation).']); 52 | % --------------------------------------------------------------------- 53 | nfeats = size(Xaux,2); 54 | if nfeats<=1 55 | error('-> There is only 1 feature. Stopping space construction.'); 56 | elseif nfeats<=3 57 | disp('-> There are 3 or less features to do selection. Skipping correlation clustering selection.'); 58 | X = Xaux; 59 | return; 60 | elseif nfeats There are less features than clusters. Skipping correlation clustering selection.'); 62 | X = Xaux; 63 | return; 64 | end 65 | % --------------------------------------------------------------------- 66 | disp('-> Selecting features based on correlation clustering.'); 67 | nalgos = size(Ybin,2); 68 | state = rng; 69 | rng('default'); 70 | out.eva = evalclusters(Xaux', 'kmeans', 'Silhouette', 'KList', 3:nfeats, ... % minimum of three features 71 | 'Distance', 'correlation'); 72 | disp('-> Average silhouette values for each number of clusters.') 73 | disp([out.eva.InspectedK; out.eva.CriterionValues]); 74 | if out.eva.CriterionValues(out.eva.InspectedK==opts.K)<0.5 75 | disp(['-> The silhouette value for K=' num2str(opts.K) ... 76 | ' is below 0.5. You should consider increasing K.']); 77 | out.Ksuggested = out.eva.InspectedK(find(out.eva.CriterionValues>0.75,1)); 78 | if ~isempty(out.Ksuggested) 79 | disp(['-> A suggested value of K is ' num2str(out.Ksuggested)]); 80 | end 81 | end 82 | % --------------------------------------------------------------------- 83 | rng('default'); 84 | out.clust = bsxfun(@eq, kmeans(Xaux', opts.K, 'Distance', 'correlation', ... 85 | 'MaxIter', opts.MaxIter, ... 86 | 'Replicates', opts.Replicates, ... 87 | 'Options', statset('UseParallel', nworkers~=0), ... 88 | 'OnlinePhase', 'on'), 1:opts.K); 89 | rng(state); 90 | disp(['-> Constructing ' num2str(opts.K) ' clusters of features.']); 91 | % --------------------------------------------------------------------- 92 | % Using these out.clusters, determine all possible combinations that take one 93 | % feature from each out.cluster. 94 | strcmd = '['; 95 | for i=1:opts.K 96 | strcmd = [strcmd 'X' num2str(i) ]; %#ok<*AGROW> 97 | if i 124 | comb = sort(comb,2); 125 | disp(['-> ' num2str(ncomb) ' valid feature combinations.']); 126 | 127 | maxcomb = 1000; 128 | % --------------------------------------------------------------------- 129 | % Determine which combination produces the best separation while using a 130 | % two dimensional PCA projection. The separation is defined by a Tree 131 | % Bagger. 132 | if ncomb>maxcomb 133 | disp('-> There are over 1000 valid combinations. Using a GA+LookUpTable to find an optimal one.'); 134 | gacostvals = NaN.*ones(ncomb,1); 135 | fcnwrap = @(idx) fcnforga(idx,Xaux,Ybin,opts.NTREES,out.clust,nworkers); 136 | gaopts = optimoptions('ga','FitnessLimit',0,'FunctionTolerance',1e-3,... 137 | 'MaxGenerations',100,'MaxStallGenerations',5,... 138 | 'PopulationSize',50); % This sets the maximum to 1000 combinations 139 | ind = ga(fcnwrap,opts.K,[],[],[],[],ones(1,opts.K),sum(out.clust),[],1:opts.K,gaopts); 140 | decoder = false(1,size(Xaux,2)); % Decode the chromosome 141 | for i=1:opts.K 142 | aux = find(out.clust(:,i)); 143 | decoder(aux(ind(i))) = true; 144 | end 145 | out.selvars = out.selvars(decoder); 146 | elseif ncomb==1 147 | disp('-> There is one valid combination. It will be considered the optimal one.'); 148 | % out.selvars = 1:nfeats; 149 | else 150 | disp('-> There are less than 1000 valid combinations. Using brute-force to find an optimal one.'); 151 | out.ooberr = zeros(ncomb,nalgos); 152 | for i=1:ncomb 153 | tic; 154 | out.ooberr(i,:) = costfcn(comb(i,:),Xaux,Ybin,opts.NTREES,nworkers); 155 | etime = toc; 156 | disp([' -> Combination No. ' num2str(i) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... 157 | 's | Average error : ' num2str(mean(out.ooberr(i,:)))]); 158 | tic; 159 | end 160 | [~,best] = min(sum(out.ooberr,2)); 161 | out.selvars = sort(out.selvars(comb(best,:))); 162 | end 163 | X = X(:,out.selvars); 164 | disp(['-> Keeping ' num2str(size(X, 2)) ' out of ' num2str(nfeats) ' features (clustering).']); 165 | 166 | end 167 | % ========================================================================= 168 | function ooberr = costfcn(comb,X,Ybin,ntrees,nworkers) 169 | 170 | [~, score] = pca(X(:,comb), 'NumComponents', 2); %#ok<*IDISVAR> % Reduce using PCA 171 | nalgos = size(Ybin,2); 172 | ooberr = zeros(1,nalgos); 173 | for j = 1:nalgos 174 | state = rng; 175 | rng('default'); 176 | tree = TreeBagger(ntrees, score, Ybin(:,j), 'OOBPrediction', 'on',... 177 | 'Options', statset('UseParallel', nworkers~=0)); 178 | ooberr(j) = mean(Ybin(:,j)~=str2double(oobPredict(tree))); 179 | rng(state); 180 | end 181 | 182 | end 183 | % ========================================================================= 184 | function sumerr = fcnforga(idx,X,Ybin,ntrees,clust,nworkers) 185 | global gacostvals comb 186 | 187 | tic; 188 | % Decode the chromosome into a binary string representing the selected 189 | % features 190 | ccomb = false(1,size(X,2)); 191 | for i=1:length(idx) 192 | aux = find(clust(:,i)); 193 | ccomb(aux(idx(i))) = true; 194 | end 195 | % Calculate the cost function. Use the lookup table to reduce the amount of 196 | % computation. 197 | ind = find(all(comb==find(ccomb),2)); 198 | if isnan(gacostvals(ind)) 199 | ooberr = costfcn(ccomb,X,Ybin,ntrees,nworkers); 200 | sumerr = sum(ooberr); 201 | gacostvals(ind) = sumerr; 202 | else 203 | sumerr = gacostvals(ind); 204 | end 205 | 206 | etime = toc; 207 | disp([' -> Combination No. ' num2str(ind) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... 208 | 's | Average error : ' num2str(sumerr./size(Ybin,2))]); 209 | 210 | end 211 | % ========================================================================= -------------------------------------------------------------------------------- /PYTHIA2.m: -------------------------------------------------------------------------------- 1 | function out = PYTHIA2(Z, Y, Ybin, Ybest, algolabels, opts) 2 | % ------------------------------------------------------------------------- 3 | % PYTHIA.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | disp(' -> Initializing PYTHIA.'); 15 | [ninst,nalgos] = size(Ybin); 16 | out.cp = cell(1,nalgos); 17 | out.knn = cell(1,nalgos); 18 | out.cvcmat = zeros(nalgos,4); 19 | out.Ysub = false & Ybin; 20 | out.Yhat = false & Ybin; 21 | out.Pr0sub = 0.*Ybin; 22 | out.Pr0hat = 0.*Ybin; 23 | out.boxcosnt = zeros(1,nalgos); 24 | out.kscale = out.boxcosnt; 25 | disp('-------------------------------------------------------------------------'); 26 | precalcparams = isfield(opts,'params') && isnumeric(opts.params) && ... 27 | size(opts.params,1)==nalgos && size(opts.params,2)==2; 28 | disp(' -> Using MATLAB''s KNN libraries.'); 29 | if precalcparams 30 | disp(' -> Using pre-calculated hyper-parameters for the SVM.'); 31 | params = opts.params; 32 | else 33 | disp(' -> Bayesian Optimization will be used for parameter hyper-tunning.'); 34 | params = NaN.*ones(nalgos,2); 35 | end 36 | disp('-------------------------------------------------------------------------'); 37 | if opts.useweights 38 | disp(' -> PYTHIA is using weights for cost-sensitive classification [experimental]'); 39 | out.W = abs(Y-nanmean(Y(:))); 40 | out.W(out.W==0) = min(out.W(out.W~=0)); 41 | out.W(isnan(out.W)) = max(out.W(~isnan(out.W))); 42 | Waux = out.W; 43 | else 44 | disp(' -> PYTHIA is not using cost-sensitive classification'); 45 | Waux = ones(ninst,nalgos); 46 | end 47 | 48 | disp('-------------------------------------------------------------------------'); 49 | disp([' -> Using a ' num2str(opts.cvfolds) ... 50 | '-fold stratified cross-validation experiment to evaluate the models.']); 51 | disp('-------------------------------------------------------------------------'); 52 | disp(' -> Training has started. PYTHIA may take a while to complete...'); 53 | t = tic; 54 | for i=1:nalgos 55 | tic; 56 | state = rng; 57 | rng('default'); 58 | out.cp{i} = cvpartition(Ybin(:,i),'Kfold',opts.cvfolds,'Stratify',true); 59 | [out.knn{i},out.Ysub(:,i),out.Pr0sub(:,i),out.Yhat(:,i),... 60 | out.Pr0hat(:,i),out.boxcosnt(i),out.kscale(i)] = fitmatknn(Z,Ybin(:,i),... 61 | Waux(:,i),out.cp{i},... 62 | params(i,:)); 63 | rng(state); 64 | aux = confusionmat(Ybin(:,i),out.Ysub(:,i)); 65 | if numel(aux)~=4 66 | caux = aux; 67 | aux = zeros(2); 68 | if all(Ybin(:,i)==0) 69 | if all(out.Ysub(:,i)==0) 70 | aux(1,1) = caux; 71 | elseif all(out.Ysub(:,i)==1) 72 | aux(2,1) = caux; 73 | end 74 | elseif all(Ybin(:,i)==1) 75 | if all(out.Ysub(:,i)==0) 76 | aux(1,2) = caux; 77 | elseif all(out.Ysub(:,i)==1) 78 | aux(2,2) = caux; 79 | end 80 | end 81 | end 82 | out.cvcmat(i,:) = aux(:); 83 | if i==nalgos 84 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 85 | ''', there are no models left to train.']); 86 | elseif i==nalgos-1 87 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 88 | ''', there is 1 model left to train.']); 89 | else 90 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 91 | ''', there are ' num2str(nalgos-i) ' models left to train.']); 92 | end 93 | disp([' -> Elapsed time: ' num2str(toc,'%.2f\n') 's']); 94 | end 95 | tn = out.cvcmat(:,1); 96 | fp = out.cvcmat(:,3); 97 | fn = out.cvcmat(:,2); 98 | tp = out.cvcmat(:,4); 99 | out.precision = tp./(tp+fp); 100 | out.recall = tp./(tp+fn); 101 | out.accuracy = (tp+tn)./ninst; 102 | disp('-------------------------------------------------------------------------'); 103 | disp(' -> PYTHIA has completed training the models.'); 104 | disp([' -> The average cross validated precision is: ' ... 105 | num2str(round(100.*mean(out.precision),1)) '%']); 106 | disp([' -> The average cross validated accuracy is: ' ... 107 | num2str(round(100.*mean(out.accuracy),1)) '%']); 108 | disp([' -> Elapsed time: ' num2str(toc(t),'%.2f\n') 's']); 109 | disp('-------------------------------------------------------------------------'); 110 | % We assume that the most precise SVM (as per CV-Precision) is the most 111 | % reliable. 112 | if nalgos>1 113 | [best,out.selection0] = max(bsxfun(@times,out.Yhat,out.precision'),[],2); 114 | else 115 | best = out.Yhat; 116 | out.selection0 = out.Yhat; 117 | end 118 | [~,default] = max(mean(Ybin)); 119 | out.selection1 = out.selection0; 120 | out.selection0(best<=0) = 0; 121 | out.selection1(best<=0) = default; 122 | 123 | sel0 = bsxfun(@eq,out.selection0,1:nalgos); 124 | sel1 = bsxfun(@eq,out.selection1,1:nalgos); 125 | avgperf = nanmean(Y); 126 | stdperf = nanstd(Y); 127 | Yfull = Y; 128 | Ysvms = Y; 129 | Y(~sel0) = NaN; 130 | Yfull(~sel1) = NaN; 131 | Ysvms(~out.Yhat) = NaN; 132 | 133 | pgood = mean(any( Ybin & sel1,2)); 134 | fb = sum(any( Ybin & ~sel0,2)); 135 | fg = sum(any(~Ybin & sel0,2)); 136 | tg = sum(any( Ybin & sel0,2)); 137 | precisionsel = tg./(tg+fg); 138 | recallsel = tg./(tg+fb); 139 | 140 | disp(' -> PYTHIA is preparing the summary table.'); 141 | out.summary = cell(nalgos+3, 11); 142 | out.summary{1,1} = 'Algorithms '; 143 | out.summary(2:end-2, 1) = algolabels; 144 | out.summary(end-1:end, 1) = {'Oracle','Selector'}; 145 | out.summary(1, 2:11) = {'Avg_Perf_all_instances'; 146 | 'Std_Perf_all_instances'; 147 | 'Probability_of_good'; 148 | 'Avg_Perf_selected_instances'; 149 | 'Std_Perf_selected_instances'; 150 | 'CV_model_accuracy'; 151 | 'CV_model_precision'; 152 | 'CV_model_recall'; 153 | 'NumNeighbours'; 154 | 'Distance'}; 155 | out.summary(2:end, 2) = num2cell(round([avgperf nanmean(Ybest) nanmean(Yfull(:))],3)); 156 | out.summary(2:end, 3) = num2cell(round([stdperf nanstd(Ybest) nanstd(Yfull(:))],3)); 157 | out.summary(2:end, 4) = num2cell(round([mean(Ybin) 1 pgood],3)); 158 | out.summary(2:end, 5) = num2cell(round([nanmean(Ysvms) NaN nanmean(Y(:))],3)); 159 | out.summary(2:end, 6) = num2cell(round([nanstd(Ysvms) NaN nanstd(Y(:))],3)); 160 | out.summary(2:end, 7) = num2cell(round(100.*[out.accuracy' NaN NaN],1)); 161 | out.summary(2:end, 8) = num2cell(round(100.*[out.precision' NaN precisionsel],1)); 162 | out.summary(2:end, 9) = num2cell(round(100.*[out.recall' NaN recallsel],1)); 163 | out.summary(2:end-2, 10) = num2cell(round(out.boxcosnt,3)); 164 | out.summary(2:end-2, 11) = num2cell(round(out.kscale,3)); 165 | out.summary(cellfun(@(x) all(isnan(x)),out.summary)) = {[]}; % Clean up. Not really needed 166 | disp(' -> PYTHIA has completed! Performance of the models:'); 167 | disp(' '); 168 | disp(out.summary); 169 | 170 | end 171 | % ========================================================================= 172 | % SUBFUNCTIONS 173 | % ========================================================================= 174 | function [knn,Ysub,Psub,Yhat,Phat,NumNeighbors,Distance] = fitmatknn(Z,Ybin,W,cp,params) 175 | 176 | if exist('gcp','file')==2 177 | mypool = gcp('nocreate'); 178 | if ~isempty(mypool) 179 | nworkers = mypool.NumWorkers; 180 | else 181 | nworkers = 0; 182 | end 183 | else 184 | nworkers = 0; 185 | end 186 | 187 | hypparams = hyperparameters('fitcknn',Z,Ybin); 188 | 189 | if any(isnan(params)) 190 | rng('default'); 191 | knn = fitcknn(Z,Ybin,'Standardize',false,... 192 | 'Weights',W,... 193 | 'OptimizeHyperparameters',hypparams,... 194 | 'HyperparameterOptimizationOptions',... 195 | struct('CVPartition',cp,... 196 | 'Verbose',0,... 197 | 'AcquisitionFunctionName','probability-of-improvement',... 198 | 'ShowPlots',false,... 199 | 'UseParallel',nworkers~=0)); 200 | NumNeighbors = knn.HyperparameterOptimizationResults.bestPoint{1,1}; 201 | Distance = knn.HyperparameterOptimizationResults.bestPoint{1,2}; 202 | [Ysub,aux] = knn.resubPredict; 203 | Psub = aux(:,1); 204 | [Yhat,aux] = knn.predict(Z); 205 | Phat = aux(:,1); 206 | else 207 | NumNeighbors = round(params(1)); 208 | Distance = hypparams(2).Range(round(params(2))); 209 | rng('default'); 210 | knn = fitcknn(Z,Ybin,'Standardize',false,... 211 | 'Weights',W,... 212 | 'CVPartition',cp,... 213 | 'NumNeighbors',NumNeighbors,... 214 | 'Distance',Distance); 215 | [Ysub,aux] = knn.kfoldPredict; 216 | Psub = aux(:,1); 217 | [Yhat,aux] = knn.predict(Z); 218 | Phat = aux(:,1); 219 | end 220 | 221 | end 222 | % ========================================================================= -------------------------------------------------------------------------------- /scriptfcn.m: -------------------------------------------------------------------------------- 1 | function scriptfcn 2 | % ------------------------------------------------------------------------- 3 | % scriptfcn.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | writeArray2CSV = @(data,colnames,rownames,filename) writetable(array2table(data,'VariableNames',colnames,... 15 | 'RowNames',rownames),... 16 | filename,'WriteRowNames',true); 17 | writeCell2CSV = @(data,colnames,rownames,filename) writetable(cell2table(data,'VariableNames',colnames,... 18 | 'RowNames',rownames),... 19 | filename,'WriteRowNames',true); 20 | makeBndLabels = @(data) arrayfun(@(x) strcat('bnd_pnt_',num2str(x)),1:size(data,1),'UniformOutput',false); 21 | colorscale = @(data) round(255.*bsxfun(@rdivide, bsxfun(@minus, data, min(data,[],1)), range(data))); 22 | colorscaleg = @(data) round(255.*bsxfun(@rdivide, bsxfun(@minus, data, min(data(:))), range(data(:)))); 23 | 24 | assignin('caller','writeArray2CSV',writeArray2CSV); 25 | assignin('caller','writeCell2CSV',writeCell2CSV); 26 | assignin('caller','makeBndLabels',makeBndLabels); 27 | assignin('caller','colorscale',colorscale); 28 | assignin('caller','colorscaleg',colorscaleg); 29 | assignin('caller','drawSources',@drawSources); 30 | assignin('caller','drawScatter',@drawScatter); 31 | assignin('caller','drawPortfolioSelections',@drawPortfolioSelections); 32 | assignin('caller','drawPortfolioFootprint',@drawPortfolioFootprint); 33 | assignin('caller','drawGoodBadFootprint',@drawGoodBadFootprint); 34 | assignin('caller','drawFootprint',@drawFootprint); 35 | assignin('caller','drawBinaryPerformance',@drawBinaryPerformance); 36 | 37 | end 38 | % ========================================================================= 39 | % SUBFUNCTIONS 40 | % ========================================================================= 41 | function handle = drawSources(Z, S) 42 | 43 | ubound = ceil(max(Z)); 44 | lbound = floor(min(Z)); 45 | sourcelabels = cellstr(unique(S)); 46 | nsources = length(sourcelabels); 47 | clrs = flipud(lines(nsources)); 48 | handle = zeros(nsources,1); 49 | for i=nsources:-1:1 50 | line(Z(S==sourcelabels{i},1), ... 51 | Z(S==sourcelabels{i},2), ... 52 | 'LineStyle', 'none', ... 53 | 'Marker', '.', ... 54 | 'Color', clrs(i,:), ... 55 | 'MarkerFaceColor', clrs(i,:), ... 56 | 'MarkerSize', 8); 57 | handle(i) = patch([0 0],[0 0], clrs(i,:), 'EdgeColor','none'); 58 | end 59 | xlabel('z_{1}'); ylabel('z_{2}'); title('Sources'); 60 | legend(handle, sourcelabels, 'Location', 'NorthEastOutside'); 61 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 62 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 63 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 64 | 65 | end 66 | % ========================================================================= 67 | function handle = drawScatter(Z, X, titlelabel) 68 | 69 | ubound = ceil(max(Z)); 70 | lbound = floor(min(Z)); 71 | handle = scatter(Z(:,1), Z(:,2), 8, X, 'filled'); 72 | caxis([0,1]) 73 | xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); 74 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 75 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 76 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 77 | colorbar('EastOutside'); 78 | 79 | end 80 | % ========================================================================= 81 | function drawPortfolioSelections(Z, P, algolabels, titlelabel) 82 | 83 | ubound = ceil(max(Z)); 84 | lbound = floor(min(Z)); 85 | nalgos = length(algolabels); 86 | algolbls = cell(1,nalgos+1); 87 | h = zeros(1,nalgos+1); 88 | isworthy = sum(bsxfun(@eq, P, 0:nalgos))~=0; 89 | clr = flipud(lines(nalgos+1)); 90 | for i=0:nalgos 91 | if ~isworthy(i+1) 92 | continue; 93 | end 94 | line(Z(P==i,1), Z(P==i,2), 'LineStyle', 'none', ... 95 | 'Marker', '.', ... 96 | 'Color', clr(i+1,:), ... 97 | 'MarkerFaceColor', clr(i+1,:), ... 98 | 'MarkerSize', 4); 99 | h(i+1) = patch([0 0],[0 0], clr(i+1,:), 'EdgeColor','none'); 100 | if i==0 101 | algolbls{i+1} = 'None'; 102 | else 103 | algolbls{i+1} = strrep(algolabels{i},'_',' '); 104 | end 105 | end 106 | xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); 107 | legend(h(isworthy), algolbls(isworthy), 'Location', 'NorthEastOutside'); 108 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 109 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 110 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 111 | 112 | end 113 | % ========================================================================= 114 | function h = drawPortfolioFootprint(Z, best, P, algolabels) 115 | 116 | % Color definitions 117 | ubound = ceil(max(Z)); 118 | lbound = floor(min(Z)); 119 | nalgos = length(algolabels); 120 | algolbls = cell(1,nalgos+1); 121 | isworthy = sum(bsxfun(@eq, P, 0:nalgos))~=0; 122 | clr = flipud(lines(nalgos+1)); 123 | h = zeros(1,nalgos+1); 124 | for i=0:nalgos 125 | if ~isworthy(i+1) 126 | continue; 127 | end 128 | line(Z(P==i,1), Z(P==i,2), 'LineStyle', 'none', ... 129 | 'Marker', '.', ... 130 | 'Color', clr(i+1,:), ... 131 | 'MarkerFaceColor', clr(i+1,:), ... 132 | 'MarkerSize', 4); 133 | h(i+1) = patch([0 0],[0 0], clr(i+1,:), 'EdgeColor','none'); 134 | if i==0 135 | algolbls{i+1} = 'None'; 136 | else 137 | drawFootprint(best{i}, clr(i+1,:), 0.3); 138 | algolbls{i+1} = strrep(algolabels{i},'_',' '); 139 | end 140 | end 141 | xlabel('z_{1}'); ylabel('z_{2}'); title('Portfolio footprints'); 142 | legend(h(isworthy), algolbls(isworthy), 'Location', 'NorthEastOutside'); 143 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 144 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 145 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 146 | 147 | end 148 | % ========================================================================= 149 | function h = drawGoodBadFootprint(Z, good, Ybin, titlelabel) 150 | 151 | ubound = ceil(max(Z)); 152 | lbound = floor(min(Z)); 153 | orange = [1.0 0.6471 0.0]; 154 | blue = [0.0 0.0 1.0]; 155 | lbls = {'GOOD','BAD'}; 156 | h = zeros(1,2); 157 | if any(~Ybin) 158 | % drawFootprint(bad, orange, 0.2); 159 | line(Z(~Ybin,1), Z(~Ybin,2), 'LineStyle', 'none', ... 160 | 'Marker', '.', ... 161 | 'Color', orange, ... 162 | 'MarkerFaceColor', orange, ... 163 | 'MarkerSize', 4); 164 | h(2) = patch([0 0],[0 0], orange, 'EdgeColor','none'); 165 | end 166 | if any(Ybin) 167 | line(Z(Ybin,1), Z(Ybin,2), 'LineStyle', 'none', ... 168 | 'Marker', '.', ... 169 | 'Color', blue, ... 170 | 'MarkerFaceColor', blue, ... 171 | 'MarkerSize', 4); 172 | h(1) = patch([0 0],[0 0], blue, 'EdgeColor','none'); 173 | drawFootprint(good, blue, 0.3); 174 | end 175 | xlabel('z_{1}'); ylabel('z_{2}'); title([titlelabel ' Footprints']); 176 | legend(h(h~=0), lbls(h~=0), 'Location', 'NorthEastOutside'); 177 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 178 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 179 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 180 | 181 | end 182 | % ========================================================================= 183 | function handle = drawFootprint(footprint, color, alpha) 184 | % 185 | hold on; 186 | if isempty(footprint) || isempty(footprint.polygon) 187 | handle = patch([0 0],[0 0], color, 'EdgeColor','none'); 188 | return 189 | end 190 | 191 | handle = plot(footprint.polygon,'FaceColor', color, 'EdgeColor','none', 'FaceAlpha', alpha); 192 | hold off; 193 | 194 | end 195 | % ========================================================================= 196 | function h = drawBinaryPerformance(Z, Ybin, titlelabel) 197 | 198 | ubound = ceil(max(Z)); 199 | lbound = floor(min(Z)); 200 | orange = [1.0 0.6471 0.0]; 201 | blue = [0.0 0.0 1.0]; 202 | lbls = {'GOOD','BAD'}; 203 | h = zeros(1,2); 204 | if any(~Ybin) 205 | h(2) = patch([0 0],[0 0], orange, 'EdgeColor','none'); 206 | line(Z(~Ybin,1), Z(~Ybin,2), 'LineStyle', 'none', ... 207 | 'Marker', '.', ... 208 | 'Color', orange, ... 209 | 'MarkerFaceColor', orange, ... 210 | 'MarkerSize', 4); 211 | end 212 | if any(Ybin) 213 | h(1) = patch([0 0],[0 0], blue, 'EdgeColor','none'); 214 | line(Z(Ybin,1), Z(Ybin,2), 'LineStyle', 'none', ... 215 | 'Marker', '.', ... 216 | 'Color', blue, ... 217 | 'MarkerFaceColor', blue, ... 218 | 'MarkerSize', 4); 219 | end 220 | xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); 221 | legend(h(h~=0), lbls(h~=0), 'Location', 'NorthEastOutside'); 222 | set(findall(gcf,'-property','FontSize'),'FontSize',12); 223 | set(findall(gcf,'-property','LineWidth'),'LineWidth',1); 224 | axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); 225 | 226 | end 227 | % ========================================================================= -------------------------------------------------------------------------------- /exploreIS.m: -------------------------------------------------------------------------------- 1 | function out = exploreIS(rootdir) 2 | % ------------------------------------------------------------------------- 3 | % exploreIS.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2019 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | startProcess = tic; 15 | scriptdisc('exploreIS.m'); 16 | % ------------------------------------------------------------------------- 17 | % Collect all the data from the files 18 | disp(['Root Directory: ' rootdir]); 19 | modelfile = [rootdir 'model.mat']; 20 | datafile = [rootdir 'metadata_test.csv']; 21 | if ~isfile(modelfile) || ~isfile(datafile) 22 | error(['Please place the datafiles in the directory ''' rootdir '''']); 23 | end 24 | model = load(modelfile); 25 | disp('-------------------------------------------------------------------------'); 26 | disp('Listing options used:'); 27 | optfields = fieldnames(model.opts); 28 | for i = 1:length(optfields) 29 | disp(optfields{i}); 30 | disp(model.opts.(optfields{i})); 31 | end 32 | disp('-------------------------------------------------------------------------'); 33 | disp('-> Loading the data'); 34 | Xbar = readtable(datafile); 35 | varlabels = Xbar.Properties.VariableNames; 36 | isname = strcmpi(varlabels,'instances'); 37 | isfeat = strncmpi(varlabels,'feature_',8); 38 | isalgo = strncmpi(varlabels,'algo_',5); 39 | issource = strcmpi(varlabels,'source'); 40 | out.data.instlabels = Xbar{:,isname}; 41 | if isnumeric(out.data.instlabels) 42 | out.data.instlabels = num2cell(out.data.instlabels); 43 | out.data.instlabels = cellfun(@(x) num2str(x),out.data.instlabels,'UniformOutput',false); 44 | end 45 | if any(issource) 46 | out.data.S = categorical(Xbar{:,issource}); 47 | end 48 | out.data.X = Xbar{:,isfeat}; 49 | out.data.Y = Xbar{:,isalgo}; 50 | [ninst,nalgos] = size(out.data.Y); 51 | % ------------------------------------------------------------------------- 52 | % HERE CHECK IF THE NUMBER OF ALGORITHMS IS THE SAME AS IN THE MODEL. IF 53 | % NOT, CHECK IF THE NAMES OF THE ALGORITHMS ARE THE SAME, IF NOT, MOVE THE 54 | % DATA IN SUCH WAY THAT THE NON-EXISTING ALGORITHMS ARE MADE NAN AND THE 55 | % NEW ALGORITHMS ARE LAST. 56 | out.data.algolabels = strrep(varlabels(isalgo),'algo_',''); 57 | algoexist = zeros(1,nalgos); 58 | for ii=1:nalgos 59 | aux = find(strcmp(out.data.algolabels{ii},model.data.algolabels)); 60 | if ~isempty(aux) 61 | algoexist(ii) = aux; 62 | end 63 | end 64 | newalgos = sum(algoexist==0); 65 | modelalgos = length(model.data.algolabels); 66 | Yaux = NaN+ones(ninst, modelalgos+newalgos); 67 | lblaux = model.data.algolabels; 68 | acc = modelalgos+1; 69 | for ii=1:nalgos 70 | if algoexist(ii)==0 71 | Yaux(:,acc) = out.data.Y(:,ii); 72 | lblaux(:,acc) = out.data.algolabels(ii); 73 | acc = acc+1; 74 | else 75 | Yaux(:,algoexist(ii)) = out.data.Y(:,ii); 76 | % lblaux(:,acc) = out.data.algolabels(ii); 77 | end 78 | end 79 | out.data.Y = Yaux; 80 | out.data.algolabels = lblaux; 81 | nalgos = size(out.data.Y,2); 82 | % ------------------------------------------------------------------------- 83 | % Storing the raw data for further processing, e.g., graphs 84 | out.data.Xraw = out.data.X; 85 | out.data.Yraw = out.data.Y; 86 | % ------------------------------------------------------------------------- 87 | % Determine whether the performance of an algorithm is a cost measure to 88 | % be minimized or a profit measure to be maximized. Moreover, determine 89 | % whether we are using an absolute threshold as good peformance (the 90 | % algorithm has a performance better than the threshold) or a relative 91 | % performance (the algorithm has a performance that is similar that the 92 | % best algorithm minus a percentage). 93 | disp('-------------------------------------------------------------------------'); 94 | disp('-> Calculating the binary measure of performance'); 95 | msg = '-> An algorithm is good if its performace is '; 96 | MaxPerf = false; 97 | if isfield(model.opts.perf, 'MaxPerf') 98 | MaxPerf = model.opts.perf.MaxPerf; 99 | elseif isfield(model.opts.perf, 'MaxMin') 100 | MaxPerf = model.opts.perf.MaxMin; 101 | else 102 | warning('Can not find parameter "MaxPerf" in the trained model. We are assuming that performance metric is needed to be minimized.'); 103 | end 104 | if MaxPerf 105 | Yaux = out.data.Y; 106 | Yaux(isnan(Yaux)) = -Inf; 107 | [rankPerf,rankAlgo] = sort(Yaux,2,'descend'); 108 | out.data.bestPerformace = rankPerf(:,1); 109 | out.data.P = rankAlgo(:,1); 110 | if model.opts.perf.AbsPerf 111 | out.data.Ybin = out.data.Y>=model.opts.perf.epsilon; 112 | msg = [msg 'higher than ' num2str(model.opts.perf.epsilon)]; 113 | else 114 | out.data.bestPerformace(out.data.bestPerformace==0) = eps; 115 | out.data.Y(out.data.Y==0) = eps; 116 | out.data.Y = 1-bsxfun(@rdivide,out.data.Y,out.data.bestPerformace); 117 | out.data.Ybin = (1-bsxfun(@rdivide,Yaux,out.data.bestPerformace))<=model.opts.perf.epsilon; 118 | msg = [msg 'within ' num2str(round(100.*model.opts.perf.epsilon)) '% of the best.']; 119 | end 120 | else 121 | Yaux = out.data.Y; 122 | Yaux(isnan(Yaux)) = Inf; 123 | [rankPerf,rankAlgo] = sort(Yaux,2,'ascend'); 124 | out.data.bestPerformace = rankPerf(:,1); 125 | out.data.P = rankAlgo(:,1); 126 | if model.opts.perf.AbsPerf 127 | out.data.Ybin = out.data.Y<=model.opts.perf.epsilon; 128 | msg = [msg 'less than ' num2str(model.opts.perf.epsilon)]; 129 | else 130 | out.data.bestPerformace(out.data.bestPerformace==0) = eps; 131 | out.data.Y(out.data.Y==0) = eps; 132 | out.data.Y = bsxfun(@rdivide,out.data.Y,out.data.bestPerformace)-1; 133 | out.data.Ybin = (bsxfun(@rdivide,Yaux,out.data.bestPerformace)-1)<=model.opts.perf.epsilon; 134 | msg = [msg 'within ' num2str(round(100.*model.opts.perf.epsilon)) '% of the best.']; 135 | end 136 | end 137 | disp(msg); 138 | out.data.numGoodAlgos = sum(out.data.Ybin,2); 139 | out.data.beta = out.data.numGoodAlgos>model.opts.perf.betaThreshold*nalgos; 140 | % --------------------------------------------------------------------- 141 | % Automated pre-processing 142 | if model.opts.auto.preproc && model.opts.bound.flag 143 | disp('-------------------------------------------------------------------------'); 144 | disp('-> Auto-pre-processing. Bounding outliers, scaling and normalizing the data.'); 145 | % Eliminate extreme outliers, i.e., any point that exceedes 5 times the 146 | % inter quantile range, by bounding them to that value. 147 | disp('-> Removing extreme outliers from the feature values.'); 148 | himask = bsxfun(@gt,out.data.X,model.bound.hibound); 149 | lomask = bsxfun(@lt,out.data.X,model.bound.lobound); 150 | out.data.X = out.data.X.*~(himask | lomask) + bsxfun(@times,himask,model.bound.hibound) + ... 151 | bsxfun(@times,lomask,model.bound.lobound); 152 | end 153 | 154 | if model.opts.auto.preproc && model.opts.norm.flag 155 | % Normalize the data using Box-Cox and out.pilot.Z-transformations 156 | disp('-> Auto-normalizing the data.'); 157 | out.data.X = bsxfun(@minus,out.data.X,model.norm.minX)+1; 158 | for ii=1:legnth(model.norm.lambdaX) 159 | out.data.X(:,ii) = boxcox(out.data.X(:,ii),model.norm.lambdaX(:,ii)); 160 | end 161 | out.data.X = bsxfun(@rdivide,bsxfun(@minus,out.data.X,model.norm.muX),model.norm.sigmaX); 162 | 163 | % If the algorithm is new, something else should be made... 164 | out.data.Y(out.data.Y==0) = eps; % Assumes that out.data.Y is always positive and higher than 1e-16 165 | for ii=1:modelalgos 166 | out.data.Y(:,ii) = boxcox(out.data.Y(:,ii),model.norm.lambdaY); 167 | end 168 | out.data.Y(:,1:modelalgos) = bsxfun(@rdivide,bsxfun(@minus,out.data.Y(:,1:modelalgos),model.norm.muY),model.norm.sigmaY); 169 | if newalgos>0 170 | [~,out.data.Y(:,modelalgos+1:nalgos),out.norm] = autoNormalize(ones(ninst,1), ... % Dummy variable 171 | out.data.Y(:,modelalgos+1:nalgos)); 172 | end 173 | end 174 | % --------------------------------------------------------------------- 175 | % This is the final subset of features. 176 | out.featsel.idx = model.featsel.idx; 177 | out.data.X = out.data.X(:,out.featsel.idx); 178 | out.data.featlabels = strrep(varlabels(isfeat),'feature_',''); 179 | out.data.featlabels = out.data.featlabels(model.featsel.idx); 180 | % --------------------------------------------------------------------- 181 | % Calculate the two dimensional projection using the PBLDR algorithm 182 | % (Munoz et al. Mach Learn 2018) 183 | out.pilot.Z = out.data.X*model.pilot.A'; 184 | % ------------------------------------------------------------------------- 185 | % Algorithm selection. Fit a model that would separate the space into 186 | % classes of good and bad performance. 187 | out.pythia = PYTHIAtest(model.pythia, out.pilot.Z, out.data.Yraw, ... 188 | out.data.Ybin, out.data.bestPerformace, ... 189 | out.data.algolabels); 190 | % ------------------------------------------------------------------------- 191 | % Validating the footprints 192 | if model.opts.trace.usesim 193 | out.trace = TRACEtest(model.trace, out.pilot.Z, out.pythia.Yhat, ... 194 | out.pythia.selection0, out.data.beta, ... 195 | out.data.algolabels); 196 | % out.trace = TRACE(out.pilot.Z, out.pythia.Yhat, out.pythia.selection0, ... 197 | % out.data.beta, out.data.algolabels, model.opts.trace); 198 | else 199 | out.trace = TRACEtest(model.trace, out.pilot.Z, out.data.Ybin, ... 200 | out.data.P, out.data.beta, ... 201 | out.data.algolabels); 202 | % out.trace = TRACE(out.pilot.Z, out.data.Ybin, out.data.P, out.data.beta,... 203 | % out.data.algolabels, model.opts.trace); 204 | end 205 | 206 | out.opts = model.opts; 207 | % ------------------------------------------------------------------------- 208 | % Writing the results 209 | if model.opts.outputs.csv 210 | scriptcsv(out,rootdir); 211 | if model.opts.outputs.web 212 | scriptweb(out,rootdir); 213 | end 214 | end 215 | 216 | if model.opts.outputs.png 217 | scriptpng(out,rootdir); 218 | end 219 | 220 | disp('-------------------------------------------------------------------------'); 221 | disp('-> Storing the raw MATLAB results for post-processing and/or debugging.'); 222 | save([rootdir 'workspace_test.mat']); % Save the full workspace for debugging 223 | disp(['-> Completed! Elapsed time: ' num2str(toc(startProcess)) 's']); 224 | disp('EOF:SUCCESS'); 225 | end 226 | % ========================================================================= -------------------------------------------------------------------------------- /PYTHIA.m: -------------------------------------------------------------------------------- 1 | function out = PYTHIA(Z, Y, Ybin, Ybest, algolabels, opts) 2 | % ------------------------------------------------------------------------- 3 | % PYTHIA.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | disp(' -> Initializing PYTHIA.'); 15 | [Znorm,out.mu,out.sigma] = zscore(Z); 16 | [ninst,nalgos] = size(Ybin); 17 | out.cp = cell(1,nalgos); 18 | out.svm = cell(1,nalgos); 19 | out.cvcmat = zeros(nalgos,4); 20 | out.Ysub = false & Ybin; 21 | out.Yhat = false & Ybin; 22 | out.Pr0sub = 0.*Ybin; 23 | out.Pr0hat = 0.*Ybin; 24 | out.boxcosnt = zeros(1,nalgos); 25 | out.kscale = out.boxcosnt; 26 | disp('-------------------------------------------------------------------------'); 27 | precalcparams = isfield(opts,'params') && isnumeric(opts.params) && ... 28 | size(opts.params,1)==nalgos && size(opts.params,2)==2; 29 | params = NaN.*ones(nalgos,2); 30 | if opts.ispolykrnl 31 | KernelFcn = 'polynomial'; 32 | else 33 | if ninst>1e3 34 | disp(' -> For datasets larger than 1K Instances, PYTHIA works better with a Polynomial kernel.'); 35 | disp(' -> Consider changing the kernel if the results are unsatisfactory.'); 36 | disp('-------------------------------------------------------------------------'); 37 | end 38 | KernelFcn = 'gaussian'; 39 | end 40 | disp([' -> PYTHIA is using a ' KernelFcn ' kernel ']); 41 | disp('-------------------------------------------------------------------------'); 42 | if opts.uselibsvm 43 | disp(' -> Using LIBSVM''s libraries.'); 44 | if precalcparams 45 | disp(' -> Using pre-calculated hyper-parameters for the SVM.'); 46 | params = opts.params; 47 | else 48 | disp(' -> Search on a latin hyper-cube design will be used for parameter hyper-tunning.'); 49 | end 50 | else 51 | disp(' -> Using MATLAB''s SVM libraries.'); 52 | if precalcparams 53 | disp(' -> Using pre-calculated hyper-parameters for the SVM.'); 54 | params = opts.params; 55 | else 56 | disp(' -> Bayesian Optimization will be used for parameter hyper-tunning.'); 57 | end 58 | disp('-------------------------------------------------------------------------'); 59 | if opts.useweights 60 | disp(' -> PYTHIA is using cost-sensitive classification'); 61 | out.W = abs(Y-nanmean(Y(:))); 62 | out.W(out.W==0) = min(out.W(out.W~=0)); 63 | out.W(isnan(out.W)) = max(out.W(~isnan(out.W))); 64 | Waux = out.W; 65 | else 66 | disp(' -> PYTHIA is not using cost-sensitive classification'); 67 | Waux = ones(ninst,nalgos); 68 | end 69 | end 70 | disp('-------------------------------------------------------------------------'); 71 | disp([' -> Using a ' num2str(opts.cvfolds) ... 72 | '-fold stratified cross-validation experiment to evaluate the SVMs.']); 73 | disp('-------------------------------------------------------------------------'); 74 | disp(' -> Training has started. PYTHIA may take a while to complete...'); 75 | t = tic; 76 | for i=1:nalgos 77 | tic; 78 | state = rng; 79 | rng('default'); 80 | out.cp{i} = cvpartition(Ybin(:,i),'Kfold',opts.cvfolds,'Stratify',true); 81 | if opts.uselibsvm 82 | [out.svm{i},out.Ysub(:,i),out.Pr0sub(:,i),out.Yhat(:,i),... 83 | out.Pr0hat(:,i),out.boxcosnt(i),out.kscale(i)] = fitlibsvm(Znorm,Ybin(:,i),... 84 | out.cp{i},KernelFcn,... 85 | params(i,:)); 86 | else 87 | [out.svm{i},out.Ysub(:,i),out.Pr0sub(:,i),out.Yhat(:,i),... 88 | out.Pr0hat(:,i),out.boxcosnt(i),out.kscale(i)] = fitmatsvm(Znorm,Ybin(:,i),... 89 | Waux(:,i),out.cp{i},... 90 | KernelFcn,params(i,:)); 91 | end 92 | rng(state); 93 | aux = confusionmat(Ybin(:,i),out.Ysub(:,i)); 94 | if numel(aux)~=4 95 | caux = aux; 96 | aux = zeros(2); 97 | if all(Ybin(:,i)==0) 98 | if all(out.Ysub(:,i)==0) 99 | aux(1,1) = caux; 100 | elseif all(out.Ysub(:,i)==1) 101 | aux(2,1) = caux; 102 | end 103 | elseif all(Ybin(:,i)==1) 104 | if all(out.Ysub(:,i)==0) 105 | aux(1,2) = caux; 106 | elseif all(out.Ysub(:,i)==1) 107 | aux(2,2) = caux; 108 | end 109 | end 110 | end 111 | out.cvcmat(i,:) = aux(:); 112 | if i==nalgos 113 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 114 | ''', there are no models left to train.']); 115 | elseif i==nalgos-1 116 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 117 | ''', there is 1 model left to train.']); 118 | else 119 | disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... 120 | ''', there are ' num2str(nalgos-i) ' models left to train.']); 121 | end 122 | disp([' -> Elapsed time: ' num2str(toc,'%.2f\n') 's']); 123 | end 124 | tn = out.cvcmat(:,1); 125 | fp = out.cvcmat(:,3); 126 | fn = out.cvcmat(:,2); 127 | tp = out.cvcmat(:,4); 128 | out.precision = tp./(tp+fp); 129 | out.recall = tp./(tp+fn); 130 | out.accuracy = (tp+tn)./ninst; 131 | disp('-------------------------------------------------------------------------'); 132 | disp(' -> PYTHIA has completed training the models.'); 133 | disp([' -> The average cross validated precision is: ' ... 134 | num2str(round(100.*mean(out.precision),1)) '%']); 135 | disp([' -> The average cross validated accuracy is: ' ... 136 | num2str(round(100.*mean(out.accuracy),1)) '%']); 137 | disp([' -> Elapsed time: ' num2str(toc(t),'%.2f\n') 's']); 138 | disp('-------------------------------------------------------------------------'); 139 | % We assume that the most precise SVM (as per CV-Precision) is the most 140 | % reliable. 141 | if nalgos>1 142 | [best,out.selection0] = max(bsxfun(@times,out.Yhat,out.precision'),[],2); 143 | else 144 | best = out.Yhat; 145 | out.selection0 = out.Yhat; 146 | end 147 | [~,default] = max(mean(Ybin)); 148 | out.selection1 = out.selection0; 149 | out.selection0(best<=0) = 0; 150 | out.selection1(best<=0) = default; 151 | 152 | sel0 = bsxfun(@eq,out.selection0,1:nalgos); 153 | sel1 = bsxfun(@eq,out.selection1,1:nalgos); 154 | avgperf = nanmean(Y); 155 | stdperf = nanstd(Y); 156 | Yfull = Y; 157 | Ysvms = Y; 158 | Y(~sel0) = NaN; 159 | Yfull(~sel1) = NaN; 160 | Ysvms(~out.Yhat) = NaN; 161 | 162 | pgood = mean(any( Ybin & sel1,2)); 163 | fb = sum(any( Ybin & ~sel0,2)); 164 | fg = sum(any(~Ybin & sel0,2)); 165 | tg = sum(any( Ybin & sel0,2)); 166 | precisionsel = tg./(tg+fg); 167 | recallsel = tg./(tg+fb); 168 | 169 | disp(' -> PYTHIA is preparing the summary table.'); 170 | out.summary = cell(nalgos+3, 11); 171 | out.summary{1,1} = 'Algorithms '; 172 | out.summary(2:end-2, 1) = algolabels; 173 | out.summary(end-1:end, 1) = {'Oracle','Selector'}; 174 | out.summary(1, 2:11) = {'Avg_Perf_all_instances'; 175 | 'Std_Perf_all_instances'; 176 | 'Probability_of_good'; 177 | 'Avg_Perf_selected_instances'; 178 | 'Std_Perf_selected_instances'; 179 | 'CV_model_accuracy'; 180 | 'CV_model_precision'; 181 | 'CV_model_recall'; 182 | 'BoxConstraint'; 183 | 'KernelScale'}; 184 | out.summary(2:end, 2) = num2cell(round([avgperf nanmean(Ybest) nanmean(Yfull(:))],3)); 185 | out.summary(2:end, 3) = num2cell(round([stdperf nanstd(Ybest) nanstd(Yfull(:))],3)); 186 | out.summary(2:end, 4) = num2cell(round([mean(Ybin) 1 pgood],3)); 187 | out.summary(2:end, 5) = num2cell(round([nanmean(Ysvms) NaN nanmean(Y(:))],3)); 188 | out.summary(2:end, 6) = num2cell(round([nanstd(Ysvms) NaN nanstd(Y(:))],3)); 189 | out.summary(2:end, 7) = num2cell(round(100.*[out.accuracy' NaN NaN],1)); 190 | out.summary(2:end, 8) = num2cell(round(100.*[out.precision' NaN precisionsel],1)); 191 | out.summary(2:end, 9) = num2cell(round(100.*[out.recall' NaN recallsel],1)); 192 | out.summary(2:end-2, 10) = num2cell(round(out.boxcosnt,3)); 193 | out.summary(2:end-2, 11) = num2cell(round(out.kscale,3)); 194 | out.summary(cellfun(@(x) all(isnan(x)),out.summary)) = {[]}; % Clean up. Not really needed 195 | disp(' -> PYTHIA has completed! Performance of the models:'); 196 | disp(' '); 197 | disp(out.summary); 198 | 199 | end 200 | % ========================================================================= 201 | % SUBFUNCTIONS 202 | % ========================================================================= 203 | function [svm,Ysub,Psub,Yhat,Phat,C,g] = fitlibsvm(Z,Ybin,cp,k,params) 204 | 205 | ninst = size(Z,1); 206 | maxgrid = 4; 207 | mingrid = -10; 208 | if any(isnan(params)) 209 | rng('default'); 210 | nvals = 30; 211 | paramgrid = sortrows(2.^((maxgrid-mingrid).*lhsdesign(nvals,2) + mingrid)); 212 | else 213 | nvals = 1; 214 | paramgrid = params; 215 | end 216 | Ybin = double(Ybin)+1; 217 | Ysub = zeros(ninst,nvals); 218 | Psub = zeros(ninst,nvals); 219 | 220 | if strcmp(k,'polynomial') 221 | k = 1; 222 | else 223 | k = 2; 224 | end 225 | 226 | if exist('gcp','file')==2 227 | mypool = gcp('nocreate'); 228 | if ~isempty(mypool) 229 | nworkers = mypool.NumWorkers; 230 | else 231 | nworkers = 0; 232 | end 233 | else 234 | nworkers = 0; 235 | end 236 | 237 | for jj=1:cp.NumTestSets 238 | idx = cp.training(jj); 239 | Ztrain = Z(idx,:); 240 | Ytrain = Ybin(idx); 241 | Ztest = Z(~idx,:); 242 | Ytest = Ybin(~idx); 243 | Yaux = zeros(sum(~idx),nvals); 244 | Paux = zeros(sum(~idx),nvals); 245 | parfor (ii=1:nvals,nworkers) 246 | cparams = paramgrid(ii,:); 247 | prior = mean(bsxfun(@eq,Ytrain,[1 2])); 248 | command = ['-s 0 -t ' num2str(k) ' -q -b 1 -c ' num2str(cparams(1)) ... 249 | ' -g ' num2str(cparams(2)) ' -w1 1 -w2 ' num2str(prior(1)./prior(2),4)]; 250 | rng('default'); 251 | svm = svmtrain(Ytrain, Ztrain, command); %#ok 252 | [Yaux(:,ii),~,Paux(:,ii)] = svmpredict(Ytest, Ztest, svm, '-q'); 253 | end 254 | for ii=1:nvals 255 | Ysub(~idx,ii) = Yaux(:,ii); 256 | Psub(~idx,ii) = Paux(:,ii); 257 | end 258 | end 259 | [~,idx] = min(mean(bsxfun(@ne,Ysub,Ybin),1)); 260 | Ysub = Ysub(:,idx)==2; 261 | Psub = Psub(:,idx); 262 | 263 | C = paramgrid(idx,1); 264 | g = paramgrid(idx,2); 265 | prior = mean(bsxfun(@eq,Ybin,[1 2])); 266 | command = ['-s 0 -t ' num2str(k) ' -q -b 1 -c ' num2str(C) ' -g ' num2str(g) ... 267 | ' -w1 1 -w2 ' num2str(prior(1)./prior(2),4)]; 268 | rng('default'); 269 | svm = svmtrain(Ybin, Z, command); %#ok 270 | [Yhat,~,Phat] = svmpredict(Ybin, Z, svm, '-q'); 271 | Yhat = Yhat==2; 272 | 273 | end 274 | % ========================================================================= 275 | function [svm,Ysub,Psub,Yhat,Phat,C,g] = fitmatsvm(Z,Ybin,W,cp,k,params) 276 | 277 | if exist('gcp','file')==2 278 | mypool = gcp('nocreate'); 279 | if ~isempty(mypool) 280 | nworkers = mypool.NumWorkers; 281 | else 282 | nworkers = 0; 283 | end 284 | else 285 | nworkers = 0; 286 | end 287 | 288 | if any(isnan(params)) 289 | rng('default'); 290 | hypparams = hyperparameters('fitcsvm',Z,Ybin); 291 | hypparams = hypparams(1:2); 292 | hypparams(1).Range = 2.^[-10,4]; 293 | hypparams(2).Range = hypparams(1).Range; 294 | svm = fitcsvm(Z,Ybin,'Standardize',false,... 295 | 'Weights',W,... 296 | 'CacheSize','maximal',... 297 | 'RemoveDuplicates',true,... 298 | 'KernelFunction',k,... 299 | 'OptimizeHyperparameters',hypparams,... 300 | 'HyperparameterOptimizationOptions',... 301 | struct('CVPartition',cp,... 302 | 'Verbose',0,... 303 | 'AcquisitionFunctionName','probability-of-improvement',... 304 | 'ShowPlots',false,... 305 | 'UseParallel',nworkers~=0)); 306 | svm = fitSVMPosterior(svm); 307 | C = svm.HyperparameterOptimizationResults.bestPoint{1,1}; 308 | g = svm.HyperparameterOptimizationResults.bestPoint{1,2}; 309 | [Ysub,aux] = svm.resubPredict; 310 | Psub = aux(:,1); 311 | [Yhat,aux] = svm.predict(Z); 312 | Phat = aux(:,1); 313 | else 314 | C = params(1); 315 | g = params(2); 316 | rng('default'); 317 | svm = fitcsvm(Z,Ybin,'Standardize',false,... 318 | 'Weights',W,... 319 | 'CacheSize','maximal',... 320 | 'RemoveDuplicates',true,... 321 | 'KernelFunction',k,... 322 | 'CVPartition',cp,... 323 | 'BoxConstraint',C,... 324 | 'KernelScale',g); 325 | svm = fitSVMPosterior(svm); 326 | [Ysub,aux] = svm.kfoldPredict; 327 | Psub = aux(:,1); 328 | rng('default'); 329 | svm = fitcsvm(Z,Ybin,'Standardize',false,... 330 | 'Weights',W,... 331 | 'CacheSize','maximal',... 332 | 'RemoveDuplicates',true,... 333 | 'KernelFunction',k,... 334 | 'BoxConstraint',C,... 335 | 'KernelScale',g); 336 | svm = fitSVMPosterior(svm); 337 | [Yhat,aux] = svm.predict(Z); 338 | Phat = aux(:,1); 339 | end 340 | 341 | end 342 | % ========================================================================= 343 | -------------------------------------------------------------------------------- /TRACE.m: -------------------------------------------------------------------------------- 1 | function out = TRACE(Z, Ybin, P, beta, algolabels, opts) 2 | % ------------------------------------------------------------------------- 3 | % TRACE.m 4 | % ------------------------------------------------------------------------- 5 | % 6 | % By: Mario Andres Munoz Acosta 7 | % School of Mathematics and Statistics 8 | % The University of Melbourne 9 | % Australia 10 | % 2020 11 | % 12 | % ------------------------------------------------------------------------- 13 | 14 | if exist('gcp','file')==2 15 | mypool = gcp('nocreate'); 16 | if ~isempty(mypool) 17 | nworkers = mypool.NumWorkers; 18 | else 19 | nworkers = 0; 20 | end 21 | else 22 | nworkers = 0; 23 | end 24 | % ------------------------------------------------------------------------- 25 | % First step is to transform the data to the footprint space, and to 26 | % calculate the 'space' footprint. This is also the maximum area possible 27 | % for a footprint. 28 | disp(' -> TRACE is calculating the space area and density.'); 29 | ninst = size(Z,1); 30 | nalgos = size(Ybin,2); 31 | out.space = TRACEbuild(Z, true(ninst,1), opts); 32 | disp([' -> Space area: ' num2str(out.space.area) ... 33 | ' | Space density: ' num2str(out.space.density)]); 34 | % ------------------------------------------------------------------------- 35 | % This loop will calculate the footprints for good/bad instances and the 36 | % best algorithm. 37 | disp('-------------------------------------------------------------------------'); 38 | disp(' -> TRACE is calculating the algorithm footprints.'); 39 | good = cell(1,nalgos); 40 | best = cell(1,nalgos); 41 | % Use the actual data to calculate the footprints 42 | parfor (i=1:nalgos,nworkers) 43 | tic; 44 | disp([' -> Good performance footprint for ''' algolabels{i} '''']); 45 | good{i} = TRACEbuild(Z, Ybin(:,i), opts); 46 | disp([' -> Best performance footprint for ''' algolabels{i} '''']); 47 | best{i} = TRACEbuild(Z, P==i, opts); 48 | disp([' -> Algorithm ''' algolabels{i} ''' completed. Elapsed time: ' num2str(toc,'%.2f\n') 's']); 49 | end 50 | out.good = good; 51 | out.best = best; 52 | % ------------------------------------------------------------------------- 53 | % Detecting collisions and removing them. 54 | disp('-------------------------------------------------------------------------'); 55 | disp(' -> TRACE is detecting and removing contradictory sections of the footprints.'); 56 | for i=1:nalgos 57 | disp([' -> Base algorithm ''' algolabels{i} '''']); 58 | startBase = tic; 59 | for j=i+1:nalgos 60 | disp([' -> TRACE is comparing ''' algolabels{i} ''' with ''' algolabels{j} '''']); 61 | startTest = tic; 62 | [out.best{i}, out.best{j}] = TRACEcontra(out.best{i}, out.best{j}, ... 63 | Z, P==i, P==j, opts);%, false); 64 | 65 | disp([' -> Test algorithm ''' algolabels{j} ... 66 | ''' completed. Elapsed time: ' num2str(toc(startTest),'%.2f\n') 's']); 67 | end 68 | disp([' -> Base algorithm ''' algolabels{i} ... 69 | ''' completed. Elapsed time: ' num2str(toc(startBase),'%.2f\n') 's']); 70 | end 71 | % ------------------------------------------------------------------------- 72 | % Beta hard footprints. First step is to calculate them. 73 | disp('-------------------------------------------------------------------------'); 74 | disp(' -> TRACE is calculating the beta-footprint.'); 75 | out.hard = TRACEbuild(Z, ~beta, opts); 76 | % ------------------------------------------------------------------------- 77 | % Calculating performance 78 | disp('-------------------------------------------------------------------------'); 79 | disp(' -> TRACE is preparing the summary table.'); 80 | out.summary = cell(nalgos+1,11); 81 | out.summary(1,2:end) = {'Area_Good',... 82 | 'Area_Good_Normalized',... 83 | 'Density_Good',... 84 | 'Density_Good_Normalized',... 85 | 'Purity_Good',... 86 | 'Area_Best',... 87 | 'Area_Best_Normalized',... 88 | 'Density_Best',... 89 | 'Density_Best_Normalized',... 90 | 'Purity_Best'}; 91 | out.summary(2:end,1) = algolabels; 92 | for i=1:nalgos 93 | row = [TRACEsummary(out.good{i}, out.space.area, out.space.density), ... 94 | TRACEsummary(out.best{i}, out.space.area, out.space.density)]; 95 | out.summary(i+1,2:end) = num2cell(round(row,3)); 96 | end 97 | 98 | disp(' -> TRACE has completed. Footprint analysis results:'); 99 | disp(' '); 100 | disp(out.summary); 101 | 102 | end 103 | % ========================================================================= 104 | % SUBFUNCTIONS 105 | % ========================================================================= 106 | function footprint = TRACEbuild(Z, Ybin, opts) 107 | 108 | % If there is no Y to work with, then there is not point on this one 109 | Ig = unique(Z(Ybin,:),'rows'); % There might be points overlapped, so eliminate them to avoid problems 110 | if size(Ig,1)<3 111 | footprint = TRACEthrow; 112 | else 113 | footprint = struct; 114 | end 115 | 116 | nn = max(min(ceil(sum(Ybin)/20),50),3); 117 | class = dbscan(Ig,nn); % Use DBSCAN to identify dense regions 118 | flag = false; 119 | for i=1:max(class) %Ignore -1/0 120 | polydata = Ig(class==i,:); 121 | polydata = polydata(boundary(polydata,1),:); 122 | aux = TRACEfitpoly(polydata,Z,Ybin, opts); 123 | if ~isempty(aux) 124 | if ~flag 125 | footprint.polygon = aux; 126 | flag = true; 127 | else 128 | footprint.polygon = union(footprint.polygon,aux); 129 | end 130 | end 131 | end 132 | if isfield(footprint,'polygon') && ~isempty(footprint.polygon) 133 | footprint.polygon = rmslivers(footprint.polygon,1e-2); 134 | footprint.area = area(footprint.polygon); 135 | footprint.elements = sum(isinterior(footprint.polygon,Z)); 136 | footprint.goodElements = sum(isinterior(footprint.polygon,Z(Ybin,:))); 137 | footprint.density = footprint.elements./footprint.area; 138 | footprint.purity = footprint.goodElements./footprint.elements; 139 | else 140 | footprint = TRACEthrow; 141 | end 142 | 143 | end 144 | % ========================================================================= 145 | function [base,test] = TRACEcontra(base,test,Z,Ybase,Ytest,opts)%,isbin) 146 | % 147 | if isempty(base.polygon) || isempty(test.polygon) 148 | return; 149 | end 150 | 151 | maxtries = 3; % Tries once to tighten the bounds. 152 | numtries = 1; 153 | contradiction = intersect(base.polygon,test.polygon); 154 | while contradiction.NumRegions~=0 && numtries<=maxtries 155 | numElements = sum(isinterior(contradiction,Z)); 156 | numGoodElementsBase = sum(isinterior(contradiction,Z(Ybase,:))); 157 | numGoodElementsTest = sum(isinterior(contradiction,Z(Ytest,:))); 158 | purityBase = numGoodElementsBase/numElements; 159 | purityTest = numGoodElementsTest/numElements; 160 | if purityBase>purityTest %&& (~isbin || (purityBase>0.55 && isbin)) 161 | carea = area(contradiction)./area(test.polygon); 162 | disp([' -> ' num2str(round(100.*carea,1)) '%' ... 163 | ' of the test footprint is contradictory.']); 164 | test.polygon = subtract(test.polygon,contradiction); 165 | if numtriespurityBase %&& (~isbin || (purityTest>0.55 && isbin)) 169 | carea = area(contradiction)./area(base.polygon); 170 | disp([' -> ' num2str(round(100.*carea,1)) '%' ... 171 | ' of the base footprint is contradictory.']); 172 | base.polygon = subtract(base.polygon,contradiction); 173 | if numtries Purity of the contradicting areas is equal for both footprints.'); 178 | disp(' -> Ignoring the contradicting area.'); 179 | break; 180 | end 181 | if isempty(base.polygon) || isempty(test.polygon) 182 | break; 183 | else 184 | contradiction = intersect(base.polygon,test.polygon); 185 | end 186 | numtries = numtries+1; 187 | end 188 | 189 | if isempty(base.polygon) 190 | base = TRACEthrow; 191 | else 192 | base.area = area(base.polygon); 193 | base.elements = sum(isinterior(base.polygon,Z)); 194 | base.goodElements = sum(isinterior(base.polygon,Z(Ybase,:))); 195 | base.density = base.elements./base.area; 196 | base.purity = base.goodElements./base.elements; 197 | end 198 | if isempty(test.polygon) 199 | test = TRACEthrow; 200 | else 201 | test.area = area(test.polygon); 202 | test.elements = sum(isinterior(test.polygon,Z)); 203 | test.goodElements = sum(isinterior(test.polygon,Z(Ytest,:))); 204 | test.density = test.elements./test.area; 205 | test.purity = test.goodElements./test.elements; 206 | end 207 | 208 | end 209 | % ========================================================================= 210 | function polygon = TRACEtight(polygon,Z,Ybin,opts) 211 | 212 | splits = regions(polygon); 213 | nregions = length(splits); 214 | flags = true(1,nregions); 215 | for i=1:nregions 216 | % Find the vertex of this polygon 217 | criteria = isinterior(splits(i),Z) & Ybin; 218 | polydata = Z(criteria,:); 219 | if size(polydata,1)<3 220 | flags(i) = false; 221 | continue 222 | end 223 | aux = TRACEfitpoly(polydata(boundary(polydata,1),:),Z,Ybin,opts); 224 | if isempty(aux) 225 | flags(i) = false; 226 | continue 227 | end 228 | splits(i) = aux; 229 | end 230 | if any(flags) 231 | polygon = union(splits(flags)); 232 | else 233 | polygon = []; 234 | end 235 | 236 | end 237 | % ========================================================================= 238 | function polygon = TRACEfitpoly(polydata,Z,Ybin,opts) 239 | 240 | warning('off','MATLAB:polyshape:repairedBySimplify'); 241 | 242 | if size(polydata,1)<3 243 | polygon = []; 244 | warning('on','MATLAB:polyshape:repairedBySimplify'); 245 | return 246 | end 247 | 248 | polygon = polyshape(polydata,'Simplify',true); 249 | polygon = rmslivers(polygon,5e-2); 250 | 251 | if ~all(Ybin) 252 | if polygon.NumRegions<1 253 | polygon = []; 254 | warning('on','MATLAB:polyshape:repairedBySimplify'); 255 | return 256 | end 257 | tri = triangulation(polygon); 258 | nrow = size(tri.ConnectivityList,1); 259 | for ii=1:nrow 260 | tridata = tri.Points(tri.ConnectivityList(ii,:),:); 261 | piece = polyshape(tridata,'Simplify',true); 262 | elements = sum(isinterior(piece,Z)); 263 | goodElements = sum(isinterior(piece,Z(Ybin,:))); 264 | if opts.PI>(goodElements/elements) 265 | polygon = subtract(polygon,piece); 266 | end 267 | end 268 | end 269 | 270 | warning('on','MATLAB:polyshape:repairedBySimplify'); 271 | 272 | end 273 | % ========================================================================= 274 | function out = TRACEsummary(footprint, spaceArea, spaceDensity) 275 | % 276 | out = [footprint.area,... 277 | footprint.area/spaceArea,... 278 | footprint.density,... 279 | footprint.density/spaceDensity,... 280 | footprint.purity]; 281 | out(isnan(out)) = 0; 282 | 283 | end 284 | % ========================================================================= 285 | function footprint = TRACEthrow 286 | 287 | disp(' -> There are not enough instances to calculate a footprint.'); 288 | disp(' -> The subset of instances used is too small.'); 289 | footprint.polygon = []; 290 | footprint.area = 0; 291 | footprint.elements = 0; 292 | footprint.goodElements = 0; 293 | footprint.density = 0; 294 | footprint.purity = 0; 295 | 296 | end 297 | % ========================================================================= 298 | % Function: [class,type]=dbscan(x,k,Eps) 299 | % ------------------------------------------------------------------------- 300 | % Aim: 301 | % Clustering the data with Density-Based Scan Algorithm with Noise (DBSCAN) 302 | % ------------------------------------------------------------------------- 303 | % Input: 304 | % x - data set (m,n); m-objects, n-variables 305 | % k - number of objects in a neighborhood of an object 306 | % (minimal number of objects considered as a cluster) 307 | % Eps - neighborhood radius, if not known avoid this parameter or put [] 308 | % ------------------------------------------------------------------------- 309 | % Output: 310 | % class - vector specifying assignment of the i-th object to certain 311 | % cluster (m,1) 312 | % type - vector specifying type of the i-th object 313 | % (core: 1, border: 0, outlier: -1) 314 | % ------------------------------------------------------------------------- 315 | % Example of use: 316 | % x=[randn(30,2)*.4;randn(40,2)*.5+ones(40,1)*[4 4]]; 317 | % [class,type]=dbscan(x,5,[]); 318 | % ------------------------------------------------------------------------- 319 | % References: 320 | % [1] M. Ester, H. Kriegel, J. Sander, X. Xu, A density-based algorithm for 321 | % discovering clusters in large spatial databases with noise, proc. 322 | % 2nd Int. Conf. on Knowledge Discovery and Data Mining, Portland, OR, 1996, 323 | % p. 226, available from: 324 | % www.dbs.informatik.uni-muenchen.de/cgi-bin/papers?query=--CO 325 | % [2] M. Daszykowski, B. Walczak, D. L. Massart, Looking for 326 | % Natural Patterns in Data. Part 1: Density Based Approach, 327 | % Chemom. Intell. Lab. Syst. 56 (2001) 83-92 328 | % ------------------------------------------------------------------------- 329 | % Written by Michal Daszykowski 330 | % Department of Chemometrics, Institute of Chemistry, 331 | % The University of Silesia 332 | % December 2004 333 | % http://www.chemometria.us.edu.pl 334 | 335 | function [class,type]=dbscan(x,k,Eps) 336 | 337 | m=size(x,1); 338 | 339 | if nargin<3 || isempty(Eps) 340 | [Eps]=epsilon(x,k); 341 | end 342 | 343 | x=[(1:m)' x]; 344 | [m,n]=size(x); 345 | type=zeros(1,m); 346 | no=1; 347 | touched=zeros(m,1); 348 | class=zeros(1,m); 349 | for i=1:m 350 | if touched(i)==0 351 | ob=x(i,:); 352 | D=dist(ob(2:n),x(:,2:n)); 353 | ind=find(D<=Eps); 354 | 355 | if length(ind)>1 && length(ind)=k+1 366 | type(i)=1; 367 | class(ind)=ones(length(ind),1)*max(no); 368 | 369 | while ~isempty(ind) 370 | ob=x(ind(1),:); 371 | touched(ind(1))=1; 372 | ind(1)=[]; 373 | D=dist(ob(2:n),x(:,2:n)); 374 | i1=find(D<=Eps); 375 | 376 | if length(i1)>1 377 | class(i1)=no; 378 | if length(i1)>=k+1 379 | type(ob(1))=1; 380 | else 381 | type(ob(1))=0; 382 | end 383 | 384 | for j=1:length(i1) 385 | if touched(i1(j))==0 386 | touched(i1(j))=1; 387 | ind=[ind i1(j)]; 388 | class(i1(j))=no; 389 | end 390 | end 391 | end 392 | end 393 | no=no+1; 394 | end 395 | end 396 | end 397 | 398 | i1=find(class==0); 399 | class(i1)=-1; 400 | type(i1)=-1; 401 | 402 | end 403 | % ========================================================================= 404 | function [Eps]=epsilon(x,k) 405 | 406 | % Function: [Eps]=epsilon(x,k) 407 | % 408 | % Aim: 409 | % Analytical way of estimating neighborhood radius for DBSCAN 410 | % 411 | % Input: 412 | % x - data matrix (m,n); m-objects, n-variables 413 | % k - number of objects in a neighborhood of an object 414 | % (minimal number of objects considered as a cluster) 415 | 416 | [m,n]=size(x); 417 | 418 | Eps=((prod(max(x)-min(x))*k*gamma(.5*n+1))/(m*sqrt(pi.^n))).^(1/n); 419 | 420 | end 421 | % ========================================================================= 422 | function [D]=dist(i,x) 423 | 424 | % function: [D]=dist(i,x) 425 | % 426 | % Aim: 427 | % Calculates the Euclidean distances between the i-th object and all objects in x 428 | % 429 | % Input: 430 | % i - an object (1,n) 431 | % x - data matrix (m,n); m-objects, n-variables 432 | % 433 | % Output: 434 | % D - Euclidean distance (m,1) 435 | 436 | [m,n]=size(x); 437 | D=sqrt(sum((((ones(m,1)*i)-x).^2)')); 438 | 439 | if n==1 440 | D=abs((ones(m,1)*i-x))'; 441 | end 442 | 443 | end 444 | % ========================================================================= -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Instance Space Analysis: A toolkit for the assessment of algorithmic power 2 | 3 | [![View InstanceSpace on File Exchange](https://www.mathworks.com/matlabcentral/images/matlab-file-exchange.svg)](https://au.mathworks.com/matlabcentral/fileexchange/75170-instancespace) 4 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4750845.svg)](https://doi.org/10.5281/zenodo.4750845) 5 | 6 | Instance Space Analysis is a methodology for the assessment of the strengths and weaknesses of an algorithm, and an approach to objectively compare algorithmic power without bias introduced by restricted choice of test instances. At its core is the modelling of the relationship between structural properties of an instance and the performance of a group of algorithms. Instance Space Analysis allows the construction of **footprints** for each algorithm, defined as regions in the instance space where we statistically infer good performance. Other insights that can be gathered from Instance Space Analysis include: 7 | 8 | - Objective metrics of each algorithm’s footprint across the instance space as a measure of algorithmic power; 9 | - Explanation through visualisation of how instance features correlate with algorithm performance in various regions of the instance space; 10 | - Visualisation of the distribution and diversity of existing benchmark and real-world instances; 11 | - Assessment of the adequacy of the features used to characterise an instance; 12 | - Partitioning of the instance space into recommended regions for automated algorithm selection; 13 | - Distinguishing areas of the instance space where it may be useful to generate additional instances to gain further insights. 14 | 15 | The unique advantage of visualizing algorithm performance in the instance space, rather than as a small set of summary statistics averaged across a selected collection of instances, is the nuanced analysis that becomes possible to explain strengths and weaknesses and examine interesting variations in performance that may be hidden by tables of summary statistics. 16 | 17 | This repository provides a set of MATLAB tools to carry out a complete Instance Space Analysis in an automated pipeline. It is also the computational engine that powers the Melbourne Algorithm Test Instance Library with Data Analytics ([MATILDA](http://matilda.unimelb.edu.au/matilda/)) web tools for online analysis. For further information on the Instance Space Analysis methodology can be found [here](http://matilda.unimelb.edu.au/matilda/our-methodology). 18 | 19 | If you follow the Instance Space Analysis methodology, please cite as follows: 20 | 21 | > K. Smith-Miles and M.A. Muñoz. *Instance Space Analysis for Algorithm Testing: Methodology and Software Tools*. ACM Comput. Surv. 55(12:255),1-31 [DOI:10.1145/3572895](https://doi.org/10.1145/3572895), 2023. 22 | 23 | Also, if you specifically use this code, please cite as follows: 24 | 25 | > M.A. Muñoz and K. Smith-Miles. *Instance Space Analysis: A toolkit for the assessment of algorithmic power*. andremun/InstanceSpace on Github. Zenodo, [DOI:10.5281/zenodo.4484107](https://doi.org/10.5281/zenodo.4484107), 2020. 26 | 27 | Or if you specifically use [MATILDA](http://matilda.unimelb.edu.au/matilda/), please cite as follows: 28 | 29 | > K. Smith-Miles, M.A. Muñoz and Neelofar. *Melbourne Algorithm Test Instance Library with Data Analytics (MATILDA)*. Available at (https://matilda.unimelb.edu.au). 2020. 30 | 31 | **DISCLAIMER: This repository contains research code. In occassions new features will be added or changes are made that may result in crashes. Although we have have made every effort to reduce bugs, this code has NO GUARANTIES. If you find issues, let us know ASAP through the contact methods described at the end of this document.** 32 | 33 | ## Installation Instructions 34 | 35 | The main requirement for the software to run is to have a current version of [MATLAB](http://www.mathworks.com), with the [Communications](https://au.mathworks.com/products/communications.html), [Financial](https://au.mathworks.com/products/finance.html), [Global Optimization](https://au.mathworks.com/help/gads/index.html), [Parallel Computing](https://www.mathworks.com/products/parallel-computing.html), [Optimization](https://au.mathworks.com/products/optimization.html), and [Statistics and Machine Learning](https://au.mathworks.com/help/stats/index.html) toolboxes installed. It has been tested and known to work properly in Windows 10 with MATLAB version r2018b. Earlier versions of MATLAB may fail to support several functions being used. Although compiled MEX-files for external libraries, such as [LIBSVM](https://www.csie.ntu.edu.tw/~cjlin/libsvm/), are being provided for Windows, these must be downloaded and compiled for the appropriate environment. 36 | 37 | ## Working with the code 38 | 39 | The main interfase is the script ```example.m``` which provides the path for the ```metadata.csv``` file, and constructs the ```options.json``` file. The path provided will also be the location of all the software outputs, such as images (in ```.png``` format), tables (in ```.csv``` format) and raw intermediate data (in ```.mat``` format). 40 | 41 | ## The metadata file 42 | 43 | The ```metadata.csv``` file should contain a table where each row corresponds to a problem instance, and each column must strictly follow the naming convention mentioned below: 44 | 45 | - **instances** instance identifier - We expect instance identifier to be of type "String". This column is mandatory. 46 | - **source** instance source - This column is optional 47 | - **feature_name** The keyword "feature_" concatenated with feature name. For instance, if feature name is "density", header name should be mentioned as "feature_density". If name consists of more than one word, each word should be separated by "_" (spaces are not allowed). There must be more than two features for the software to work. We expect the features to be of the type "Double". 48 | - **algo_name** The keyword "algo_" concatenated with algorithm name. For instance, if algorithm name is "Greedy", column header should be "algo_greedy". If name consists of more than one word, each word should be separated by "_" (spaces are not allowed). You can add the performance of more than one algorithm in the same ```.csv```. We expect the algorithm performance to be of the type "Double". 49 | 50 | Moreover, empty cells, NaN or null values are allowed but **not recommended**. We expect you to handle missing values in your data before processing. You may use [this file](https://matilda.unimelb.edu.au/matilda/matildadata/graph_coloring_problem/metadata/metadata.csv) as reference. 51 | 52 | ## Options 53 | 54 | The script ```example.m``` constructs a structure that contains all the settings used by the code. Broadly, there are settings required for the analysis itself, settings for the pre-processing of the data, and output settings. For the first these are divided into general, dimensionality reduction, bound estimation, algorithm selection and footprint construction settings. For the second, the toolkit has routines for bounding outliers, scale the data and select features. 55 | 56 | ### General settings 57 | 58 | - ```opts.perf.MaxPerf``` determines whether the algorithm performance values provided are **efficiency** measures that should be maximised (set as ```TRUE```), or **cost** measures that should be minimised (set as ```FALSE```). 59 | - ```opts.perf.AbsPerf``` determines whether good performance is defined absolutely, e.g., misclassification error is lower than a 20%, (set as ```TRUE```), or if it is defined relatively to the best performing algorithm, e.g., misclassification error is within at least 5% of the best algorithm, (set as ```FALSE```). 60 | - ```opts.perf.epsilon``` corresponds to the threshold used to calculate good performance. It must be of the type "Double". 61 | - ```opts.general.betaThreshold``` corresponds to the fraction of algorithms in the portfolio that must have good performance in the instance, for it to be considered an **easy** instance. It must be a value between 0 and 1. 62 | - ```opts.parallel.flag``` determines whether parallel processing will be available (set as ```TRUE```), or not (set as ```FALSE```). The toolkit makes use of MATLAB's [```parpool```](https://au.mathworks.com/help/parallel-computing/parpool.html) functionality to create a multisession environment in the local machine. 63 | - ```opts.parallel.ncores``` number of available cores for parallel procesing. 64 | - ```opts.selvars.smallscaleflag``` by setting this flag as ```TRUE```, you can carry out a small scale experiment using a randomly selected fraction of the original data. This is useful if you have a large dataset with more than 1000 instances, and you want to explore the parameters of the model. 65 | - ```opts.selvars.smallscale``` fraction taken from the original data on the small scale experiment. 66 | - ```opts.selvars.fileidxflag``` by setting this flag as ```TRUE```, you can carry out a small scale experiment. This time you must provide a ```.csv``` file that contains in one column the indices of the instances to be taken. This may be useful if you want to make a more controlled experiment than just randomly selecting instances. 67 | - ```opts.selvars.fileidx``` name of the file containing the indexes of the instances. 68 | 69 | ### Dimensionality reduction settings 70 | 71 | The toolkit uses PILOT as a dimensionality reduction method, with [BFGS](https://en.wikipedia.org/wiki/Broyden-Fletcher-Goldfarb-Shanno_algorithm) as numerical solver. Technical details about it can be found [here](https://doi.org/10.1007/s10994-017-5629-5). 72 | 73 | - ```opts.pilot.analytic``` determines whether the analytic (set as ```TRUE```) or the numerical (set as ```FALSE```) solution to the dimensionality reduction problem should be used. We recommend to leave this setting as ```FALSE```, due to the instability of the analytical solution due to possible poor-conditioning. 74 | - ```opts.pilot.ntries``` number of iterations that the numerical solution is attempted. 75 | 76 | ### Empirical bound estimation settings. 77 | 78 | The toolkit uses CLOISTER, an algorithm based on correlation to detect the empirical bounds of the Instance Space. 79 | 80 | - ```opts.cloister.cthres``` Determines the maximum [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) that would indicate non-correlated variables. The lower this value is, the more stringent is the algorithm; hence, it would be less likely to produce a good bound. 81 | - ```opts.cloister.pval``` Determines the p-value of the Pearson correlation coefficient that indicates no correlation. 82 | 83 | ### Algorithm selection settings 84 | 85 | The toolkit uses SVMs with radial basis kernels as algorithm selection models, through MATLAB's Statistics and Machine Learning Toolbox or [LIBSVM](https://www.csie.ntu.edu.tw/~cjlin/libsvm/). 86 | 87 | - ```opts.pythia.uselibsvm``` determines whether to use LIBSVM (set as ```TRUE```) or MATLAB's implementation of an SVM, depending on which a different method is used to fine tune the parameters. For the former, tuning is achieved using 30 iterations of the random search algorithm, usinga Latin Hyper-cube design bounded between as sample points, withk-fold stratified cross-validation (CV), and using model error as the loss function. On the other hand, for the latter, tuning is achieved using 30 iterations of the Bayesian Optimization algorithm bounded between , with k-fold stratified CV. 88 | - ```opts.pythia.cvfolds``` number of folds of the CV experiment. 89 | - ```opts.pythia.ispolykrnl``` determines whether to use a polynomial (set as ```TRUE```) or Gaussian (set as ```FALSE```) kernel. Usually, the latter one is significantly faster to calculate and more accurate; however, it also has the disadvantage of producing discontinuous areas of good performance which may look overfitted. We tend to recommend a polynomial kernel if the dataset is higher than 1000 instances. 90 | - ```opts.pythia.useweights``` determines whether weighted (set as ```TRUE```) or unweighted (set as ```FALSE```) classification is performed. The weights are calculated as . 91 | 92 | ### Footprint construction settings 93 | 94 | The toolkit uses TRACE, an algorithm based on MATLAB's [```polyshapes```](https://au.mathworks.com/help/matlab/ref/polyshape.html) to define the regions in the space where we statistically infer good algorithm performance. The polyshapes are then pruned to remove those sections for which the evidence, as defined by a minimum purity value, is poor or non-existing. 95 | 96 | - ```opts.trace.usesim``` makes use of the actual (set as ```FALSE```) or simulated data from the SVM results (set as ```TRUE```) to produce the footprints. 97 | - ```opts.trace.PI``` minimum purity required for a section of a footprint. 98 | 99 | ### Automatic data bounding and scaling 100 | 101 | The toolkit implements simple routines to bound outliers and scale the data. **These routines are by no means perfect, and users should pre-process their data independently if preferred**. However, the automatic bounding and scaling routines should give some idea of the kind of results may be achieved. In general, we recommend that the data is transformed to become **close to normally distributed** due to the linear nature of PILOT's optimal projection algorithm. 102 | 103 | - ```opts.auto.preproc``` turns on (set as ```TRUE```) the automatic pre-processing. 104 | - ```opts.bound.flag``` turns on (set as ```TRUE```) data bounding. This sub-routine calculates the median and the interquartile range ([IQR](https://en.wikipedia.org/wiki/Interquartile_range)) of each feature and performance measure, and bounds the data to the median plus or minus five times the IQR. 105 | - ```opts.norm.flag``` turns on (set as ```TRUE```) scalling. This sub-routine scales into a positive range each feature and performance measure. Then it calculates a [box-cox transformation](https://en.wikipedia.org/wiki/Power_transform#Box%E2%80%93Cox_transformation) to stabilise the variance, and a [Z-transformation](https://en.wikipedia.org/wiki/Standard_score) to standarise the data. The result are features and performance measures that are close to normally distributed. 106 | 107 | ### Automatic feature selection 108 | 109 | The toolkit implements SIFTED, a routine to select features, given their cross-correlation and correlation to performance. Ideally, we want the smallest number of orthogonal and predictive features. **This routine are by no means perfect, and users should pre-process their data independently if preferred**. In general, we recommend **using no more than 10 features** as input to PILOT's optimal projection algorithm, due to the numerical nature of its solution and issues in identifying meaningful linear trends. 110 | 111 | - ```opts.sifted.flag``` turns on (set as ```TRUE```) the automatic feature selection. SIFTED is composed of two sub-processes. On the first one, SIFTED calculates the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) between the features and the performance. Then it takes its absolute value, and sorts them from largest to lowest. Then, it takes all features that have a correlation above the threshold. It automatically bounds itself to a minimum of 3 features. Then, SIFTED uses the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) as a dissimilarity metric between features. Then, [k-means clustering](https://en.wikipedia.org/wiki/K-means_clustering) is used to identify groups of similar features. To select one feature per group, the algorithm first projects the subset of selected featurs into two dimensions using Principal Components Analysis ([PCA](https://en.wikipedia.org/wiki/Principal_component_analysis)) and then [Random Forests](https://en.wikipedia.org/wiki/Random_forest) to predict whether an instance is easy or not for a given algorithm. Then, the subset of features that gives the most accurate models is selected. This section of the routine is **potentially very expensive computationally** due to the multiple layer training process. However, it is our current recommended approach to select the most relevant features. This routine tests all possible combinations if they are less than 1000, or uses the combination of a [Genetic Algorithm](https://en.wikipedia.org/wiki/Genetic_algorithm) and a Look-up table otherwise. 112 | - ```opts.sifted.rho``` correlation threshold indicating the lowest acceptable absolute correlation between a feature and performance. It should be a value between 0 and 1. 113 | - ```opts.sifted.K``` number of clusters which corresponds to the final number of features returned. The routine assumes at least 3 clusters and no more than the number of features. Ideally it **should not** be a value larger than 10. 114 | - ```opts.sifted.NTREES``` number of threes used by the Random Forest models. Usually, this setting does not need tuning. 115 | - ```opts.sifted.MaxIter``` number of iterations used to converge the k-means algorithm. Usually, this setting does not need tuning. 116 | - ```opts.sifted.Replicates``` number of repeats carried out of the k-means algorithm. Usually, this setting does not need tuning. 117 | 118 | ### Output settings 119 | 120 | These settings result in more information being stored in files or presented in the console output. 121 | 122 | - ```opts.outputs.csv``` This flag produces the output CSV files for post-processing and analysis. It is recommended to leave this setting as ```TRUE```. 123 | - ```opts.outputs.png``` This flag produces the output figures files for post-processing and analysis. It is recommended to leave this setting as ```TRUE```. 124 | - ```opts.outputs.web``` This flag produces the output files employed to draw the figures in MATILDA's web tools (click [here](https://matilda.unimelb.edu.au/matilda/newuser) to open an account). It is recommended to leave this setting as ```FALSE```. 125 | 126 | ## Contact 127 | 128 | If you have any suggestions or ideas (e.g. for new features), or if you encounter any problems while running the code, please use the [issue tracker](https://github.com/andremun/InstanceSpace/issues) or contact us through the MATILDA's [Queries and Feedback](http://matilda.unimelb.edu.au/matilda/contact-us) page. 129 | 130 | ## Acknowledgements 131 | 132 | Funding for the development of this code was provided by the Australian Research Council through the Australian Laureate Fellowship FL140100012. 133 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------