diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a5fa9c --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +devenv +env + +.idea +*.iml +*.lock +*.out + +AGModels/ +AutogluonModels/ +experiment/AutogluonModels/ +datasets/ +instanceSpace-master/ +imbalanced-ensemble/ +logs/ +openml_cache/ +test/ +config_spaces/classifiers_tpot/ +stash/ + +__pycache__/ +*.pkl diff --git a/InstanceSpace-master/.gitattributes b/InstanceSpace-master/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/InstanceSpace-master/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/InstanceSpace-master/.github/ISSUE_TEMPLATE/bug_report.md b/InstanceSpace-master/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dd84ea7 --- /dev/null +++ b/InstanceSpace-master/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/InstanceSpace-master/.github/ISSUE_TEMPLATE/feature_request.md b/InstanceSpace-master/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/InstanceSpace-master/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/InstanceSpace-master/.gitignore b/InstanceSpace-master/.gitignore new file mode 100644 index 0000000..b85737d --- /dev/null +++ b/InstanceSpace-master/.gitignore @@ -0,0 +1,10 @@ +*.asv +*.zip +*.png +*.pdf +*.mat +*.db +*.csv +old_versions/*.* +old_versions +*.json diff --git a/InstanceSpace-master/CLOISTER.m b/InstanceSpace-master/CLOISTER.m new file mode 100644 index 0000000..64bb149 --- /dev/null +++ b/InstanceSpace-master/CLOISTER.m @@ -0,0 +1,65 @@ +function out = CLOISTER(X, A, opts) +% ------------------------------------------------------------------------- +% CLOISTER.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +disp(' -> CLOISTER is using correlation to estimate a boundary for the space.'); + +nfeats = size(X,2); +[rho,pval] = corr(X); +rho = rho.*(pvalopts.cthres && sign(Xedge(i,j))~=sign(Xedge(i,k)) + remove(i) = true; + elseif rho(j,k)<-opts.cthres && sign(Xedge(i,j))==sign(Xedge(i,k)) + remove(i) = true; + end + if remove(i) + break; + end + end + if remove(i) + break; + end + end +end +Zedge = Xedge*A'; +Kedge = convhull(Zedge(:,1),Zedge(:,2)); +out.Zedge = Zedge(Kedge,:); + +try + Xecorr = Xedge(~remove,:); + Zecorr = Xecorr*A'; + Kecorr = convhull(Zecorr(:,1),Zecorr(:,2)); + out.Zecorr = Zecorr(Kecorr,:); +catch + disp(' -> The acceptable correlation threshold was too strict.'); + disp(' -> The features are weakely correlated.') + disp(' -> Please consider increasing it.'); + out.Zecorr = out.Zedge; +end +disp('-------------------------------------------------------------------------'); +disp(' -> CLOISTER has completed.'); + diff --git a/InstanceSpace-master/FILTER.m b/InstanceSpace-master/FILTER.m new file mode 100644 index 0000000..b307449 --- /dev/null +++ b/InstanceSpace-master/FILTER.m @@ -0,0 +1,65 @@ +function [subsetIndex,isDissimilar,isVISA] = FILTER(X,Y,Ybin,opts) + +[ninst,nalgos] = size(Y); +nfeats = size(X,2); + +subsetIndex = false(ninst,1); +isDissimilar = true(ninst,1); +isVISA = false(ninst,1); +gamma = sqrt(nalgos/nfeats)*opts.mindistance; + +for ii=1:ninst + if ~subsetIndex(ii) + for jj=ii+1:ninst + if ~subsetIndex(jj) + Dx = pdist2(X(ii,:),X(jj,:)); + Dy = pdist2(Y(ii,:),Y(jj,:)); + Db = all(Ybin(ii,:) & Ybin(jj,:)); + if Dx <= opts.mindistance + isDissimilar(jj) = false; + switch opts.type + case 'Ftr' + subsetIndex(jj) = true; + case 'Ftr&AP' + if Dy <= gamma + subsetIndex(jj) = true; + isVISA(jj) = false; + else + isVISA(jj) = true; + end + case 'Ftr&Good' + if Db + subsetIndex(jj) = true; + isVISA(jj) = false; + else + isVISA(jj) = true; + end + case 'Ftr&AP&Good' + if Db + if Dy <= gamma + subsetIndex(jj) = true; + isVISA(jj) = false; + else + isVISA(jj) = true; + end + else + isVISA(jj) = true; + end + otherwise + disp('Invalid flag!') + end + end + end + end + end +end + +% Assess the uniformity of the data +D = squareform(pdist(X(~subsetIndex,:))); +ninst = size(D,1); +D(eye(ninst,'logical')) = NaN; +nearest = min(D,[],2,'omitnan'); +model.data.unif = 1-(std(nearest)./mean(nearest)); +disp(['Uniformity of the instance subset: ' num2str(model.data.unif,4)]); + +end \ No newline at end of file diff --git a/InstanceSpace-master/LICENSE b/InstanceSpace-master/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/InstanceSpace-master/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/InstanceSpace-master/PILOT.m b/InstanceSpace-master/PILOT.m new file mode 100644 index 0000000..dc6fc19 --- /dev/null +++ b/InstanceSpace-master/PILOT.m @@ -0,0 +1,111 @@ +function out = PILOT(X, Y, featlabels, opts) +% ------------------------------------------------------------------------- +% PILOT.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +errorfcn = @(alpha,Xbar,n,m) nanmean(nanmean((Xbar-(reshape(alpha((2*n)+1:end),m,2)*... % B,C + reshape(alpha(1:2*n),2,n)... % A + *Xbar(:,1:n)')').^2,1),2); +n = size(X, 2); % Number of features +Xbar = [X Y]; +m = size(Xbar, 2); +Hd = pdist(X)'; +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +if opts.analytic + disp(' -> PILOT is solving analyticaly the projection problem.'); + disp(' -> This won''t take long.'); + Xbar = Xbar'; + X = X'; + [V,D] = eig(Xbar*Xbar'); + [~,idx] = sort(abs(diag(D)),'descend'); + V = V(:,idx(1:2)); + out.B = V(1:n,:); + out.C = V(n+1:m,:)'; + Xr = X'/(X*X'); + out.A = V'*Xbar*Xr; + out.Z = out.A*X; + Xhat = [out.B*out.Z; out.C'*out.Z]; + out.error = sum(sum((Xbar-Xhat).^2,2)); + out.R2 = diag(corr(Xbar',Xhat')).^2; +else + if isfield(opts,'alpha') && isnumeric(opts.alpha) && ... + size(opts.alpha,1)==2*m+2*n && size(opts.alpha,2)==1 + disp(' -> PILOT is using a pre-calculated solution.'); + idx = 1; + out.alpha = opts.alpha; + else + if isfield(opts,'X0') && isnumeric(opts.X0) && ... + size(opts.X0,1)==2*m+2*n && size(opts.X0,2)>=1 + disp(' -> PILOT is using a user defined starting points for BFGS.'); + X0 = opts.X0; + opts.ntries = size(opts.X0,2); + else + disp(' -> PILOT is using a random starting points for BFGS.'); + state = rng; + rng('default'); + X0 = 2*rand(2*m+2*n, opts.ntries)-1; + rng(state); + end + alpha = zeros(2*m+2*n, opts.ntries); + eoptim = zeros(1, opts.ntries); + perf = zeros(1, opts.ntries); + disp('-------------------------------------------------------------------------'); + disp(' -> PILOT is solving numerically the projection problem.'); + disp(' -> This may take a while. Trials will not be run sequentially.'); + disp('-------------------------------------------------------------------------'); + parfor (i=1:opts.ntries,nworkers) + [alpha(:,i),eoptim(i)] = fminunc(errorfcn, X0(:,i), ... + optimoptions('fminunc','Algorithm','quasi-newton',... + 'Display','off',... + 'UseParallel',false),... + Xbar, n, m); + aux = alpha(:,i); + A = reshape(aux(1:2*n),2,n); + Z = X*A'; + perf(i) = corr(Hd,pdist(Z)'); + disp([' -> PILOT has completed trial ' num2str(i)]); + end + out.X0 = X0; + out.alpha = alpha; + out.eoptim = eoptim; + out.perf = perf; + [~,idx] = max(out.perf); + end + out.A = reshape(out.alpha(1:2*n,idx),2,n); + out.Z = X*out.A'; + B = reshape(out.alpha((2*n)+1:end,idx),m,2); + Xhat = out.Z*B'; + out.C = B(n+1:m,:)'; + out.B = B(1:n,:); + out.error = sum(sum((Xbar-Xhat).^2,2)); + out.R2 = diag(corr(Xbar,Xhat)).^2; +end + +disp('-------------------------------------------------------------------------'); +disp(' -> PILOT has completed. The projection matrix A is:'); +out.summary = cell(3, n+1); +out.summary(1,2:end) = featlabels; +out.summary(2:end,1) = {'Z_{1}','Z_{2}'}; +out.summary(2:end,2:end) = num2cell(round(out.A,4)); +disp(' '); +disp(out.summary); + +end \ No newline at end of file diff --git a/InstanceSpace-master/PRELIM.m b/InstanceSpace-master/PRELIM.m new file mode 100644 index 0000000..db626e2 --- /dev/null +++ b/InstanceSpace-master/PRELIM.m @@ -0,0 +1,108 @@ +function [X,Y,Ybest,Ybin,P,numGoodAlgos,beta,out] = PRELIM(X,Y,opts) + +Yraw = Y; +nalgos = size(Y,2); +% ------------------------------------------------------------------------- +% Determine whether the performance of an algorithm is a cost measure to +% be minimized or a profit measure to be maximized. Moreover, determine +% whether we are using an absolute threshold as good peformance (the +% algorithm has a performance better than the threshold) or a relative +% performance (the algorithm has a performance that is similar that the +% best algorithm minus a percentage). +disp('-------------------------------------------------------------------------'); +disp('-> Calculating the binary measure of performance'); +msg = '-> An algorithm is good if its performace is '; +if opts.MaxPerf + Yaux = Y; + Yaux(isnan(Yaux)) = -Inf; + [Ybest,P] = max(Yaux,[],2); + if opts.AbsPerf + Ybin = Yaux>=opts.epsilon; + msg = [msg 'higher than ' num2str(opts.epsilon)]; + else + Ybest(Ybest==0) = eps; + Y(Y==0) = eps; + Y = 1-bsxfun(@rdivide,Y,Ybest); + Ybin = (1-bsxfun(@rdivide,Yaux,Ybest))<=opts.epsilon; + msg = [msg 'within ' num2str(round(100.*opts.epsilon)) '% of the best.']; + end +else + Yaux = Y; + Yaux(isnan(Yaux)) = Inf; + [Ybest,P] = min(Yaux,[],2); + if opts.AbsPerf + Ybin = Yaux<=opts.epsilon; + msg = [msg 'less than ' num2str(opts.epsilon)]; + else + Ybest(Ybest==0) = eps; + Y(Y==0) = eps; + Y = bsxfun(@rdivide,Y,Ybest)-1; + Ybin = (bsxfun(@rdivide,Yaux,Ybest)-1)<=opts.epsilon; + msg = [msg 'within ' num2str(round(100.*opts.epsilon)) '% of the best.']; + end +end +disp(msg); +% ------------------------------------------------------------------------- +% Testing for ties. If there is a tie in performance, we pick an algorithm +% at random. +bestAlgos = bsxfun(@eq,Yraw,Ybest); +multipleBestAlgos = sum(bestAlgos,2)>1; +aidx = 1:nalgos; +for i=1:size(Y,1) + if multipleBestAlgos(i) + aux = aidx(bestAlgos(i,:)); + P(i) = aux(randi(length(aux),1)); % Pick one at random + end +end +disp(['-> For ' num2str(round(100.*mean(multipleBestAlgos))) '% of the instances there is ' ... + 'more than one best algorithm. Random selection is used to break ties.']); +numGoodAlgos = sum(Ybin,2); +beta = numGoodAlgos>(opts.betaThreshold*nalgos); + +disp('========================================================================='); +disp('-> Auto-pre-processing.'); +disp('========================================================================='); +if opts.bound + disp('-> Removing extreme outliers from the feature values.'); + out.medval = nanmedian(X, 1); + out.iqrange = iqr(X, 1); + out.hibound = out.medval + 5.*out.iqrange; + out.lobound = out.medval - 5.*out.iqrange; + himask = bsxfun(@gt,X,out.hibound); + lomask = bsxfun(@lt,X,out.lobound); + X = X.*~(himask | lomask) + bsxfun(@times,himask,out.hibound) + ... + bsxfun(@times,lomask,out.lobound); +end + +if opts.norm + nfeats = size(X,2); + nalgos = size(Y,2); + disp('-> Auto-normalizing the data using Box-Cox and Z transformations.'); + out.minX = min(X,[],1); + X = bsxfun(@minus,X,out.minX)+1; + out.lambdaX = zeros(1,nfeats); + out.muX = zeros(1,nfeats); + out.sigmaX = zeros(1,nfeats); + for i=1:nfeats + aux = X(:,i); + idx = isnan(aux); + [aux, out.lambdaX(i)] = boxcox(aux(~idx)); + [aux, out.muX(i), out.sigmaX(i)] = zscore(aux); + X(~idx,i) = aux; + end + + out.minY = min(Y(:)); + Y = (Y-out.minY)+eps; + out.lambdaY = zeros(1,nalgos); + out.muY = zeros(1,nalgos); + out.sigmaY = zeros(1,nalgos); + for i=1:nalgos + aux = Y(:,i); + idx = isnan(aux); + [aux, out.lambdaY(i)] = boxcox(aux(~idx)); + [aux, out.muY(i), out.sigmaY(i)] = zscore(aux); + Y(~idx,i) = aux; + end +end + +end diff --git a/InstanceSpace-master/PYTHIA.m b/InstanceSpace-master/PYTHIA.m new file mode 100644 index 0000000..7b1f370 --- /dev/null +++ b/InstanceSpace-master/PYTHIA.m @@ -0,0 +1,342 @@ +function out = PYTHIA(Z, Y, Ybin, Ybest, algolabels, opts) +% ------------------------------------------------------------------------- +% PYTHIA.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +disp(' -> Initializing PYTHIA.'); +[Znorm,out.mu,out.sigma] = zscore(Z); +[ninst,nalgos] = size(Ybin); +out.cp = cell(1,nalgos); +out.svm = cell(1,nalgos); +out.cvcmat = zeros(nalgos,4); +out.Ysub = false & Ybin; +out.Yhat = false & Ybin; +out.Pr0sub = 0.*Ybin; +out.Pr0hat = 0.*Ybin; +out.boxcosnt = zeros(1,nalgos); +out.kscale = out.boxcosnt; +disp('-------------------------------------------------------------------------'); +precalcparams = isfield(opts,'params') && isnumeric(opts.params) && ... + size(opts.params,1)==nalgos && size(opts.params,2)==2; +params = NaN.*ones(nalgos,2); +if opts.ispolykrnl + KernelFcn = 'polynomial'; +else + if ninst>1e3 + disp(' -> For datasets larger than 1K Instances, PYTHIA works better with a Polynomial kernel.'); + disp(' -> Consider changing the kernel if the results are unsatisfactory.'); + disp('-------------------------------------------------------------------------'); + end + KernelFcn = 'gaussian'; +end +disp([' -> PYTHIA is using a ' KernelFcn ' kernel ']); +disp('-------------------------------------------------------------------------'); +if opts.uselibsvm + disp(' -> Using LIBSVM''s libraries.'); + if precalcparams + disp(' -> Using pre-calculated hyper-parameters for the SVM.'); + params = opts.params; + else + disp(' -> Search on a latin hyper-cube design will be used for parameter hyper-tunning.'); + end +else + disp(' -> Using MATLAB''s SVM libraries.'); + if precalcparams + disp(' -> Using pre-calculated hyper-parameters for the SVM.'); + params = opts.params; + else + disp(' -> Bayesian Optimization will be used for parameter hyper-tunning.'); + end + disp('-------------------------------------------------------------------------'); + if opts.useweights + disp(' -> PYTHIA is using cost-sensitive classification'); + out.W = abs(Y-nanmean(Y(:))); + out.W(out.W==0) = min(out.W(out.W~=0)); + out.W(isnan(out.W)) = max(out.W(~isnan(out.W))); + Waux = out.W; + else + disp(' -> PYTHIA is not using cost-sensitive classification'); + Waux = ones(ninst,nalgos); + end +end +disp('-------------------------------------------------------------------------'); +disp([' -> Using a ' num2str(opts.cvfolds) ... + '-fold stratified cross-validation experiment to evaluate the SVMs.']); +disp('-------------------------------------------------------------------------'); +disp(' -> Training has started. PYTHIA may take a while to complete...'); +t = tic; +for i=1:nalgos + tic; + state = rng; + rng('default'); + out.cp{i} = cvpartition(Ybin(:,i),'Kfold',opts.cvfolds,'Stratify',true); + if opts.uselibsvm + [out.svm{i},out.Ysub(:,i),out.Pr0sub(:,i),out.Yhat(:,i),... + out.Pr0hat(:,i),out.boxcosnt(i),out.kscale(i)] = fitlibsvm(Znorm,Ybin(:,i),... + out.cp{i},KernelFcn,... + params(i,:)); + else + [out.svm{i},out.Ysub(:,i),out.Pr0sub(:,i),out.Yhat(:,i),... + out.Pr0hat(:,i),out.boxcosnt(i),out.kscale(i)] = fitmatsvm(Znorm,Ybin(:,i),... + Waux(:,i),out.cp{i},... + KernelFcn,params(i,:)); + end + rng(state); + aux = confusionmat(Ybin(:,i),out.Ysub(:,i)); + if numel(aux)~=4 + caux = aux; + aux = zeros(2); + if all(Ybin(:,i)==0) + if all(out.Ysub(:,i)==0) + aux(1,1) = caux; + elseif all(out.Ysub(:,i)==1) + aux(2,1) = caux; + end + elseif all(Ybin(:,i)==1) + if all(out.Ysub(:,i)==0) + aux(1,2) = caux; + elseif all(out.Ysub(:,i)==1) + aux(2,2) = caux; + end + end + end + out.cvcmat(i,:) = aux(:); + if i==nalgos + disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... + ''', there are no models left to train.']); + elseif i==nalgos-1 + disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... + ''', there is 1 model left to train.']); + else + disp([' -> PYTHIA has trained a model for ''' algolabels{i}, ... + ''', there are ' num2str(nalgos-i) ' models left to train.']); + end + disp([' -> Elapsed time: ' num2str(toc,'%.2f\n') 's']); +end +tn = out.cvcmat(:,1); +fp = out.cvcmat(:,3); +fn = out.cvcmat(:,2); +tp = out.cvcmat(:,4); +out.precision = tp./(tp+fp); +out.recall = tp./(tp+fn); +out.accuracy = (tp+tn)./ninst; +disp('-------------------------------------------------------------------------'); +disp(' -> PYTHIA has completed training the models.'); +disp([' -> The average cross validated precision is: ' ... + num2str(round(100.*mean(out.precision),1)) '%']); +disp([' -> The average cross validated accuracy is: ' ... + num2str(round(100.*mean(out.accuracy),1)) '%']); + disp([' -> Elapsed time: ' num2str(toc(t),'%.2f\n') 's']); +disp('-------------------------------------------------------------------------'); +% We assume that the most precise SVM (as per CV-Precision) is the most +% reliable. +if nalgos>1 + [best,out.selection0] = max(bsxfun(@times,out.Yhat,out.precision'),[],2); +else + best = out.Yhat; + out.selection0 = out.Yhat; +end +[~,default] = max(mean(Ybin)); +out.selection1 = out.selection0; +out.selection0(best<=0) = 0; +out.selection1(best<=0) = default; + +sel0 = bsxfun(@eq,out.selection0,1:nalgos); +sel1 = bsxfun(@eq,out.selection1,1:nalgos); +avgperf = nanmean(Y); +stdperf = nanstd(Y); +Yfull = Y; +Ysvms = Y; +Y(~sel0) = NaN; +Yfull(~sel1) = NaN; +Ysvms(~out.Yhat) = NaN; + +pgood = mean(any( Ybin & sel1,2)); +fb = sum(any( Ybin & ~sel0,2)); +fg = sum(any(~Ybin & sel0,2)); +tg = sum(any( Ybin & sel0,2)); +precisionsel = tg./(tg+fg); +recallsel = tg./(tg+fb); + +disp(' -> PYTHIA is preparing the summary table.'); +out.summary = cell(nalgos+3, 11); +out.summary{1,1} = 'Algorithms '; +out.summary(2:end-2, 1) = algolabels; +out.summary(end-1:end, 1) = {'Oracle','Selector'}; +out.summary(1, 2:11) = {'Avg_Perf_all_instances'; + 'Std_Perf_all_instances'; + 'Probability_of_good'; + 'Avg_Perf_selected_instances'; + 'Std_Perf_selected_instances'; + 'CV_model_accuracy'; + 'CV_model_precision'; + 'CV_model_recall'; + 'BoxConstraint'; + 'KernelScale'}; +out.summary(2:end, 2) = num2cell(round([avgperf nanmean(Ybest) nanmean(Yfull(:))],3)); +out.summary(2:end, 3) = num2cell(round([stdperf nanstd(Ybest) nanstd(Yfull(:))],3)); +out.summary(2:end, 4) = num2cell(round([mean(Ybin) 1 pgood],3)); +out.summary(2:end, 5) = num2cell(round([nanmean(Ysvms) NaN nanmean(Y(:))],3)); +out.summary(2:end, 6) = num2cell(round([nanstd(Ysvms) NaN nanstd(Y(:))],3)); +out.summary(2:end, 7) = num2cell(round(100.*[out.accuracy' NaN NaN],1)); +out.summary(2:end, 8) = num2cell(round(100.*[out.precision' NaN precisionsel],1)); +out.summary(2:end, 9) = num2cell(round(100.*[out.recall' NaN recallsel],1)); +out.summary(2:end-2, 10) = num2cell(round(out.boxcosnt,3)); +out.summary(2:end-2, 11) = num2cell(round(out.kscale,3)); +out.summary(cellfun(@(x) all(isnan(x)),out.summary)) = {[]}; % Clean up. Not really needed +disp(' -> PYTHIA has completed! Performance of the models:'); +disp(' '); +disp(out.summary); + +end +% ========================================================================= +% SUBFUNCTIONS +% ========================================================================= +function [svm,Ysub,Psub,Yhat,Phat,C,g] = fitlibsvm(Z,Ybin,cp,k,params) + +ninst = size(Z,1); +maxgrid = 4; +mingrid = -10; +if any(isnan(params)) + rng('default'); + nvals = 30; + paramgrid = sortrows(2.^((maxgrid-mingrid).*lhsdesign(nvals,2) + mingrid)); +else + nvals = 1; + paramgrid = params; +end +Ybin = double(Ybin)+1; +Ysub = zeros(ninst,nvals); +Psub = zeros(ninst,nvals); + +if strcmp(k,'polynomial') + k = 1; +else + k = 2; +end + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +for jj=1:cp.NumTestSets + idx = cp.training(jj); + Ztrain = Z(idx,:); + Ytrain = Ybin(idx); + Ztest = Z(~idx,:); + Ytest = Ybin(~idx); + Yaux = zeros(sum(~idx),nvals); + Paux = zeros(sum(~idx),nvals); + parfor (ii=1:nvals,nworkers) + cparams = paramgrid(ii,:); + prior = mean(bsxfun(@eq,Ytrain,[1 2])); + command = ['-s 0 -t ' num2str(k) ' -q -b 1 -c ' num2str(cparams(1)) ... + ' -g ' num2str(cparams(2)) ' -w1 1 -w2 ' num2str(prior(1)./prior(2),4)]; + rng('default'); + svm = svmtrain(Ytrain, Ztrain, command); %#ok + [Yaux(:,ii),~,Paux(:,ii)] = svmpredict(Ytest, Ztest, svm, '-q'); + end + for ii=1:nvals + Ysub(~idx,ii) = Yaux(:,ii); + Psub(~idx,ii) = Paux(:,ii); + end +end +[~,idx] = min(mean(bsxfun(@ne,Ysub,Ybin),1)); +Ysub = Ysub(:,idx)==2; +Psub = Psub(:,idx); + +C = paramgrid(idx,1); +g = paramgrid(idx,2); +prior = mean(bsxfun(@eq,Ybin,[1 2])); +command = ['-s 0 -t ' num2str(k) ' -q -b 1 -c ' num2str(C) ' -g ' num2str(g) ... + ' -w1 1 -w2 ' num2str(prior(1)./prior(2),4)]; +rng('default'); +svm = svmtrain(Ybin, Z, command); %#ok +[Yhat,~,Phat] = svmpredict(Ybin, Z, svm, '-q'); +Yhat = Yhat==2; + +end +% ========================================================================= +function [svm,Ysub,Psub,Yhat,Phat,C,g] = fitmatsvm(Z,Ybin,W,cp,k,params) + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +if any(isnan(params)) + rng('default'); + hypparams = hyperparameters('fitcsvm',Z,Ybin); + hypparams = hypparams(1:2); + hypparams(1).Range = 2.^[-10,4]; + hypparams(2).Range = hypparams(1).Range; + svm = fitcsvm(Z,Ybin,'Standardize',false,... + 'Weights',W,... + 'CacheSize','maximal',... + 'RemoveDuplicates',true,... + 'KernelFunction',k,... + 'OptimizeHyperparameters',hypparams,... + 'HyperparameterOptimizationOptions',... + struct('CVPartition',cp,... + 'Verbose',0,... + 'AcquisitionFunctionName','probability-of-improvement',... + 'ShowPlots',false,... + 'UseParallel',nworkers~=0)); + svm = fitSVMPosterior(svm); + C = svm.HyperparameterOptimizationResults.bestPoint{1,1}; + g = svm.HyperparameterOptimizationResults.bestPoint{1,2}; + [Ysub,aux] = svm.resubPredict; + Psub = aux(:,1); + [Yhat,aux] = svm.predict(Z); + Phat = aux(:,1); +else + C = params(1); + g = params(2); + rng('default'); + svm = fitcsvm(Z,Ybin,'Standardize',false,... + 'Weights',W,... + 'CacheSize','maximal',... + 'RemoveDuplicates',true,... + 'KernelFunction',k,... + 'CVPartition',cp,... + 'BoxConstraint',C,... + 'KernelScale',g); + svm = fitSVMPosterior(svm); + [Ysub,aux] = svm.kfoldPredict; + Psub = aux(:,1); + rng('default'); + svm = fitcsvm(Z,Ybin,'Standardize',false,... + 'Weights',W,... + 'CacheSize','maximal',... + 'RemoveDuplicates',true,... + 'KernelFunction',k,... + 'BoxConstraint',C,... + 'KernelScale',g); + svm = fitSVMPosterior(svm); + [Yhat,aux] = svm.predict(Z); + Phat = aux(:,1); +end + +end +% ========================================================================= diff --git a/InstanceSpace-master/PYTHIAtest.m b/InstanceSpace-master/PYTHIAtest.m new file mode 100644 index 0000000..e080919 --- /dev/null +++ b/InstanceSpace-master/PYTHIAtest.m @@ -0,0 +1,83 @@ +function out = PYTHIAtest(model, Z, Y, Ybin, Ybest, algolabels) + +Z = (Z-model.mu)./model.sigma; +nalgos = length(model.svm); +Y = Y(:,1:nalgos); +Ybin = Ybin(:,1:nalgos); +out.Yhat = false(size(Ybin)); +out.Pr0hat = 0.*Ybin; +out.cvcmat = zeros(nalgos,4); +for ii=1:nalgos + if isstruct(model.svm{ii}) + Yin = double(Ybin(:,ii))+1; + [aux,~,out.Pr0hat(:,ii)] = svmpredict(Yin, Z, model.svm{ii}, '-q'); + out.Yhat(:,ii) = aux==2; + elseif isa(model.svm{ii},'ClassificationSVM') + [out.Yhat(:,ii),aux] = model.svm{ii}.predict(Z); + out.Pr0hat(:,ii) = aux(:,1); + else + disp('There is no model for this algorithm'); + out.Yhat(:,ii) = NaN; + out.Pr0hat(:,ii) = NaN; + end + aux = confusionmat(Ybin(:,ii),out.Yhat(:,ii)); + out.cvcmat(ii,:) = aux(:); +end +tn = out.cvcmat(:,1); +fp = out.cvcmat(:,3); +fn = out.cvcmat(:,2); +tp = out.cvcmat(:,4); +out.precision = tp./(tp+fp); +out.recall = tp./(tp+fn); +out.accuracy = (tp+tn)./sum(out.cvcmat(1,:)); + +[best,out.selection0] = max(bsxfun(@times,out.Yhat,model.precision'),[],2); +[~,default] = max(mean(Ybin)); +out.selection1 = out.selection0; +out.selection0(best<=0) = 0; +out.selection1(best<=0) = default; + +sel0 = bsxfun(@eq,out.selection0,1:nalgos); +sel1 = bsxfun(@eq,out.selection1,1:nalgos); +avgperf = nanmean(Y); +stdperf = nanstd(Y); +Yfull = Y; +Ysvms = Y; +Y(~sel0) = NaN; +Yfull(~sel1) = NaN; +Ysvms(~out.Yhat) = NaN; + +pgood = mean(any( Ybin & sel1,2)); +fb = sum(any( Ybin & ~sel0,2)); +fg = sum(any(~Ybin & sel0,2)); +tg = sum(any( Ybin & sel0,2)); +precisionsel = tg./(tg+fg); +recallsel = tg./(tg+fb); + +disp(' -> PYTHIA is preparing the summary table.'); +out.summary = cell(nalgos+3, 9); +out.summary{1,1} = 'Algorithms '; +out.summary(2:end-2, 1) = algolabels(1:nalgos); +out.summary(end-1:end, 1) = {'Oracle','Selector'}; +out.summary(1, 2:9) = {'Avg_Perf_all_instances'; + 'Std_Perf_all_instances'; + 'Probability_of_good'; + 'Avg_Perf_selected_instances'; + 'Std_Perf_selected_instances'; + 'CV_model_accuracy'; + 'CV_model_precision'; + 'CV_model_recall'}; +out.summary(2:end, 2) = num2cell(round([avgperf nanmean(Ybest) nanmean(Yfull(:))],3)); +out.summary(2:end, 3) = num2cell(round([stdperf nanstd(Ybest) nanstd(Yfull(:))],3)); +out.summary(2:end, 4) = num2cell(round([mean(Ybin) 1 pgood],3)); +out.summary(2:end, 5) = num2cell(round([nanmean(Ysvms) NaN nanmean(Y(:))],3)); +out.summary(2:end, 6) = num2cell(round([nanstd(Ysvms) NaN nanstd(Y(:))],3)); +out.summary(2:end, 7) = num2cell(round(100.*[out.accuracy' NaN NaN],1)); +out.summary(2:end, 8) = num2cell(round(100.*[out.precision' NaN precisionsel],1)); +out.summary(2:end, 9) = num2cell(round(100.*[out.recall' NaN recallsel],1)); +out.summary(cellfun(@(x) all(isnan(x)),out.summary)) = {[]}; % Clean up. Not really needed +disp(' -> PYTHIA has completed! Performance of the models:'); +disp(' '); +disp(out.summary); + +end \ No newline at end of file diff --git a/InstanceSpace-master/README.md b/InstanceSpace-master/README.md new file mode 100644 index 0000000..cf43cdc --- /dev/null +++ b/InstanceSpace-master/README.md @@ -0,0 +1,132 @@ +# Instance Space Analysis: A toolkit for the assessment of algorithmic power + +[![View InstanceSpace on File Exchange](https://www.mathworks.com/matlabcentral/images/matlab-file-exchange.svg)](https://au.mathworks.com/matlabcentral/fileexchange/75170-instancespace) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4750845.svg)](https://doi.org/10.5281/zenodo.4750845) + +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: + +- Objective metrics of each algorithm’s footprint across the instance space as a measure of algorithmic power; +- Explanation through visualisation of how instance features correlate with algorithm performance in various regions of the instance space; +- Visualisation of the distribution and diversity of existing benchmark and real-world instances; +- Assessment of the adequacy of the features used to characterise an instance; +- Partitioning of the instance space into recommended regions for automated algorithm selection; +- Distinguishing areas of the instance space where it may be useful to generate additional instances to gain further insights. + +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. + +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). + +If you follow the Instance Space Analysis methodology, please cite as follows: + +> 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. + +Also, if you specifically use this code, please cite as follows: + +> 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. + +Or if you specifically use [MATILDA](http://matilda.unimelb.edu.au/matilda/), please cite as follows: + +> 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. + +**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.** + +## Installation Instructions + +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. + +## Working with the code + +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). + +## The metadata file + +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: + +- **instances** instance identifier - We expect instance identifier to be of type "String". This column is mandatory. +- **source** instance source - This column is optional +- **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". +- **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". + +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. + +## Options + +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. + +### General settings + +- ```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```). +- ```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```). +- ```opts.perf.epsilon``` corresponds to the threshold used to calculate good performance. It must be of the type "Double". +- ```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. +- ```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. +- ```opts.parallel.ncores``` number of available cores for parallel procesing. +- ```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. +- ```opts.selvars.smallscale``` fraction taken from the original data on the small scale experiment. +- ```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. +- ```opts.selvars.fileidx``` name of the file containing the indexes of the instances. + +### Dimensionality reduction settings + +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). + +- ```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. +- ```opts.pilot.ntries``` number of iterations that the numerical solution is attempted. + +### Empirical bound estimation settings. + +The toolkit uses CLOISTER, an algorithm based on correlation to detect the empirical bounds of the Instance Space. + +- ```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. +- ```opts.cloister.pval``` Determines the p-value of the Pearson correlation coefficient that indicates no correlation. + +### Algorithm selection settings + +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/). + +- ```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. +- ```opts.pythia.cvfolds``` number of folds of the CV experiment. +- ```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. +- ```opts.pythia.useweights``` determines whether weighted (set as ```TRUE```) or unweighted (set as ```FALSE```) classification is performed. The weights are calculated as . + +### Footprint construction settings + +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. + +- ```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. +- ```opts.trace.PI``` minimum purity required for a section of a footprint. + +### Automatic data bounding and scaling + +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. + +- ```opts.auto.preproc``` turns on (set as ```TRUE```) the automatic pre-processing. +- ```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. +- ```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. + +### Automatic feature selection + +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. + +- ```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. +- ```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. +- ```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. +- ```opts.sifted.NTREES``` number of threes used by the Random Forest models. Usually, this setting does not need tuning. +- ```opts.sifted.MaxIter``` number of iterations used to converge the k-means algorithm. Usually, this setting does not need tuning. +- ```opts.sifted.Replicates``` number of repeats carried out of the k-means algorithm. Usually, this setting does not need tuning. + +### Output settings + +These settings result in more information being stored in files or presented in the console output. + +- ```opts.outputs.csv``` This flag produces the output CSV files for post-processing and analysis. It is recommended to leave this setting as ```TRUE```. +- ```opts.outputs.png``` This flag produces the output figures files for post-processing and analysis. It is recommended to leave this setting as ```TRUE```. +- ```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```. + +## Contact + +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. + +## Acknowledgements + +Funding for the development of this code was provided by the Australian Research Council through the Australian Laureate Fellowship FL140100012. diff --git a/InstanceSpace-master/SIFTED.m b/InstanceSpace-master/SIFTED.m new file mode 100644 index 0000000..41306f8 --- /dev/null +++ b/InstanceSpace-master/SIFTED.m @@ -0,0 +1,211 @@ +function [X, out] = SIFTED(X, Y, Ybin, opts) +% ------------------------------------------------------------------------- +% SIFTED.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2021 +% +% ------------------------------------------------------------------------- + +global comb gacostvals + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +% --------------------------------------------------------------------- +nfeats = size(X,2); +if nfeats<=1 + error('-> There is only 1 feature. Stopping space construction.'); +elseif nfeats<=3 + disp('-> There are 3 or less features to do selection. Skipping feature selection.') + out.selvars = 1:nfeats; + return; +end +% --------------------------------------------------------------------- +disp('-> Selecting features based on correlation with performance.'); +[out.rho,out.p] = corr(X,Y,'rows','pairwise'); +rho = out.rho; +rho(isnan(rho) | (out.p>0.05)) = 0; +[rho,row] = sort(abs(rho),1,'descend'); +out.selvars = false(1,nfeats); +% Always take the most correlated feature for each algorithm +out.selvars(unique(row(1,:))) = true; +% Now take any feature that has correlation at least equal to opts.rho +for ii=2:nfeats + out.selvars(unique(row(ii,rho(ii,:)>=opts.rho))) = true; +end +out.selvars = find(out.selvars); +Xaux = X(:,out.selvars); +disp(['-> Keeping ' num2str(size(Xaux,2)) ' out of ' num2str(nfeats) ' features (correlation).']); +% --------------------------------------------------------------------- +nfeats = size(Xaux,2); +if nfeats<=1 + error('-> There is only 1 feature. Stopping space construction.'); +elseif nfeats<=3 + disp('-> There are 3 or less features to do selection. Skipping correlation clustering selection.'); + X = Xaux; + return; +elseif nfeats There are less features than clusters. Skipping correlation clustering selection.'); + X = Xaux; + return; +end +% --------------------------------------------------------------------- +disp('-> Selecting features based on correlation clustering.'); +nalgos = size(Ybin,2); +state = rng; +rng('default'); +out.eva = evalclusters(Xaux', 'kmeans', 'Silhouette', 'KList', 3:nfeats, ... % minimum of three features + 'Distance', 'correlation'); +disp('-> Average silhouette values for each number of clusters.') +disp([out.eva.InspectedK; out.eva.CriterionValues]); +if out.eva.CriterionValues(out.eva.InspectedK==opts.K)<0.5 + disp(['-> The silhouette value for K=' num2str(opts.K) ... + ' is below 0.5. You should consider increasing K.']); + out.Ksuggested = out.eva.InspectedK(find(out.eva.CriterionValues>0.75,1)); + if ~isempty(out.Ksuggested) + disp(['-> A suggested value of K is ' num2str(out.Ksuggested)]); + end +end +% --------------------------------------------------------------------- +rng('default'); +out.clust = bsxfun(@eq, kmeans(Xaux', opts.K, 'Distance', 'correlation', ... + 'MaxIter', opts.MaxIter, ... + 'Replicates', opts.Replicates, ... + 'Options', statset('UseParallel', nworkers~=0), ... + 'OnlinePhase', 'on'), 1:opts.K); +rng(state); +disp(['-> Constructing ' num2str(opts.K) ' clusters of features.']); +% --------------------------------------------------------------------- +% Using these out.clusters, determine all possible combinations that take one +% feature from each out.cluster. +strcmd = '['; +for i=1:opts.K + strcmd = [strcmd 'X' num2str(i) ]; %#ok<*AGROW> + if i +comb = sort(comb,2); +disp(['-> ' num2str(ncomb) ' valid feature combinations.']); + +maxcomb = 1000; +% --------------------------------------------------------------------- +% Determine which combination produces the best separation while using a +% two dimensional PCA projection. The separation is defined by a Tree +% Bagger. +if ncomb>maxcomb + disp('-> There are over 1000 valid combinations. Using a GA+LookUpTable to find an optimal one.'); + gacostvals = NaN.*ones(ncomb,1); + fcnwrap = @(idx) fcnforga(idx,Xaux,Ybin,opts.NTREES,out.clust,nworkers); + gaopts = optimoptions('ga','FitnessLimit',0,'FunctionTolerance',1e-3,... + 'MaxGenerations',100,'MaxStallGenerations',5,... + 'PopulationSize',50); % This sets the maximum to 1000 combinations + ind = ga(fcnwrap,opts.K,[],[],[],[],ones(1,opts.K),sum(out.clust),[],1:opts.K,gaopts); + decoder = false(1,size(Xaux,2)); % Decode the chromosome + for i=1:opts.K + aux = find(out.clust(:,i)); + decoder(aux(ind(i))) = true; + end + out.selvars = out.selvars(decoder); +elseif ncomb==1 + disp('-> There is one valid combination. It will be considered the optimal one.'); + % out.selvars = 1:nfeats; +else + disp('-> There are less than 1000 valid combinations. Using brute-force to find an optimal one.'); + out.ooberr = zeros(ncomb,nalgos); + for i=1:ncomb + tic; + out.ooberr(i,:) = costfcn(comb(i,:),Xaux,Ybin,opts.NTREES,nworkers); + etime = toc; + disp([' -> Combination No. ' num2str(i) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... + 's | Average error : ' num2str(mean(out.ooberr(i,:)))]); + tic; + end + [~,best] = min(sum(out.ooberr,2)); + out.selvars = sort(out.selvars(comb(best,:))); +end +X = X(:,out.selvars); +disp(['-> Keeping ' num2str(size(X, 2)) ' out of ' num2str(nfeats) ' features (clustering).']); + +end +% ========================================================================= +function ooberr = costfcn(comb,X,Ybin,ntrees,nworkers) + +[~, score] = pca(X(:,comb), 'NumComponents', 2); %#ok<*IDISVAR> % Reduce using PCA +nalgos = size(Ybin,2); +ooberr = zeros(1,nalgos); +for j = 1:nalgos + state = rng; + rng('default'); + tree = TreeBagger(ntrees, score, Ybin(:,j), 'OOBPrediction', 'on',... + 'Options', statset('UseParallel', nworkers~=0)); + ooberr(j) = mean(Ybin(:,j)~=str2double(oobPredict(tree))); + rng(state); +end + +end +% ========================================================================= +function sumerr = fcnforga(idx,X,Ybin,ntrees,clust,nworkers) +global gacostvals comb + +tic; +% Decode the chromosome into a binary string representing the selected +% features +ccomb = false(1,size(X,2)); +for i=1:length(idx) + aux = find(clust(:,i)); + ccomb(aux(idx(i))) = true; +end +% Calculate the cost function. Use the lookup table to reduce the amount of +% computation. +ind = find(all(comb==find(ccomb),2)); +if isnan(gacostvals(ind)) + ooberr = costfcn(ccomb,X,Ybin,ntrees,nworkers); + sumerr = sum(ooberr); + gacostvals(ind) = sumerr; +else + sumerr = gacostvals(ind); +end + +etime = toc; +disp([' -> Combination No. ' num2str(ind) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... + 's | Average error : ' num2str(sumerr./size(Ybin,2))]); + +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/TRACE.m b/InstanceSpace-master/TRACE.m new file mode 100644 index 0000000..bc6b240 --- /dev/null +++ b/InstanceSpace-master/TRACE.m @@ -0,0 +1,444 @@ +function out = TRACE(Z, Ybin, P, beta, algolabels, opts) +% ------------------------------------------------------------------------- +% TRACE.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end +% ------------------------------------------------------------------------- +% First step is to transform the data to the footprint space, and to +% calculate the 'space' footprint. This is also the maximum area possible +% for a footprint. +disp(' -> TRACE is calculating the space area and density.'); +ninst = size(Z,1); +nalgos = size(Ybin,2); +out.space = TRACEbuild(Z, true(ninst,1), opts); +disp([' -> Space area: ' num2str(out.space.area) ... + ' | Space density: ' num2str(out.space.density)]); +% ------------------------------------------------------------------------- +% This loop will calculate the footprints for good/bad instances and the +% best algorithm. +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is calculating the algorithm footprints.'); +good = cell(1,nalgos); +best = cell(1,nalgos); +% Use the actual data to calculate the footprints +parfor (i=1:nalgos,nworkers) + tic; + disp([' -> Good performance footprint for ''' algolabels{i} '''']); + good{i} = TRACEbuild(Z, Ybin(:,i), opts); + disp([' -> Best performance footprint for ''' algolabels{i} '''']); + best{i} = TRACEbuild(Z, P==i, opts); + disp([' -> Algorithm ''' algolabels{i} ''' completed. Elapsed time: ' num2str(toc,'%.2f\n') 's']); +end +out.good = good; +out.best = best; +% ------------------------------------------------------------------------- +% Detecting collisions and removing them. +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is detecting and removing contradictory sections of the footprints.'); +for i=1:nalgos + disp([' -> Base algorithm ''' algolabels{i} '''']); + startBase = tic; + for j=i+1:nalgos + disp([' -> TRACE is comparing ''' algolabels{i} ''' with ''' algolabels{j} '''']); + startTest = tic; + [out.best{i}, out.best{j}] = TRACEcontra(out.best{i}, out.best{j}, ... + Z, P==i, P==j, opts);%, false); + + disp([' -> Test algorithm ''' algolabels{j} ... + ''' completed. Elapsed time: ' num2str(toc(startTest),'%.2f\n') 's']); + end + disp([' -> Base algorithm ''' algolabels{i} ... + ''' completed. Elapsed time: ' num2str(toc(startBase),'%.2f\n') 's']); +end +% ------------------------------------------------------------------------- +% Beta hard footprints. First step is to calculate them. +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is calculating the beta-footprint.'); +out.hard = TRACEbuild(Z, ~beta, opts); +% ------------------------------------------------------------------------- +% Calculating performance +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is preparing the summary table.'); +out.summary = cell(nalgos+1,11); +out.summary(1,2:end) = {'Area_Good',... + 'Area_Good_Normalized',... + 'Density_Good',... + 'Density_Good_Normalized',... + 'Purity_Good',... + 'Area_Best',... + 'Area_Best_Normalized',... + 'Density_Best',... + 'Density_Best_Normalized',... + 'Purity_Best'}; +out.summary(2:end,1) = algolabels; +for i=1:nalgos + row = [TRACEsummary(out.good{i}, out.space.area, out.space.density), ... + TRACEsummary(out.best{i}, out.space.area, out.space.density)]; + out.summary(i+1,2:end) = num2cell(round(row,3)); +end + +disp(' -> TRACE has completed. Footprint analysis results:'); +disp(' '); +disp(out.summary); + +end +% ========================================================================= +% SUBFUNCTIONS +% ========================================================================= +function footprint = TRACEbuild(Z, Ybin, opts) + +% If there is no Y to work with, then there is not point on this one +Ig = unique(Z(Ybin,:),'rows'); % There might be points overlapped, so eliminate them to avoid problems +if size(Ig,1)<3 + footprint = TRACEthrow; +else + footprint = struct; +end + +nn = max(min(ceil(sum(Ybin)/20),50),3); +class = dbscan(Ig,nn); % Use DBSCAN to identify dense regions +flag = false; +for i=1:max(class) %Ignore -1/0 + polydata = Ig(class==i,:); + polydata = polydata(boundary(polydata,1),:); + aux = TRACEfitpoly(polydata,Z,Ybin, opts); + if ~isempty(aux) + if ~flag + footprint.polygon = aux; + flag = true; + else + footprint.polygon = union(footprint.polygon,aux); + end + end +end +if isfield(footprint,'polygon') && ~isempty(footprint.polygon) + footprint.polygon = rmslivers(footprint.polygon,1e-2); + footprint.area = area(footprint.polygon); + footprint.elements = sum(isinterior(footprint.polygon,Z)); + footprint.goodElements = sum(isinterior(footprint.polygon,Z(Ybin,:))); + footprint.density = footprint.elements./footprint.area; + footprint.purity = footprint.goodElements./footprint.elements; +else + footprint = TRACEthrow; +end + +end +% ========================================================================= +function [base,test] = TRACEcontra(base,test,Z,Ybase,Ytest,opts)%,isbin) +% +if isempty(base.polygon) || isempty(test.polygon) + return; +end + +maxtries = 3; % Tries once to tighten the bounds. +numtries = 1; +contradiction = intersect(base.polygon,test.polygon); +while contradiction.NumRegions~=0 && numtries<=maxtries + numElements = sum(isinterior(contradiction,Z)); + numGoodElementsBase = sum(isinterior(contradiction,Z(Ybase,:))); + numGoodElementsTest = sum(isinterior(contradiction,Z(Ytest,:))); + purityBase = numGoodElementsBase/numElements; + purityTest = numGoodElementsTest/numElements; + if purityBase>purityTest %&& (~isbin || (purityBase>0.55 && isbin)) + carea = area(contradiction)./area(test.polygon); + disp([' -> ' num2str(round(100.*carea,1)) '%' ... + ' of the test footprint is contradictory.']); + test.polygon = subtract(test.polygon,contradiction); + if numtriespurityBase %&& (~isbin || (purityTest>0.55 && isbin)) + carea = area(contradiction)./area(base.polygon); + disp([' -> ' num2str(round(100.*carea,1)) '%' ... + ' of the base footprint is contradictory.']); + base.polygon = subtract(base.polygon,contradiction); + if numtries Purity of the contradicting areas is equal for both footprints.'); + disp(' -> Ignoring the contradicting area.'); + break; + end + if isempty(base.polygon) || isempty(test.polygon) + break; + else + contradiction = intersect(base.polygon,test.polygon); + end + numtries = numtries+1; +end + +if isempty(base.polygon) + base = TRACEthrow; +else + base.area = area(base.polygon); + base.elements = sum(isinterior(base.polygon,Z)); + base.goodElements = sum(isinterior(base.polygon,Z(Ybase,:))); + base.density = base.elements./base.area; + base.purity = base.goodElements./base.elements; +end +if isempty(test.polygon) + test = TRACEthrow; +else + test.area = area(test.polygon); + test.elements = sum(isinterior(test.polygon,Z)); + test.goodElements = sum(isinterior(test.polygon,Z(Ytest,:))); + test.density = test.elements./test.area; + test.purity = test.goodElements./test.elements; +end + +end +% ========================================================================= +function polygon = TRACEtight(polygon,Z,Ybin,opts) + +splits = regions(polygon); +nregions = length(splits); +flags = true(1,nregions); +for i=1:nregions + % Find the vertex of this polygon + criteria = isinterior(splits(i),Z) & Ybin; + polydata = Z(criteria,:); + if size(polydata,1)<3 + flags(i) = false; + continue + end + aux = TRACEfitpoly(polydata(boundary(polydata,1),:),Z,Ybin,opts); + if isempty(aux) + flags(i) = false; + continue + end + splits(i) = aux; +end +if any(flags) + polygon = union(splits(flags)); +else + polygon = []; +end + +end +% ========================================================================= +function polygon = TRACEfitpoly(polydata,Z,Ybin,opts) + +warning('off','MATLAB:polyshape:repairedBySimplify'); + +if size(polydata,1)<3 + polygon = []; + warning('on','MATLAB:polyshape:repairedBySimplify'); + return +end + +polygon = polyshape(polydata,'Simplify',true); +polygon = rmslivers(polygon,5e-2); + +if ~all(Ybin) + if polygon.NumRegions<1 + polygon = []; + warning('on','MATLAB:polyshape:repairedBySimplify'); + return + end + tri = triangulation(polygon); + nrow = size(tri.ConnectivityList,1); + for ii=1:nrow + tridata = tri.Points(tri.ConnectivityList(ii,:),:); + piece = polyshape(tridata,'Simplify',true); + elements = sum(isinterior(piece,Z)); + goodElements = sum(isinterior(piece,Z(Ybin,:))); + if opts.PI>(goodElements/elements) + polygon = subtract(polygon,piece); + end + end +end + +warning('on','MATLAB:polyshape:repairedBySimplify'); + +end +% ========================================================================= +function out = TRACEsummary(footprint, spaceArea, spaceDensity) +% +out = [footprint.area,... + footprint.area/spaceArea,... + footprint.density,... + footprint.density/spaceDensity,... + footprint.purity]; +out(isnan(out)) = 0; + +end +% ========================================================================= +function footprint = TRACEthrow + +disp(' -> There are not enough instances to calculate a footprint.'); +disp(' -> The subset of instances used is too small.'); +footprint.polygon = []; +footprint.area = 0; +footprint.elements = 0; +footprint.goodElements = 0; +footprint.density = 0; +footprint.purity = 0; + +end +% ========================================================================= +% Function: [class,type]=dbscan(x,k,Eps) +% ------------------------------------------------------------------------- +% Aim: +% Clustering the data with Density-Based Scan Algorithm with Noise (DBSCAN) +% ------------------------------------------------------------------------- +% Input: +% x - data set (m,n); m-objects, n-variables +% k - number of objects in a neighborhood of an object +% (minimal number of objects considered as a cluster) +% Eps - neighborhood radius, if not known avoid this parameter or put [] +% ------------------------------------------------------------------------- +% Output: +% class - vector specifying assignment of the i-th object to certain +% cluster (m,1) +% type - vector specifying type of the i-th object +% (core: 1, border: 0, outlier: -1) +% ------------------------------------------------------------------------- +% Example of use: +% x=[randn(30,2)*.4;randn(40,2)*.5+ones(40,1)*[4 4]]; +% [class,type]=dbscan(x,5,[]); +% ------------------------------------------------------------------------- +% References: +% [1] M. Ester, H. Kriegel, J. Sander, X. Xu, A density-based algorithm for +% discovering clusters in large spatial databases with noise, proc. +% 2nd Int. Conf. on Knowledge Discovery and Data Mining, Portland, OR, 1996, +% p. 226, available from: +% www.dbs.informatik.uni-muenchen.de/cgi-bin/papers?query=--CO +% [2] M. Daszykowski, B. Walczak, D. L. Massart, Looking for +% Natural Patterns in Data. Part 1: Density Based Approach, +% Chemom. Intell. Lab. Syst. 56 (2001) 83-92 +% ------------------------------------------------------------------------- +% Written by Michal Daszykowski +% Department of Chemometrics, Institute of Chemistry, +% The University of Silesia +% December 2004 +% http://www.chemometria.us.edu.pl + +function [class,type]=dbscan(x,k,Eps) + +m=size(x,1); + +if nargin<3 || isempty(Eps) + [Eps]=epsilon(x,k); +end + +x=[(1:m)' x]; +[m,n]=size(x); +type=zeros(1,m); +no=1; +touched=zeros(m,1); +class=zeros(1,m); +for i=1:m + if touched(i)==0 + ob=x(i,:); + D=dist(ob(2:n),x(:,2:n)); + ind=find(D<=Eps); + + if length(ind)>1 && length(ind)=k+1 + type(i)=1; + class(ind)=ones(length(ind),1)*max(no); + + while ~isempty(ind) + ob=x(ind(1),:); + touched(ind(1))=1; + ind(1)=[]; + D=dist(ob(2:n),x(:,2:n)); + i1=find(D<=Eps); + + if length(i1)>1 + class(i1)=no; + if length(i1)>=k+1 + type(ob(1))=1; + else + type(ob(1))=0; + end + + for j=1:length(i1) + if touched(i1(j))==0 + touched(i1(j))=1; + ind=[ind i1(j)]; + class(i1(j))=no; + end + end + end + end + no=no+1; + end + end +end + +i1=find(class==0); +class(i1)=-1; +type(i1)=-1; + +end +% ========================================================================= +function [Eps]=epsilon(x,k) + +% Function: [Eps]=epsilon(x,k) +% +% Aim: +% Analytical way of estimating neighborhood radius for DBSCAN +% +% Input: +% x - data matrix (m,n); m-objects, n-variables +% k - number of objects in a neighborhood of an object +% (minimal number of objects considered as a cluster) + +[m,n]=size(x); + +Eps=((prod(max(x)-min(x))*k*gamma(.5*n+1))/(m*sqrt(pi.^n))).^(1/n); + +end +% ========================================================================= +function [D]=dist(i,x) + +% function: [D]=dist(i,x) +% +% Aim: +% Calculates the Euclidean distances between the i-th object and all objects in x +% +% Input: +% i - an object (1,n) +% x - data matrix (m,n); m-objects, n-variables +% +% Output: +% D - Euclidean distance (m,1) + +[m,n]=size(x); +D=sqrt(sum((((ones(m,1)*i)-x).^2)')); + +if n==1 + D=abs((ones(m,1)*i-x))'; +end + +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/TRACEtest.m b/InstanceSpace-master/TRACEtest.m new file mode 100644 index 0000000..c11b379 --- /dev/null +++ b/InstanceSpace-master/TRACEtest.m @@ -0,0 +1,64 @@ +function model = TRACEtest(model, Z, Ybin, P, beta, algolabels) + +nalgos = length(model.best); +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is calculating the algorithm footprints.'); +model.test.best = zeros(nalgos,5); +model.test.good = zeros(nalgos,5); +% model.test.bad = zeros(nalgos,5); +% Use the actual data to calculate the footprints +for i=1:nalgos + model.test.best(i,:) = TRACEtestsummary(model.best{i}, Z, P==i, model.space.area, model.space.density); + model.test.good(i,:) = TRACEtestsummary(model.good{i}, Z, Ybin(:,i), model.space.area, model.space.density); + % model.test.bad(i,:) = TRACEtestsummary(model.bad{i}, Z, ~Ybin(:,i), model.space.area, model.space.density); +end + +% ------------------------------------------------------------------------- +% Beta hard footprints. First step is to calculate them. +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is calculating the beta-footprints.'); +% model.test.easy = TRACEtestsummary(model.easy, Z, beta, model.space.area, model.space.density); +model.test.hard = TRACEtestsummary(model.hard, Z, ~beta, model.space.area, model.space.density); +% ------------------------------------------------------------------------- +% Calculating performance +disp('-------------------------------------------------------------------------'); +disp(' -> TRACE is preparing the summary table.'); +model.summary = cell(nalgos+1,11); +model.summary(1,2:end) = {'Area_Good',... + 'Area_Good_Normalized',... + 'Density_Good',... + 'Density_Good_Normalized',... + 'Purity_Good',... + 'Area_Best',... + 'Area_Best_Normalized',... + 'Density_Best',... + 'Density_Best_Normalized',... + 'Purity_Best'}; +model.summary(2:end,1) = algolabels(1:nalgos); +model.summary(2:end,2:end) = num2cell([model.test.good model.test.best]); + +disp(' -> TRACE has completed. Footprint analysis results:'); +disp(' '); +disp(model.summary); + +end +% ========================================================================= +function out = TRACEtestsummary(footprint, Z, Ybin, spaceArea, spaceDensity) +% +if isempty(footprint.polygon) || all(~Ybin) + out = zeros(5,1); +else + elements = sum(isinterior(footprint.polygon, Z)); + goodElements = sum(isinterior(footprint.polygon, Z(Ybin,:))); + density = elements./footprint.area; + purity = goodElements./elements; + + out = [footprint.area,... + footprint.area/spaceArea,... + density,... + density/spaceDensity,... + purity]; +end +out(isnan(out)) = 0; +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/buildIS.m b/InstanceSpace-master/buildIS.m new file mode 100644 index 0000000..442056e --- /dev/null +++ b/InstanceSpace-master/buildIS.m @@ -0,0 +1,322 @@ +function model = buildIS(rootdir) +% ------------------------------------------------------------------------- +% buildIS.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2019 +% +% ------------------------------------------------------------------------- + +startProcess = tic; +scriptdisc('buildIS.m'); +% ------------------------------------------------------------------------- +% Collect all the data from the files +disp(['Root Directory: ' rootdir]); +datafile = [rootdir 'metadata.csv']; +optsfile = [rootdir 'options.json']; +if ~isfile(datafile) || ~isfile(optsfile) + error(['Please place the datafiles in the directory ''' rootdir '''']); +end +opts = jsondecode(fileread(optsfile)); +disp('-------------------------------------------------------------------------'); +disp('-> Listing options to be used:'); +optfields = fieldnames(opts); +for i = 1:length(optfields) + disp(optfields{i}); + disp(opts.(optfields{i})); +end +useparallel = isfield(opts,'parallel') && isfield(opts.parallel,'flag') && opts.parallel.flag; +if useparallel + disp('-------------------------------------------------------------------------'); + disp('-> Starting parallel processing pool.'); + delete(gcp('nocreate')); + if isfield(opts.parallel,'ncores') && isnumeric(opts.parallel.ncores) + mypool = parpool('local',opts.parallel.ncores,'SpmdEnabled',false); + else + mypool = parpool('local','SpmdEnabled',false); + end + if ispc + addAttachedFiles(mypool,{'svmpredict.mexw64','svmtrain.mexw64'}); + elseif isunix + addAttachedFiles(mypool,{'svmpredict.mexa64','svmtrain.mexa64'}); + elseif ismac + addAttachedFiles(mypool,{'libsvmpredict.mexmaci64','libsvmtrain.mexmaci64'}); + end +end +disp('-------------------------------------------------------------------------'); +disp('-> Loading the data.'); +Xbar = readtable(datafile); +varlabels = Xbar.Properties.VariableNames; +isname = strcmpi(varlabels,'instances'); +isfeat = strncmpi(varlabels,'feature_',8); +isalgo = strncmpi(varlabels,'algo_',5); +issource = strcmpi(varlabels,'source'); +model.data.instlabels = Xbar{:,isname}; +if isnumeric(model.data.instlabels) + model.data.instlabels = num2cell(model.data.instlabels); + model.data.instlabels = cellfun(@(x) num2str(x),model.data.instlabels,'UniformOutput',false); +end +if any(issource) + model.data.S = categorical(Xbar{:,issource}); +end +model.data.X = Xbar{:,isfeat}; +model.data.Y = Xbar{:,isalgo}; +% ------------------------------------------------------------------------- +% Giving the oportunity to pick and choose which features/algorithms to +% work with +model.data.featlabels = varlabels(isfeat); +if isfield(opts,'selvars') && isfield(opts.selvars,'feats') + disp('-------------------------------------------------------------------------'); + msg = '-> Using the following features: '; + isselfeat = false(1,length(model.data.featlabels)); + for i=1:length(opts.selvars.feats) + isselfeat = isselfeat | strcmp(model.data.featlabels,opts.selvars.feats{i}); + msg = [msg opts.selvars.feats{i} ' ']; %#ok + end + disp(msg); + model.data.X = model.data.X(:,isselfeat); + model.data.featlabels = model.data.featlabels(isselfeat); +end + +model.data.algolabels = varlabels(isalgo); +if isfield(opts,'selvars') && isfield(opts.selvars,'algos') + disp('-------------------------------------------------------------------------'); + msg = '-> Using the following algorithms: '; + isselalgo = false(1,length(model.data.algolabels)); + for i=1:length(opts.selvars.algos) + isselalgo = isselalgo | strcmp(model.data.algolabels,opts.selvars.algos{i}); + msg = [msg opts.selvars.algos{i} ' ']; %#ok + end + disp(msg); + model.data.Y = model.data.Y(:,isselalgo); + model.data.algolabels = model.data.algolabels(isselalgo); +end +% nalgos = size(model.data.Y,2); +% ------------------------------------------------------------------------- +% PROBABLY HERE SHOULD DO A SANITY CHECK, I.E., IS THERE TOO MANY NANS? +idx = all(isnan(model.data.X),2) | all(isnan(model.data.Y),2); +if any(idx) + warning('-> There are instances with too many missing values. They are being removed to increase speed.'); + model.data.X = model.data.X(~idx,:); + model.data.Y = model.data.Y(~idx,:); + model.data.instlabels = model.data.instlabels(~idx); + if isfield(model.data,'S') + model.data.S = model.data.S(~idx); + end +end +idx = mean(isnan(model.data.X),1)>=0.20; % These features are very weak. +if any(idx) + warning('-> There are features with too many missing values. They are being removed to increase speed.'); + model.data.X = model.data.X(:,~idx); + model.data.featlabels = model.data.featlabels(~idx); +end +ninst = size(model.data.X,1); +nuinst = size(unique(model.data.X,'rows'),1); +if nuinst/ninst<0.5 + warning('-> There are too many repeated instances. It is unlikely that this run will produce good results.'); +end +% ------------------------------------------------------------------------- +% Storing the raw data for further processing, e.g., graphs +model.data.Xraw = model.data.X; +model.data.Yraw = model.data.Y; +% ------------------------------------------------------------------------- +% Removing the template data such that it can be used in the labels of +% graphs and figures. +model.data.featlabels = strrep(model.data.featlabels,'feature_',''); +model.data.algolabels = strrep(model.data.algolabels,'algo_',''); +% ------------------------------------------------------------------------- +% Running PRELIM as to pre-process the data, including scaling and bounding +opts.prelim = opts.perf; +opts.prelim.bound = opts.bound.flag; +opts.prelim.norm = opts.norm.flag; +[model.data.X,model.data.Y,model.data.Ybest,... + model.data.Ybin,model.data.P,model.data.numGoodAlgos,... + model.data.beta,model.prelim] = PRELIM(model.data.X, model.data.Y, opts.prelim); + +idx = all(~model.data.Ybin,1); +if any(idx) + warning('-> There are algorithms with no ''good'' instances. They are being removed to increase speed.'); + model.data.Yraw = model.data.Yraw(:,~idx); + model.data.Y = model.data.Y(:,~idx); + model.data.Ybin = model.data.Ybin(:,~idx); + model.data.algolabels = model.data.algolabels(~idx); + nalgos = size(model.data.Y,2); + if nalgos==0 + error('-> There are no ''good'' algorithms. Please verify the binary performance measure. STOPPING!') + end +end +% ------------------------------------------------------------------------- +% If we are only meant to take some observations +disp('-------------------------------------------------------------------------'); +ninst = size(model.data.X,1); +fractional = isfield(opts,'selvars') && ... + isfield(opts.selvars,'smallscaleflag') && ... + opts.selvars.smallscaleflag && ... + isfield(opts.selvars,'smallscale') && ... + isfloat(opts.selvars.smallscale); +fileindexed = isfield(opts,'selvars') && ... + isfield(opts.selvars,'fileidxflag') && ... + opts.selvars.fileidxflag && ... + isfield(opts.selvars,'fileidx') && ... + isfile(opts.selvars.fileidx); +bydensity = isfield(opts,'selvars') && ... + isfield(opts.selvars,'densityflag') && ... + opts.selvars.densityflag && ... + isfield(opts.selvars,'mindistance') && ... + isfloat(opts.selvars.mindistance) && ... + isfield(opts.selvars,'type') && ... + ischar(opts.selvars.type); +if fractional + disp(['-> Creating a small scale experiment for validation. Percentage of subset: ' ... + num2str(round(100.*opts.selvars.smallscale,2)) '%']); + state = rng; + rng('default'); + aux = cvpartition(ninst,'HoldOut',opts.selvars.smallscale); + rng(state); + subsetIndex = aux.test; +elseif fileindexed + disp('-> Using a subset of the instances.'); + subsetIndex = false(size(model.data.X,1),1); + aux = table2array(readtable(opts.selvars.fileidx)); + aux(aux>ninst) = []; + subsetIndex(aux) = true; +elseif bydensity + disp('-> Creating a small scale experiment for validation based on density.'); + subsetIndex = FILTER(model.data.X, model.data.Y, model.data.Ybin, ... + opts.selvars); + subsetIndex = ~subsetIndex; + disp(['-> Percentage of instances retained: ' ... + num2str(round(100.*mean(subsetIndex),2)) '%']); +else + disp('-> Using the complete set of the instances.'); + subsetIndex = true(ninst,1); +end + +if fileindexed || fractional || bydensity + if bydensity + model.data_dense = model.data; + end + model.data.X = model.data.X(subsetIndex,:); + model.data.Y = model.data.Y(subsetIndex,:); + model.data.Xraw = model.data.Xraw(subsetIndex,:); + model.data.Yraw = model.data.Yraw(subsetIndex,:); + model.data.Ybin = model.data.Ybin(subsetIndex,:); + model.data.beta = model.data.beta(subsetIndex); + model.data.numGoodAlgos = model.data.numGoodAlgos(subsetIndex); + model.data.Ybest = model.data.Ybest(subsetIndex); + model.data.P = model.data.P(subsetIndex); + model.data.instlabels = model.data.instlabels(subsetIndex); + if isfield(model.data,'S') + model.data.S = model.data.S(subsetIndex); + end +end +nfeats = size(model.data.X,2); +% ------------------------------------------------------------------------- +% Automated feature selection. +% Keep track of the features that have been removed so we can use them +% later +model.featsel.idx = 1:nfeats; +if opts.sifted.flag + disp('========================================================================='); + disp('-> Calling SIFTED for auto-feature selection.'); + disp('========================================================================='); + [model.data.X, model.sifted] = SIFTED(model.data.X, model.data.Y, model.data.Ybin, opts.sifted); + model.data.featlabels = model.data.featlabels(model.sifted.selvars); + model.featsel.idx = model.featsel.idx(model.sifted.selvars); + + if bydensity + disp('-> Creating a small scale experiment for validation based on density.'); + % model.data.featlabels = model.data_dense.featlabels(model.sifted.selvars); + subsetIndex = FILTER(model.data_dense.X(:,model.featsel.idx), ... + model.data_dense.Y, ... + model.data_dense.Ybin, ... + opts.selvars); + subsetIndex = ~subsetIndex; + model.data.X = model.data_dense.X(subsetIndex,model.featsel.idx); + model.data.Y = model.data_dense.Y(subsetIndex,:); + model.data.Xraw = model.data_dense.Xraw(subsetIndex,:); + model.data.Yraw = model.data_dense.Yraw(subsetIndex,:); + model.data.Ybin = model.data_dense.Ybin(subsetIndex,:); + model.data.beta = model.data_dense.beta(subsetIndex); + model.data.numGoodAlgos = model.data_dense.numGoodAlgos(subsetIndex); + model.data.Ybest = model.data_dense.Ybest(subsetIndex); + model.data.P = model.data_dense.P(subsetIndex); + model.data.instlabels = model.data_dense.instlabels(subsetIndex); + if isfield(model.data_dense,'S') + model.data.S = model.data_dense.S(subsetIndex); + end + disp(['-> Percentage of instances retained: ' ... + num2str(round(100.*mean(subsetIndex),2)) '%']); + end +end +% ------------------------------------------------------------------------- +% This is the final subset of features. Calculate the two dimensional +% projection using the PILOT algorithm (Munoz et al. Mach Learn 2018) +disp('========================================================================='); +disp('-> Calling PILOT to find the optimal projection.'); +disp('========================================================================='); +model.pilot = PILOT(model.data.X, model.data.Y, model.data.featlabels, opts.pilot); +% ------------------------------------------------------------------------- +% Finding the empirical bounds based on the ranges of the features and the +% correlations of the different edges. +disp('========================================================================='); +disp('-> Finding empirical bounds using CLOISTER.'); +disp('========================================================================='); +model.cloist = CLOISTER(model.data.X, model.pilot.A, opts.cloister); +% ------------------------------------------------------------------------- +% Algorithm selection. Fit a model that would separate the space into +% classes of good and bad performance. +disp('========================================================================='); +disp('-> Summoning PYTHIA to train the prediction models.'); +disp('========================================================================='); +model.pythia = PYTHIA(model.pilot.Z, model.data.Yraw, model.data.Ybin, model.data.Ybest, model.data.algolabels, opts.pythia); +% ------------------------------------------------------------------------- +% Calculating the algorithm footprints. +disp('========================================================================='); +disp('-> Calling TRACE to perform the footprint analysis.'); +disp('========================================================================='); +if opts.trace.usesim + disp(' -> TRACE will use PYTHIA''s results to calculate the footprints.'); + model.trace = TRACE(model.pilot.Z, model.pythia.Yhat, model.pythia.selection0, model.data.beta, model.data.algolabels, opts.trace); +else + disp(' -> TRACE will use experimental data to calculate the footprints.'); + model.trace = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); +end + +if useparallel + disp('-------------------------------------------------------------------------'); + disp('-> Closing parallel processing pool.'); + delete(mypool); +end +% ------------------------------------------------------------------------- +% Preparing the outputs for further analysis +model.opts = opts; +% ------------------------------------------------------------------------- +disp('-------------------------------------------------------------------------'); +disp('-> Storing the raw MATLAB results for post-processing and/or debugging.'); +save([rootdir 'model.mat'],'-struct','model'); % Save the main results +save([rootdir 'workspace.mat']); % Save the full workspace for debugging +% ------------------------------------------------------------------------- +if opts.outputs.csv + % Storing the output data as a CSV files. This is for easier + % post-processing. All workspace data will be stored in a matlab file + % later. + scriptcsv(model,rootdir); + if opts.outputs.web + scriptweb(model,rootdir); + end +end +% ------------------------------------------------------------------------- +% Making all the plots. First, plotting the features and performance as +% scatter plots. +if opts.outputs.png + scriptpng(model,rootdir); +end +% ------------------------------------------------------------------------- +disp(['-> Completed! Elapsed time: ' num2str(toc(startProcess)) 's']); +disp('EOF:SUCCESS'); +end diff --git a/InstanceSpace-master/example.m b/InstanceSpace-master/example.m new file mode 100644 index 0000000..8aee375 --- /dev/null +++ b/InstanceSpace-master/example.m @@ -0,0 +1,60 @@ +rootdir = './trial/'; + +opts.parallel.flag = false; +opts.parallel.ncores = 2; + +opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. +opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure +opts.perf.epsilon = 0.20; % Threshold of good performance +opts.perf.betaThreshold = 0.55; % Beta-easy threshold +opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing +opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) + +opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances +opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment +% You can also provide a file with the indexes of the instances to be used. +% This should be a csvfile with a single column of integer numbers that +% should be lower than the number of instances +opts.selvars.fileidxflag = false; +opts.selvars.fileidx = ''; +opts.selvars.densityflag = false; +opts.selvars.mindistance = 0.1; +opts.selvars.type = 'Ftr&Good'; + +opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. +opts.sifted.rho = 0.1; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 +opts.sifted.K = 10; % Number of final features. Ideally less than 10. +opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) +opts.sifted.MaxIter = 1000; +opts.sifted.Replicates = 100; + +opts.pilot.analytic = false; % Calculate the analytical or numerical solution +opts.pilot.ntries = 5; % Number of attempts carried out by PBLDR + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +opts.pythia.cvfolds = 5; +opts.pythia.ispolykrnl = false; +opts.pythia.useweights = false; +opts.pythia.uselibsvm = false; + +opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints +opts.trace.PI = 0.55; % Purity threshold + +opts.outputs.csv = true; % +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 +opts.outputs.png = true; % + +% Saving all the information as a JSON file +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = buildIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end \ No newline at end of file diff --git a/InstanceSpace-master/exampleWeb.m b/InstanceSpace-master/exampleWeb.m new file mode 100644 index 0000000..329f368 --- /dev/null +++ b/InstanceSpace-master/exampleWeb.m @@ -0,0 +1,9 @@ +function exampleWeb(rootdir) + +try + model = trainIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end +end diff --git a/InstanceSpace-master/exploreIS.m b/InstanceSpace-master/exploreIS.m new file mode 100644 index 0000000..3d8bf4d --- /dev/null +++ b/InstanceSpace-master/exploreIS.m @@ -0,0 +1,222 @@ +function out = exploreIS(rootdir) +% ------------------------------------------------------------------------- +% exploreIS.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2019 +% +% ------------------------------------------------------------------------- + +startProcess = tic; +scriptdisc('exploreIS.m'); +% ------------------------------------------------------------------------- +% Collect all the data from the files +disp(['Root Directory: ' rootdir]); +modelfile = [rootdir 'model.mat']; +datafile = [rootdir 'metadata_test.csv']; +if ~isfile(modelfile) || ~isfile(datafile) + error(['Please place the datafiles in the directory ''' rootdir '''']); +end +model = load(modelfile); +disp('-------------------------------------------------------------------------'); +disp('Listing options used:'); +optfields = fieldnames(model.opts); +for i = 1:length(optfields) + disp(optfields{i}); + disp(model.opts.(optfields{i})); +end +disp('-------------------------------------------------------------------------'); +disp('-> Loading the data'); +Xbar = readtable(datafile); +varlabels = Xbar.Properties.VariableNames; +isname = strcmpi(varlabels,'instances'); +isfeat = strncmpi(varlabels,'feature_',8); +isalgo = strncmpi(varlabels,'algo_',5); +issource = strcmpi(varlabels,'source'); +out.data.instlabels = Xbar{:,isname}; +if isnumeric(out.data.instlabels) + out.data.instlabels = num2cell(out.data.instlabels); + out.data.instlabels = cellfun(@(x) num2str(x),out.data.instlabels,'UniformOutput',false); +end +if any(issource) + out.data.S = categorical(Xbar{:,issource}); +end +out.data.X = Xbar{:,isfeat}; +out.data.Y = Xbar{:,isalgo}; +[ninst,nalgos] = size(out.data.Y); +% ------------------------------------------------------------------------- +% HERE CHECK IF THE NUMBER OF ALGORITHMS IS THE SAME AS IN THE MODEL. IF +% NOT, CHECK IF THE NAMES OF THE ALGORITHMS ARE THE SAME, IF NOT, MOVE THE +% DATA IN SUCH WAY THAT THE NON-EXISTING ALGORITHMS ARE MADE NAN AND THE +% NEW ALGORITHMS ARE LAST. +out.data.algolabels = strrep(varlabels(isalgo),'algo_',''); +algoexist = zeros(1,nalgos); +for ii=1:nalgos + aux = find(strcmp(out.data.algolabels{ii},model.data.algolabels)); + if ~isempty(aux) + algoexist(ii) = aux; + end +end +newalgos = sum(algoexist==0); +modelalgos = length(model.data.algolabels); +Yaux = NaN+ones(ninst, modelalgos+newalgos); +lblaux = model.data.algolabels; +acc = modelalgos+1; +for ii=1:nalgos + if algoexist(ii)==0 + Yaux(:,acc) = out.data.Y(:,ii); + lblaux(:,acc) = out.data.algolabels(ii); + acc = acc+1; + else + Yaux(:,algoexist(ii)) = out.data.Y(:,ii); + % lblaux(:,acc) = out.data.algolabels(ii); + end +end +out.data.Y = Yaux; +out.data.algolabels = lblaux; +nalgos = size(out.data.Y,2); +% ------------------------------------------------------------------------- +% Storing the raw data for further processing, e.g., graphs +out.data.Xraw = out.data.X; +out.data.Yraw = out.data.Y; +% ------------------------------------------------------------------------- +% Determine whether the performance of an algorithm is a cost measure to +% be minimized or a profit measure to be maximized. Moreover, determine +% whether we are using an absolute threshold as good peformance (the +% algorithm has a performance better than the threshold) or a relative +% performance (the algorithm has a performance that is similar that the +% best algorithm minus a percentage). +disp('-------------------------------------------------------------------------'); +disp('-> Calculating the binary measure of performance'); +msg = '-> An algorithm is good if its performace is '; +MaxPerf = false; +if isfield(model.opts.perf, 'MaxPerf') + MaxPerf = model.opts.perf.MaxPerf; +elseif isfield(model.opts.perf, 'MaxMin') + MaxPerf = model.opts.perf.MaxMin; +else + warning('Can not find parameter "MaxPerf" in the trained model. We are assuming that performance metric is needed to be minimized.'); +end +if MaxPerf + Yaux = out.data.Y; + Yaux(isnan(Yaux)) = -Inf; + [rankPerf,rankAlgo] = sort(Yaux,2,'descend'); + out.data.bestPerformace = rankPerf(:,1); + out.data.P = rankAlgo(:,1); + if model.opts.perf.AbsPerf + out.data.Ybin = out.data.Y>=model.opts.perf.epsilon; + msg = [msg 'higher than ' num2str(model.opts.perf.epsilon)]; + else + out.data.bestPerformace(out.data.bestPerformace==0) = eps; + out.data.Y(out.data.Y==0) = eps; + out.data.Y = 1-bsxfun(@rdivide,out.data.Y,out.data.bestPerformace); + out.data.Ybin = (1-bsxfun(@rdivide,Yaux,out.data.bestPerformace))<=model.opts.perf.epsilon; + msg = [msg 'within ' num2str(round(100.*model.opts.perf.epsilon)) '% of the best.']; + end +else + Yaux = out.data.Y; + Yaux(isnan(Yaux)) = Inf; + [rankPerf,rankAlgo] = sort(Yaux,2,'ascend'); + out.data.bestPerformace = rankPerf(:,1); + out.data.P = rankAlgo(:,1); + if model.opts.perf.AbsPerf + out.data.Ybin = out.data.Y<=model.opts.perf.epsilon; + msg = [msg 'less than ' num2str(model.opts.perf.epsilon)]; + else + out.data.bestPerformace(out.data.bestPerformace==0) = eps; + out.data.Y(out.data.Y==0) = eps; + out.data.Y = bsxfun(@rdivide,out.data.Y,out.data.bestPerformace)-1; + out.data.Ybin = (bsxfun(@rdivide,Yaux,out.data.bestPerformace)-1)<=model.opts.perf.epsilon; + msg = [msg 'within ' num2str(round(100.*model.opts.perf.epsilon)) '% of the best.']; + end +end +disp(msg); +out.data.numGoodAlgos = sum(out.data.Ybin,2); +out.data.beta = out.data.numGoodAlgos>model.opts.perf.betaThreshold*nalgos; +% --------------------------------------------------------------------- +% Automated pre-processing +if model.opts.auto.preproc && model.opts.bound.flag + disp('-------------------------------------------------------------------------'); + disp('-> Auto-pre-processing. Bounding outliers, scaling and normalizing the data.'); + % Eliminate extreme outliers, i.e., any point that exceedes 5 times the + % inter quantile range, by bounding them to that value. + disp('-> Removing extreme outliers from the feature values.'); + himask = bsxfun(@gt,out.data.X,model.bound.hibound); + lomask = bsxfun(@lt,out.data.X,model.bound.lobound); + out.data.X = out.data.X.*~(himask | lomask) + bsxfun(@times,himask,model.bound.hibound) + ... + bsxfun(@times,lomask,model.bound.lobound); +end + +if model.opts.auto.preproc && model.opts.norm.flag + % Normalize the data using Box-Cox and out.pilot.Z-transformations + disp('-> Auto-normalizing the data.'); + out.data.X = bsxfun(@minus,out.data.X,model.norm.minX)+1; + out.data.X = bsxfun(@rdivide,bsxfun(@power,out.data.X,model.norm.lambdaX)-1,model.norm.lambdaX); + out.data.X = bsxfun(@rdivide,bsxfun(@minus,out.data.X,model.norm.muX),model.norm.sigmaX); + + % If the algorithm is new, something else should be made... + out.data.Y(out.data.Y==0) = eps; % Assumes that out.data.Y is always positive and higher than 1e-16 + out.data.Y(:,1:modelalgos) = bsxfun(@rdivide,bsxfun(@power,out.data.Y(:,1:modelalgos),model.norm.lambdaY)-1,model.norm.lambdaY); + out.data.Y(:,1:modelalgos) = bsxfun(@rdivide,bsxfun(@minus,out.data.Y(:,1:modelalgos),model.norm.muY),model.norm.sigmaY); + if newalgos>0 + [~,out.data.Y(:,modelalgos+1:nalgos),out.norm] = autoNormalize(ones(ninst,1), ... % Dummy variable + out.data.Y(:,modelalgos+1:nalgos)); + end +end +% --------------------------------------------------------------------- +% This is the final subset of features. +out.featsel.idx = model.featsel.idx; +out.data.X = out.data.X(:,out.featsel.idx); +out.data.featlabels = strrep(varlabels(isfeat),'feature_',''); +out.data.featlabels = out.data.featlabels(model.featsel.idx); +% --------------------------------------------------------------------- +% Calculate the two dimensional projection using the PBLDR algorithm +% (Munoz et al. Mach Learn 2018) +out.pilot.Z = out.data.X*model.pilot.A'; +% ------------------------------------------------------------------------- +% Algorithm selection. Fit a model that would separate the space into +% classes of good and bad performance. +out.pythia = PYTHIAtest(model.pythia, out.pilot.Z, out.data.Yraw, ... + out.data.Ybin, out.data.bestPerformace, ... + out.data.algolabels); +% ------------------------------------------------------------------------- +% Validating the footprints +if model.opts.trace.usesim + out.trace = TRACEtest(model.trace, out.pilot.Z, out.pythia.Yhat, ... + out.pythia.selection0, out.data.beta, ... + out.data.algolabels); +% out.trace = TRACE(out.pilot.Z, out.pythia.Yhat, out.pythia.selection0, ... +% out.data.beta, out.data.algolabels, model.opts.trace); +else + out.trace = TRACEtest(model.trace, out.pilot.Z, out.data.Ybin, ... + out.data.P, out.data.beta, ... + out.data.algolabels); +% out.trace = TRACE(out.pilot.Z, out.data.Ybin, out.data.P, out.data.beta,... +% out.data.algolabels, model.opts.trace); +end + +out.opts = model.opts; +% ------------------------------------------------------------------------- +% Writing the results +if model.opts.outputs.csv + scriptcsv(out,rootdir); + if model.opts.outputs.web + scriptweb(out,rootdir); + end +end + +if model.opts.outputs.png + scriptpng(out,rootdir); +end + +disp('-------------------------------------------------------------------------'); +disp('-> Storing the raw MATLAB results for post-processing and/or debugging.'); +save([rootdir 'workspace_test.mat']); % Save the full workspace for debugging +disp(['-> Completed! Elapsed time: ' num2str(toc(startProcess)) 's']); +disp('EOF:SUCCESS'); +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/liveDemoIS.mlx b/InstanceSpace-master/liveDemoIS.mlx new file mode 100644 index 0000000..673deb5 Binary files /dev/null and b/InstanceSpace-master/liveDemoIS.mlx differ diff --git a/InstanceSpace-master/older_scripts/CVNND.m b/InstanceSpace-master/older_scripts/CVNND.m new file mode 100644 index 0000000..35b1198 --- /dev/null +++ b/InstanceSpace-master/older_scripts/CVNND.m @@ -0,0 +1,95 @@ +function CVNND_Single(Net) + +%% Descriptions +% CVNND stands for cofficient varioation of the nearest neighbor distances (NNDs). +% For each point in the instance space, this function calculates its distance +% form its nearest neighbor point. Then, claculates the coefficinet variation +% of all such distances. CVNND is used as a measure of distribution +% uniformuity (evenness) for non-classified samples. In fact, uniformity +% can be calculated as 1-CVNND. + +% Depending on the flag, we might regard NND for both features and +% algorithm prefromnces (APs). In such cases, NNDs of features and APs are +% calculated with different scales, which concide with the scalses that +% data sets are purified with the corresponding flags in +% purifyInstIS_Cmp(Net, epsilon, flag) function. + +% The argument of this function is: +% Net: is the name of metadata file including the instances and their features +% ========================================================================= +% Code by: Hossein Alipour +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% Email: h.alipour@unimelb.edu.au + +% Copyright: Hossein Alipour +% + +%% + +TblHeader_CVNND = {'InstNumb' 'CV_All' 'Uniformity_All' }; + +textHeader_CVNND = strjoin(TblHeader_CVNND, ','); + +NewFileName = sprintf('CVNND_%s.csv', Net); +fid = fopen(sprintf('%s',NewFileName),'w'); +fprintf(fid,'%s\n',textHeader_CVNND); +fclose(fid); +clear fid* + + Xbar = readtable(sprintf('%s.csv', Net)); + +%% + + + varlabels = Xbar.Properties.VariableNames; + isfeat = strncmpi(varlabels,'feature_',8); + isalgo = strncmpi(varlabels,'algo_',5); + numFtr = sum(isfeat); + numAlgo = sum(isalgo); + X = Xbar{:,isfeat}; + Y = Xbar{:,isalgo}; + + + opts.norm.flag = true; + [X, Y, model.norm] = autoNormalize(X, Y, opts.norm); + + + + + %% The loop to calculate CVNND and Uniformity (Evenness); + + nearestDist = zeros(length(X),1); + for ii=1:length(X) + Xtmp = X; + Xtmp(ii,:)=[]; + allDiff = bsxfun(@minus,Xtmp,X(ii,:)); + EucDist = cellfun(@norm,num2cell(allDiff,2)); + nearestDist(ii) = min(EucDist); + end + + CV = std(nearestDist)/mean(nearestDist) % coefficient of variation of the nearest neighbor distance + Uniformity = 1- CV + + + + %% Wrtie data on the table +% TblHeader_CVNND = {'Epsilon' 'InstNumb' 'NoViSANumb' 'ViSANumb' 'RViSA' 'CV_All' 'Uniformity_All' 'CV_NoViSA' 'Uniformity_NoViSA' }; + Current_data_CVNND = [ length(X), CV, Uniformity]; + fid = fopen(sprintf('%s',NewFileName),'a'); + fprintf(fid,'%f,%f,%f\n', Current_data_CVNND); + fclose(fid); + clear fid* + + %% + clear Xbar; + clear X; + clear XbarNoViSA; + clear XNoViSA; + clear XbarViSA +end + + + diff --git a/InstanceSpace-master/older_scripts/autoNormalize.m b/InstanceSpace-master/older_scripts/autoNormalize.m new file mode 100644 index 0000000..6e0dae6 --- /dev/null +++ b/InstanceSpace-master/older_scripts/autoNormalize.m @@ -0,0 +1,32 @@ +function [X,Y,out] = autoNormalize(X, Y) + +nfeats = size(X,2); +nalgos = size(Y,2); +disp('-> Auto-normalizing the data using Box-Cox and Z transformations.'); +out.minX = min(X,[],1); +X = bsxfun(@minus,X,out.minX)+1; +out.lambdaX = zeros(1,nfeats); +out.muX = zeros(1,nfeats); +out.sigmaX = zeros(1,nfeats); +for i=1:nfeats + aux = X(:,i); + idx = isnan(aux); + [aux, out.lambdaX(i)] = boxcox(aux(~idx)); + [aux, out.muX(i), out.sigmaX(i)] = zscore(aux); + X(~idx,i) = aux; +end + +out.minY = min(Y(:)); +Y = (Y-out.minY)+eps; +out.lambdaY = zeros(1,nalgos); +out.muY = zeros(1,nalgos); +out.sigmaY = zeros(1,nalgos); +for i=1:nalgos + aux = Y(:,i); + idx = isnan(aux); + [aux, out.lambdaY(i)] = boxcox(aux(~idx)); + [aux, out.muY(i), out.sigmaY(i)] = zscore(aux); + Y(~idx,i) = aux; +end + +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/boundOutliers.m b/InstanceSpace-master/older_scripts/boundOutliers.m new file mode 100644 index 0000000..79bc864 --- /dev/null +++ b/InstanceSpace-master/older_scripts/boundOutliers.m @@ -0,0 +1,13 @@ +function [X, out] = boundOutliers(X) + +disp('-> Removing extreme outliers from the feature values.'); +out.medval = nanmedian(X, 1); +out.iqrange = iqr(X, 1); +out.hibound = out.medval + 5.*out.iqrange; +out.lobound = out.medval - 5.*out.iqrange; +himask = bsxfun(@gt,X,out.hibound); +lomask = bsxfun(@lt,X,out.lobound); +X = X.*~(himask | lomask) + bsxfun(@times,himask,out.hibound) + ... + bsxfun(@times,lomask,out.lobound); + +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/checkCorrelation.m b/InstanceSpace-master/older_scripts/checkCorrelation.m new file mode 100644 index 0000000..b4df979 --- /dev/null +++ b/InstanceSpace-master/older_scripts/checkCorrelation.m @@ -0,0 +1,29 @@ +function [X, out] = checkCorrelation(X,Y,opts) + +[~,nfeats] = size(X); +if nfeats>2 + disp('-> Checking for feature correlation with performance.'); + [out.rho,out.p] = corr(X,Y,'rows','pairwise'); + rho = out.rho; + rho(isnan(rho) | (out.p>0.05)) = 0; + [~,row] = sort(abs(rho),1,'descend'); + out.selvars = false(1,nfeats); + testTreshold = false; + while sum(out.selvars)<3 + if testTreshold + warning('Feature selection using correlation was too strict. The threshold value was increased automatically by one.') + end + out.selvars(unique(row(1:min(opts.threshold,nfeats),:))) = true; + opts.threshold = opts.threshold + 1; + testTreshold = true; + end + X = X(:,out.selvars); + disp(['-> Keeping ' num2str(size(X,2)) ' out of ' num2str(nfeats) ' features (correlation).']); +else + disp('-> There are less than 3 features to do selection (correlation). Skipping.') + out.p = ones(nfeats,size(Y,2)); + out.rho = NaN.*out.p; + out.selvars = true(1,nfeats); +end + +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/clusterFeatureSelection.m b/InstanceSpace-master/older_scripts/clusterFeatureSelection.m new file mode 100644 index 0000000..b70b1a5 --- /dev/null +++ b/InstanceSpace-master/older_scripts/clusterFeatureSelection.m @@ -0,0 +1,193 @@ +function [X, out] = clusterFeatureSelection(X, Ybin, opts) +% ------------------------------------------------------------------------- +% clusterFeatureSelection.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2019 +% +% ------------------------------------------------------------------------- + +global comb gacostvals + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +nfeats = size(X,2); +disp('-> Selecting features based on correlation clustering.'); +nalgos = size(Ybin,2); +Kmax = min(opts.KDEFAULT, nfeats); + +state = rng; +rng('default'); +out.eva = evalclusters(X', 'kmeans', 'Silhouette', 'KList', 3:Kmax, ... % minimum of three features + 'Distance', 'correlation'); +rng(state); +disp('-> Average silhouette values for each number of clusters.') +disp([3:Kmax; out.eva.CriterionValues]); + +if all(out.eva.CriterionValues Silhouette threshold is too high. Consider using a lower value.'); + disp('-> Using the maximum number of clusters possible.'); + K = Kmax; +elseif all(out.eva.CriterionValues>opts.SILTHRESHOLD) + disp('-> Silhouette threshold is too low. Consider using a higher value.'); + disp('-> Using the minimum number of clusters possible.'); + K = 3; +else + K = out.eva.InspectedK(find(out.eva.CriterionValues>opts.SILTHRESHOLD,1)); % If empty make an error that is more meaningfull +end + +state = rng; +rng('default'); +out.clust = bsxfun(@eq, kmeans(X', K, 'Distance', 'correlation', ... + 'MaxIter', opts.MaxIter, ... + 'Replicates', opts.Replicates, ... + 'Options', statset('UseParallel', nworkers~=0), ... + 'OnlinePhase', 'on'), 1:K); +rng(state); +disp(['-> Constructing ' num2str(K) ' clusters of features.']); +% --------------------------------------------------------------------- +% Using these out.clusters, determine all possible combinations that take one +% feature from each out.cluster. +strcmd = '['; +for i=1:K + strcmd = [strcmd 'X' num2str(i) ]; %#ok<*AGROW> + if i +comb = sort(comb,2); +disp(['-> ' num2str(ncomb) ' valid feature combinations.']); + +maxcomb = 1000; +% --------------------------------------------------------------------- +% Determine which combination produces the best separation while using a +% two dimensional PCA projection. The separation is defined by a Tree +% Bagger. +if ncomb>maxcomb + disp('-> There are over 1000 valid combinations. Using a GA+LookUpTable to find an optimal one.'); + gacostvals = NaN.*ones(ncomb,1); + % gacostvals = spalloc(1,bi2de(ones(1,nfeats)),ncomb); + fcnwrap = @(idx) fcnforga(idx,X,Ybin,opts.NTREES,out.clust); + gaopts = optimoptions('ga','FitnessLimit',0,'FunctionTolerance',1e-3,... + 'MaxGenerations',100,'MaxStallGenerations',5,... + 'PopulationSize',50); % This sets the maximum to 1000 combinations + ind = ga(fcnwrap,K,[],[],[],[],ones(1,K),sum(out.clust),[],1:K,gaopts); + out.selvars = false(1,size(X,2)); % Decode the chromosome + for i=1:K + aux = find(out.clust(:,i)); + out.selvars(aux(ind(i))) = true; + end + out.selvars = find(out.selvars); +elseif ncomb==1 + disp('-> There is one valid combination. It will be considered the optimal one.'); + out.selvars = 1:nfeats; +else + disp('-> There are less than 1000 valid combinations. Using brute-force to find an optimal one.'); + out.ooberr = zeros(ncomb,nalgos); + for i=1:ncomb + tic; + out.ooberr(i,:) = costfcn(comb(i,:),X,Ybin,opts.NTREES); + etime = toc; + disp([' -> Combination No. ' num2str(i) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... + 's | Average error : ' num2str(mean(out.ooberr(i,:)))]); + tic; + end + [~,best] = min(sum(out.ooberr,2)); + out.selvars = sort(comb(best,:)); +end +X = X(:,out.selvars); +disp(['-> Keeping ' num2str(size(X, 2)) ' out of ' num2str(nfeats) ' features (clustering).']); + +end +% ========================================================================= +function ooberr = costfcn(comb,X,Ybin,ntrees) + +if exist('gcp','file')==2 + mypool = gcp('nocreate'); + if ~isempty(mypool) + nworkers = mypool.NumWorkers; + else + nworkers = 0; + end +else + nworkers = 0; +end + +[~, score] = pca(X(:,comb), 'NumComponents', 2); %#ok<*IDISVAR> % Reduce using PCA +nalgos = size(Ybin,2); +ooberr = zeros(1,nalgos); +for j = 1:nalgos + state = rng; + rng('default'); + tree = TreeBagger(ntrees, score, Ybin(:,j), 'OOBPrediction', 'on', ... + 'Options', statset('UseParallel', nworkers~=0)); + ooberr(j) = mean(Ybin(:,j)~=str2double(oobPredict(tree))); + rng(state); +end + +end +% ========================================================================= +function sumerr = fcnforga(idx,X,Ybin,ntrees,clust) +global gacostvals comb + +tic; +% Decode the chromosome into a binary string representing the selected +% features +ccomb = false(1,size(X,2)); +for i=1:length(idx) + aux = find(clust(:,i)); + ccomb(aux(idx(i))) = true; +end +% Calculate the cost function. Use the lookup table to reduce the amount of +% computation. +ind = find(all(comb==find(ccomb),2)); +if isnan(gacostvals(ind)) + ooberr = costfcn(ccomb,X,Ybin,ntrees); + sumerr = sum(ooberr); + gacostvals(ind) = sumerr; +else + sumerr = gacostvals(ind); +end + +etime = toc; +disp([' -> Combination No. ' num2str(ind) ' | Elapsed Time: ' num2str(etime,'%.2f\n') ... + 's | Average error : ' num2str(sumerr./size(Ybin,2))]); + +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/example_ksm.m b/InstanceSpace-master/older_scripts/example_ksm.m new file mode 100644 index 0000000..64516c8 --- /dev/null +++ b/InstanceSpace-master/older_scripts/example_ksm.m @@ -0,0 +1,59 @@ +rootdir = './trial_ksm/'; + +opts.parallel.flag = false; +opts.parallel.ncores = 2; + +opts.perf.MaxPerf = true; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. +opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure +opts.perf.epsilon = 0.05; % Threshold of good performance +opts.perf.betaThreshold = 0.55; % Beta-easy threshold +opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing +opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) + +opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances +opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment +% You can also provide a file with the indexes of the instances to be used. +% This should be a csvfile with a single column of integer numbers that +% should be lower than the number of instances +opts.selvars.fileidxflag = false; +opts.selvars.fileidx = ''; +opts.selvars.densityflag = false; +opts.selvars.mindistance = 0.1; + +opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. +opts.sifted.rho = 0.1; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 +opts.sifted.K = 10; % Number of final features. Ideally less than 10. +opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) +opts.sifted.MaxIter = 1000; +opts.sifted.Replicates = 100; + +opts.pilot.analytic = false; % Calculate the analytical or numerical solution +opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +opts.pythia.cvfolds = 5; +opts.pythia.ispolykrnl = false; +opts.pythia.useweights = false; +opts.pythia.uselibsvm = true; + +opts.trace.usesim = false; % Use the actual or simulated data to calculate the footprints +opts.trace.PI = 0.55; % Purity threshold + +opts.outputs.csv = true; % +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 +opts.outputs.png = true; % + +% Saving all the information as a JSON file +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = buildIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end diff --git a/InstanceSpace-master/older_scripts/example_maxflow2.m b/InstanceSpace-master/older_scripts/example_maxflow2.m new file mode 100644 index 0000000..36e50ce --- /dev/null +++ b/InstanceSpace-master/older_scripts/example_maxflow2.m @@ -0,0 +1,66 @@ +rootdir = './trial_maxflow2/'; + +opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. +opts.perf.AbsPerf = false; % True if an absolute performance measure, False if a relative performance measure +opts.perf.epsilon = 0.05; % Threshold of good performance + +opts.perf.betaThreshold = 0.55; % Beta-easy threshold + +opts.parallel.flag = true; +opts.parallel.ncores = 6; + +opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing +opts.bound.flag = true; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) + +opts.sifted.flag = true; % Run feature selection by correlation between performance and features (Step 2) +opts.sifted.rho = 0.3; +opts.sifted.K = 7; % Default maximum number of clusters +opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) +opts.sifted.MaxIter = 1000; +opts.sifted.Replicates = 100; + +opts.pilot.analytic = false; % Calculate the analytical or numerical solution +opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +opts.pythia.cvfolds = 5; +opts.pythia.ispolykrnl = true; +opts.pythia.useweights = false; +opts.pythia.uselibsvm = true; + +opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints +opts.trace.PI = 0.55; % Purity threshold + +opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances +opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment +% You can also provide a file with the indexes of the instances to be used. +% This should be a csvfile with a single column of integer numbers that +% should be lower than the number of instances +opts.selvars.fileidxflag = false; +opts.selvars.fileidx = ''; + +opts.selvars.densityflag = false; +opts.selvars.mindistance = 0.1; + +opts.outputs.csv = true; % +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 +opts.outputs.png = true; % + +% Saving all the information as a JSON file +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = buildIS(rootdir); + %The trained model can be tested using testing routine + %"testInterface.m". Make sure to place test data "metadata_test.csv" + %inside root directory specified at the top (rootdir). +% model = testIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/generate_evco2data.m b/InstanceSpace-master/older_scripts/generate_evco2data.m new file mode 100644 index 0000000..f894d03 --- /dev/null +++ b/InstanceSpace-master/older_scripts/generate_evco2data.m @@ -0,0 +1,100 @@ +rootdir = '../InstanceGeneration_BlackBoxOptimisation/'; +datafile = [rootdir 'metadata.csv']; +Xbar = readtable(datafile); +varlabels = Xbar.Properties.VariableNames; +isname = strcmpi(varlabels,'instances'); +isfeat = strncmpi(varlabels,'feature_',8); +isalgo = strncmpi(varlabels,'algo_',5); +issource = strcmpi(varlabels,'source'); +model.data.instlabels = Xbar{:,isname}; +if isnumeric(model.data.instlabels) + model.data.instlabels = num2cell(model.data.instlabels); + model.data.instlabels = cellfun(@(x) num2str(x),model.data.instlabels,'UniformOutput',false); +end +if any(issource) + model.data.S = categorical(Xbar{:,issource}); +end +model.data.featlabels = varlabels(isfeat); +model.data.algolabels = varlabels(isalgo); + +model.data.X = Xbar{:,isfeat}; +model.data.Y = Xbar{:,isalgo}; +model.data.featlabels = strrep(model.data.featlabels,'feature_',''); +model.data.algolabels = strrep(model.data.algolabels,'algo_',''); +Yaux = model.data.Y; +[rankPerf,rankAlgo] = sort(Yaux,2,'ascend'); +model.data.Ybest = rankPerf(:,1); +model.data.P = rankAlgo(:,1); +model.data.Ybin = double(~isinf(Yaux)); +model.data.Ybin(isnan(Yaux)) = NaN; +model.data.numGoodAlgos = sum(model.data.Ybin,2); + +model.pilot.A = [-0.284540475 0.209907328 -0.31958864 -0.463890898 -0.300949587 0.029790169 0.531014437 -0.429196374; + 0.610380182 0.162667986 -0.029267638 0.267385554 -0.438894233 0.533654711 0.017718121 -0.22559721]; + +model.pilot.summary = cell(3, size(model.pilot.A,2)+1); +model.pilot.summary(1,2:end) = model.data.featlabels; +model.pilot.summary(2:end,1) = {'Z_{1}','Z_{2}'}; +model.pilot.summary(2:end,2:end) = num2cell(round(model.pilot.A,4)); + +model.pilot.Z = model.data.X*model.pilot.A'; + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +model.cloist = CLOISTER(model.data.X, model.pilot.A, opts.cloister); + +scriptfcn; +writeArray2CSV(model.pilot.Z, {'z_1','z_2'}, ... + model.data.instlabels, ... + [rootdir 'coordinates.csv']); +if isfield(model,'cloist') + writeArray2CSV(model.cloist.Zedge, {'z_1','z_2'}, ... + makeBndLabels(model.cloist.Zedge), ... + [rootdir 'bounds.csv']); + writeArray2CSV(model.cloist.Zecorr, {'z_1','z_2'}, ... + makeBndLabels(model.cloist.Zecorr), ... + [rootdir 'bounds_prunned.csv']); +end +writeArray2CSV(model.data.X, ... + model.data.featlabels, ... + model.data.instlabels, ... + [rootdir 'feature_process.csv']); +writeArray2CSV(model.data.Y, ... + model.data.algolabels, ... + model.data.instlabels, ... + [rootdir 'algorithm_process.csv']); +writeArray2CSV(model.data.Ybin, ... + model.data.algolabels, ... + model.data.instlabels, ... + [rootdir 'algorithm_bin.csv']); +writeArray2CSV(model.data.numGoodAlgos, {'NumGoodAlgos'}, ... + model.data.instlabels, ... + [rootdir 'good_algos.csv']); +writeArray2CSV(model.data.P, {'Best_Algorithm'}, ... + model.data.instlabels, ... + [rootdir 'portfolio.csv']); +writeCell2CSV(model.pilot.summary(2:end,2:end), ... + model.pilot.summary(1,2:end),... + model.pilot.summary(2:end,1), ... + [rootdir 'projection_matrix.csv']); + +writetable(array2table(uint8(255.*parula(256)), ... + 'VariableNames', {'R','G','B'}), ... + [rootdir 'color_table.csv']); +writeArray2CSV(colorscale(model.data.X), ... + model.data.featlabels, ... + model.data.instlabels, ... + [rootdir 'feature_process_color.csv']); +writeArray2CSV(colorscale(model.data.Y), ... + model.data.algolabels, ... + model.data.instlabels, ... + [rootdir 'algorithm_process_single_color.csv']); +writeArray2CSV(colorscaleg(model.data.Y), ... + model.data.algolabels, ... + model.data.instlabels, ... + [rootdir 'algorithm_process_color.csv']); +writeArray2CSV(colorscaleg(model.data.numGoodAlgos), ... + {'NumGoodAlgos'}, ... + model.data.instlabels, ... + [rootdir 'good_algos_color.csv']); diff --git a/InstanceSpace-master/older_scripts/instancesProjectionInterfaceWeb.m b/InstanceSpace-master/older_scripts/instancesProjectionInterfaceWeb.m new file mode 100644 index 0000000..5ccc467 --- /dev/null +++ b/InstanceSpace-master/older_scripts/instancesProjectionInterfaceWeb.m @@ -0,0 +1,8 @@ +function instancesProjectionInterfaceWeb(rootdir) + try + testIS(rootdir); + catch ME + disp('EOF:ERROR'); + rethrow(ME) + end +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/purifyInst.m b/InstanceSpace-master/older_scripts/purifyInst.m new file mode 100644 index 0000000..5afcfe5 --- /dev/null +++ b/InstanceSpace-master/older_scripts/purifyInst.m @@ -0,0 +1,157 @@ +function purifyInst(Net, epsilon, flag) +%% Description +% This script purifies benchmarks problems based on the similarity among them. +% The similarity of two benchmark problems is defined as the Euclidian +% distnace between their features. +% This script regards the similarity of tow benchmarks based on the +% similarity of the algorithm performances (APs) on them too; the simiarity of +% APs can be calculated as th Euclidian distance among the APs or as the +% similarity of their goodness in saolving the similar benchmarks. +% If two benchmarks are similar, then it checks the similarity among +% algorithm performances on these benchmarks. + +% The arguments of this function are: +% Net: is the name of metadata file including the instances and their features +% and APs. +% epsilon: determines the treshhold of the similarity. +% flag: determines which similarity approach must be applied as follows; +% ========================================================================= +% 'Ftr': similarity just based on the features +% 'Ftr&AP': both features and APs with Euclidian distance +% 'Ftr&Good': features with Euclidian distnace and APs based on the goodness +% 'Ftr&AP&Good': features with Euclidian dustance and APs +% with both Euclidian distance and goodness criterion +% ========================================================================= +% In the cases of goodness criterion, we must define a differen threshold +% for the goddness of APs. This is ture about the +% second case too, but since the number of APs are less than the number of +% features, they are purified with different thresholds simlicitly; + +% ========================================================================= +% Code by: Hossein Alipour +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% Email: h.alipour@unimelb.edu.au + +% Copyright: Hossein Alipour +% + +%% Main loop + +for k = 1:length(epsilon) + + Xbar = readtable(sprintf('%s.csv',Net)); + + varlabels = Xbar.Properties.VariableNames; + isfeat = strncmpi(varlabels,'feature_',8); + isalgo = strncmpi(varlabels,'algo_',5); + numFtr = sum(isfeat); + numAlgo = sum(isalgo); + X = Xbar{:,isfeat}; + Y = Xbar{:,isalgo}; + + toPreclude = false((size(X,1)),1); + ViSA_idx = false((size(X,1)),1); + Dissimilar_idx = true((size(X,1)),1); + Tprcl = 0; % counter of the precluded instances + + + ViSA_D = 0; % A counter of the violation from Euclidian distance for APs + ViSA_Good = 0; % A counter of the violation from the goodness criterion for APs + + + + %% The main nested loop to preclude the similar instances according to a + % given tolearnce epsilon, preferably from the interval (0, 1). + Dissimilar_idx(1) = true; + + for i=1:size(X,1) + if (~toPreclude(i)) + for j=i+1:size(X,1) + if (~toPreclude(j)) + dist = sqrt(sum((X(i,:) - X(j,:)) .^ 2)); % Euclidean distance + if (dist <= epsilon(k)) + Dissimilar_idx(j) = false; + switch flag + case 'Ftr' + toPreclude(j) = true; + case 'Ftr&AP' + dist_AP = sqrt(sum((Y(i,:) - Y(j,:)) .^ 2)); +% if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)*(1+0.26)) % 0.26 is the value of CPUN (CPU Noise) + if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)) + toPreclude(j) = true; + ViSA_idx(j) = false; + else + ViSA_idx(j) = true; + end + case 'Ftr&Good' + if (Ybin(i,:) == Ybin(j,:)) + toPreclude(j) = true; + ViSA_idx(j) = false; + else + ViSA_idx(j) = true; + end + case 'Ftr&AP&Good' + if (Ybin(i,:) == Ybin(j,:)) + dist_AP = sqrt(sum((Y(i,:) - Y(j,:)) .^ 2)); +% if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)*(1+0.26)) % epsilon could be different from that given in the function. + if (dist_AP <= sqrt(numAlgo/numFtr)*epsilon(k)) + toPreclude(j) = true; + ViSA_idx(j) = false; + else + ViSA_idx(j) = true; + end + else + ViSA_idx(j) = true; + end + otherwise + disp('Invalid flag!') + end + end + end + end + end + end + + % Xbar = sortrows(Xbar); % This command is useful if you want to apply a random purification. + + PurifiedInst = Xbar; + PrecludedInst = Xbar; + DissimilarPurInst = Xbar; + ViSAPurInst = Xbar; + + PurifiedInst(toPreclude,:) = []; + PrecludedInst(~toPreclude,:) = []; + DissimilarPurInst(~Dissimilar_idx,:) = []; + ViSAPurInst(~ViSA_idx,:) = []; + + switch flag + case 'Ftr' + writetable(PurifiedInst,sprintf('Pur_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); + writetable(PrecludedInst,sprintf('Prec_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); + case 'Ftr&AP' + writetable(PurifiedInst,sprintf('Pur_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); + writetable(PrecludedInst,sprintf('Prec_%s_%s_Dist_%.3f.csv',flag, Net, epsilon(k))); + case 'Ftr&Good' + writetable(PurifiedInst,sprintf('Pur_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(PrecludedInst,sprintf('Prec_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(DissimilarPurInst,sprintf('Dissimilar_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(ViSAPurInst,sprintf('ViSA_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + case 'Ftr&AP&Good' + writetable(PurifiedInst,sprintf('Pur_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(PrecludedInst,sprintf('Prec_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(DissimilarPurInst,sprintf('Dissimilar_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + writetable(ViSAPurInst,sprintf('ViSA_%s_%s_G_%.2f_Dist_%.3f.csv',flag, Net, opts.perf.epsilon, epsilon(k))); + end + + %% + clear Xbar; + clear X; + clear Y; + clear Ybin; + clear toPreclude; + fclose('all'); +end + diff --git a/InstanceSpace-master/older_scripts/run_bifel.m b/InstanceSpace-master/older_scripts/run_bifel.m new file mode 100644 index 0000000..7d84619 --- /dev/null +++ b/InstanceSpace-master/older_scripts/run_bifel.m @@ -0,0 +1,59 @@ +rootdir = './trial_bifidel/'; + +opts.parallel.flag = false; +opts.parallel.ncores = 2; + +opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. +opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure +opts.perf.epsilon = 0.05; % Threshold of good performance +opts.perf.betaThreshold = 0.55; % Beta-easy threshold +opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing +opts.bound.flag = false; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) + +opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances +opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment +% You can also provide a file with the indexes of the instances to be used. +% This should be a csvfile with a single column of integer numbers that +% should be lower than the number of instances +opts.selvars.fileidxflag = false; +opts.selvars.fileidx = ''; +opts.selvars.densityflag = false; +opts.selvars.mindistance = 0.1; + +opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. +opts.sifted.rho = 0.0; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 +opts.sifted.K = 10; % Number of final features. Ideally less than 10. +opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) +opts.sifted.MaxIter = 1000; +opts.sifted.Replicates = 100; + +opts.pilot.analytic = false; % Calculate the analytical or numerical solution +opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +opts.pythia.cvfolds = 10; +opts.pythia.ispolykrnl = false; +opts.pythia.useweights = false; +opts.pythia.uselibsvm = true; + +opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints +opts.trace.PI = 0.55; % Purity threshold + +opts.outputs.csv = true; % +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 +opts.outputs.png = true; % + +% Saving all the information as a JSON file +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = buildIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/run_bifel[2305843009224844497].m b/InstanceSpace-master/older_scripts/run_bifel[2305843009224844497].m new file mode 100644 index 0000000..7d84619 --- /dev/null +++ b/InstanceSpace-master/older_scripts/run_bifel[2305843009224844497].m @@ -0,0 +1,59 @@ +rootdir = './trial_bifidel/'; + +opts.parallel.flag = false; +opts.parallel.ncores = 2; + +opts.perf.MaxPerf = false; % True if Y is a performance measure to maximize, False if it is a cost measure to minimise. +opts.perf.AbsPerf = true; % True if an absolute performance measure, False if a relative performance measure +opts.perf.epsilon = 0.05; % Threshold of good performance +opts.perf.betaThreshold = 0.55; % Beta-easy threshold +opts.auto.preproc = true; % Automatic preprocessing on. Set to false if you don't want any preprocessing +opts.bound.flag = false; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) + +opts.selvars.smallscaleflag = false; % True if you want to do a small scale experiment with a percentage of the available instances +opts.selvars.smallscale = 0.50; % Percentage of instances to be kept for a small scale experiment +% You can also provide a file with the indexes of the instances to be used. +% This should be a csvfile with a single column of integer numbers that +% should be lower than the number of instances +opts.selvars.fileidxflag = false; +opts.selvars.fileidx = ''; +opts.selvars.densityflag = false; +opts.selvars.mindistance = 0.1; + +opts.sifted.flag = true; % Automatic feature selectio on. Set to false if you don't want any feature selection. +opts.sifted.rho = 0.0; % Minimum correlation value acceptable between performance and a feature. Between 0 and 1 +opts.sifted.K = 10; % Number of final features. Ideally less than 10. +opts.sifted.NTREES = 50; % Number of trees for the Random Forest (to determine highest separability in the 2-d projection) +opts.sifted.MaxIter = 1000; +opts.sifted.Replicates = 100; + +opts.pilot.analytic = false; % Calculate the analytical or numerical solution +opts.pilot.ntries = 30; % Number of attempts carried out by PBLDR + +opts.cloister.pval = 0.05; +opts.cloister.cthres = 0.7; + +opts.pythia.cvfolds = 10; +opts.pythia.ispolykrnl = false; +opts.pythia.useweights = false; +opts.pythia.uselibsvm = true; + +opts.trace.usesim = true; % Use the actual or simulated data to calculate the footprints +opts.trace.PI = 0.55; % Purity threshold + +opts.outputs.csv = true; % +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 +opts.outputs.png = true; % + +% Saving all the information as a JSON file +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = buildIS(rootdir); +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end \ No newline at end of file diff --git a/InstanceSpace-master/older_scripts/run_regression.m b/InstanceSpace-master/older_scripts/run_regression.m new file mode 100644 index 0000000..474effb --- /dev/null +++ b/InstanceSpace-master/older_scripts/run_regression.m @@ -0,0 +1,61 @@ +rootdir = 'C:/Users/mariom1/OneDrive - The University of Melbourne/Documents/MATLAB/InstanceSpace_Regression/trial/'; + +optsfile = [rootdir 'options_bkup.json']; +opts = jsondecode(fileread(optsfile)); +opts.auto.featsel = false; +opts.corr.flag = true; +opts.corr.threshold = 5; +opts.clust.flag = false; + +opts.pilot = opts.pbldr; +opts.pilot.ntries = 30; +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]; +opts.cloister = opts.sbound; +opts.pythia = opts.oracle; +opts.pythia.useweights = false; +opts.trace = opts.footprint; +opts.trace.PI = 0.65; + +opts.selvars.fileidxflag = true; +opts.selvars.fileidx = [rootdir 'indexes.csv']; +opts.selvars.algos = {'algo_grad_boost'; + 'algo_bayesian_ARD'; + 'algo_bagging'; + 'algo_random_forest'; + 'algo_nu_svr'; + 'algo_linear_svr'; + 'algo_adaboost'; + 'algo_decision_tree'}; + +opts.selvars.feats = {'feature_n1'; + 'feature_c2'; + 'feature_c5'; + 'feature_l1_a'; + 'feature_m5'; + 'feature_s1'; + 'feature_t2'}; + +fid = fopen([rootdir 'options.json'],'w+'); +fprintf(fid,'%s',jsonencode(opts)); +fclose(fid); + +try + model = trainIS(rootdir); + PI=0:0.05:0.95; + nalgos = length(model.data.algolabels); + summaryExp = zeros(nalgos,10,length(PI)); + summarySim = zeros(nalgos,10,length(PI)); + for i=1:length(PI) + opts.trace.PI = PI(i); + model.trace.exper{i} = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); + model.trace.simul{i} = TRACE(model.pilot.Z, model.pythia.Yhat, model.pythia.selection0, model.data.beta, model.data.algolabels, opts.trace); + summaryExp(:,:,i) = cell2mat(model.trace.exper{i}.summary(2:end,2:end)); + summarySim(:,:,i) = cell2mat(model.trace.simul{i}.summary(2:end,2:end)); + end + summary{1} = [PI' squeeze(mean(summaryExp(:,[2 4 5 7 9 10],:),1))']; + summary{2} = [PI' squeeze(mean(summarySim(:,[2 4 5 7 9 10],:),1))']; +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end + diff --git a/InstanceSpace-master/older_scripts/run_timetable.m b/InstanceSpace-master/older_scripts/run_timetable.m new file mode 100644 index 0000000..ed623a3 --- /dev/null +++ b/InstanceSpace-master/older_scripts/run_timetable.m @@ -0,0 +1,122 @@ +% ------ Rephrasing the Timetable data +rdir = '../../InstanceSpace_Timetabling/'; +load([rdir 'workspace.mat']); +% Loading the options +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. +model.opts.perf.AbsPerf = opts.perf.AbsPerf; % True if an absolute performance measure, False if a relative performance measure +model.opts.perf.epsilon = opts.perf.epsilon; % Threshold of good performance + +model.opts.general = opts.general; % Beta-easy threshold +model.opts.auto = opts.auto; % Automatic preprocessing on. Set to false if you don't want any preprocessing +model.opts.bound = opts.bound; % Bound the outliers. True if you want to bound the outliers, false if you don't +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) +model.opts.corr = opts.corr; +model.opts.clust = opts.clust; + +model.opts.pilot = opts.pbldr; % Calculate the analytical or numerical solution +model.opts.pythia.cvfolds = opts.oracle.cvfolds; +model.opts.pythia.useweights = false; +model.opts.pythia.uselibsvm = true; +model.opts.pythia.params = out.algosel.paramgrid(out.algosel.paramidx,:); + +model.opts.cloister.pval = 0.05; +model.opts.cloister.cthres = 0.7; + +model.opts.trace.usesim = false; % Use the actual or simulated data to calculate the footprints +model.opts.trace.PI = 0.55; % Purity threshold + +model.opts.selvars = opts.selvars; + +model.opts.outputs.csv = true; % +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 +model.opts.outputs.png = true; + +[model.clust.selvars,idx] = sort(out.clust.selvars); + +model.data.X = X(:,idx); +model.data.Y = Y; +model.data.Xraw = Xraw; +model.data.Yraw = Yraw; +model.data.Ybin = Ybin; +model.data.S = S; +model.data.beta = beta; +model.data.bestPerformace = bestPerformace; +model.data.P = portfolio; +model.data.featlabels = featlabels(:,idx); +model.data.algolabels = algolabels; +model.data.instlabels = instlabels; +model.data.numGoodAlgos = sum(model.data.Ybin,2); + +model.pilot = out.pbldr; +model.bound = out.bound; +model.norm = out.norm; +model.corr = out.corr; +model.clust = out.clust; + +% Have to figure out a way to reconstruct the alpha and X0 values +model.pilot.A = model.pilot.A(:,idx); +model.pilot.B = model.pilot.B(idx,:); + +aux = [model.pilot.A(:); model.pilot.B(:); model.pilot.C(:)]; +alpha = 0.*model.pilot.alpha; +X0 = alpha; +for i=1:length(alpha) + [row,col] = find(model.pilot.alpha == aux(i)); + alpha(i,:) = model.pilot.alpha(row,:); + X0(i,:) = model.pilot.X0(row,:); +end +model.pilot.alpha = alpha; +model.pilot.X0 = X0; + +auxclust = false(1,7); +auxclust(out.clust.selvars) = true; +aux = false(1,11); +aux(out.corr.selvars) = auxclust; + +model.featsel.idx = aux; + +save([rdir 'model.mat'],'-struct','model'); % Save the main results + +%% +clearvars; +rdir = '../../InstanceSpace_Timetabling/'; +model = load([rdir 'model.mat']); + +% opts = model.opts; +% model.pilot.summary = cell(3, length(model.data.featlabels)+1); +% model.pilot.summary(1,2:end) = model.data.featlabels; +% model.pilot.summary(2:end,1) = {'Z_{1}','Z_{2}'}; +% model.pilot.summary(2:end,2:end) = num2cell(round(model.pilot.A,4)); +% model.cloist = CLOISTER(model.data.X, model.pilot.A, opts.cloister); +% model.pythia = PYTHIA(model.pilot.Z, model.data.Yraw, model.data.Ybin, model.data.bestPerformace, model.data.algolabels, opts.pythia); +% model.trace = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); +% save([rdir 'model.mat'],'-struct','model'); % Save the main results +% scriptcsv(model,rdir); +scriptpng(model,rdir); +h = drawSources(model.pilot.Z, model.data.S); +nsources = length(h); +h(nsources+1) = line(model.cloist.Zedge(:,1),model.cloist.Zedge(:,2), 'Color', [0.49 0.18 0.56]); +sourcelabels = cellstr(unique(model.data.S)); +sourcelabels{nsources+1} = 'estimated bound'; +legend(h, sourcelabels, 'Location', 'NorthEastOutside'); +axis square; axis([-10 10 -12 12]); +print(gcf,'-dpng',[rdir 'distribution_sources.png']); + +%% +clearvars; +rdir = 'C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Timetabling\'; +model = load([rdir 'model.mat']); +PI=0:0.05:0.95; +nalgos = length(model.data.algolabels); +summaryExp = zeros(nalgos,10,length(PI)); +summarySim = zeros(nalgos,10,length(PI)); +for i=1:length(PI) + opts.trace.PI = PI(i); + model.trace.exp{i} = TRACE(model.pilot.Z, model.data.Ybin, model.data.P, model.data.beta, model.data.algolabels, opts.trace); + model.trace.sim{i} = TRACE(model.pilot.Z, model.pythia.Yhat, model.pythia.selection0, model.data.beta, model.data.algolabels, opts.trace); + summaryExp(:,:,i) = cell2mat(model.trace.exp{i}.summary(2:end,2:end)); + summarySim(:,:,i) = cell2mat(model.trace.sim{i}.summary(2:end,2:end)); +end +summary{1} = [PI' squeeze(mean(summaryExp(:,[2 4 5 7 9 10],:),1))']; +summary{2} = [PI' squeeze(mean(summarySim(:,[2 4 5 7 9 10],:),1))']; + diff --git a/InstanceSpace-master/older_scripts/unigoodreg.m b/InstanceSpace-master/older_scripts/unigoodreg.m new file mode 100644 index 0000000..417eaf2 --- /dev/null +++ b/InstanceSpace-master/older_scripts/unigoodreg.m @@ -0,0 +1,45 @@ +% probgood = mean(model.data.Ybin,1)'; +% [pgoodsort,idx] = sort(probgood,'descend'); +% model.data.algolabels(idx(pgoodsort>0.1))'; +% +% puniquegood = mean(model.data.Ybin & (sum(model.data.Ybin,2)<=1))'; +% [puniquegoodsort,idx] = sort(puniquegood,'descend'); +% model.data.algolabels(idx(puniquegoodsort>0.01))'; +% +% +% numgoodalgos = sum(model.data.Ybin,2); +% percgoodalgos = mean(bsxfun(@eq,numgoodalgos,1:nalgos)); +% +% +% +% +% model = load('C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Regression\trial\results_r1_main_paper_results\model.mat'); +% scriptfcn; +clf; +h = drawSources(model.pilot.Z,model.data.S); +line([0 0],[-100 100],'LineStyle', '--', 'color', [0.6 0.6 0.6]); +line([-100 100],[0 0],'LineStyle', '--', 'color', [0.6 0.6 0.6]); +text(3.5, 3,'Q1'); +text(-4, 3,'Q2'); +text(3.5,-3,'Q4'); +text(-4,-3,'Q3'); +legend(h, {'BlackBoxData','EvolvedBlackBox','M3C','Repositories'}) +% print(gcf,'-dpng',[rootdir 'distribution_sources_quadrants.png']); +% +% + +rootdir = 'C:\Users\mariom1\OneDrive - The University of Melbourne\Documents\MATLAB\InstanceSpace_Regression\trial\results_r1_main_paper_results\'; +h = zeros(1,3); +for ii=1:length(model.data.algolabels) + clf; + alpha = 0.4; + blue = [0.0 0.0 1.0]; + h(1:2) = drawBinaryPerformance(model.pilot.Z, model.data.Ybin(:,ii), ... + strrep(model.data.algolabels{ii},'_',' ')); + h(3) = drawFootprint(model.trace.good{ii}, blue, alpha); + legend(h,{'GOOD','BAD','FTPRN'}); + print(gcf,'-dpng',[rootdir 'footprint_' model.data.algolabels{ii} '.png']); +end + + +ii = 3; clf; drawBinaryPerformance(model.pilot.Z, presult.Yhat(:,ii), strrep(model.data.algolabels{ii},'_',' ')); \ No newline at end of file diff --git a/InstanceSpace-master/scriptcsv.m b/InstanceSpace-master/scriptcsv.m new file mode 100644 index 0000000..c4d8ff5 --- /dev/null +++ b/InstanceSpace-master/scriptcsv.m @@ -0,0 +1,102 @@ +function scriptcsv(container,rootdir) +% ------------------------------------------------------------------------- +% csvscript.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +scriptfcn; + +nalgos = size(container.data.Y,2); +disp('========================================================================='); +disp('-> Writing the data on CSV files for posterior analysis.'); +% ------------------------------------------------------------------------- +for i=1:nalgos + if isfield(container.trace.best{i},'polygon') && ~isempty(container.trace.best{i}.polygon) + writeArray2CSV(container.trace.best{i}.polygon.Vertices, ... + {'z_1','z_2'},... + makeBndLabels(container.trace.best{i}.polygon.Vertices),... + [rootdir 'footprint_' container.data.algolabels{i} '_best.csv']); + end + if isfield(container.trace.good{i},'polygon') && ~isempty(container.trace.good{i}.polygon) + writeArray2CSV(container.trace.good{i}.polygon.Vertices, ... + {'z_1','z_2'},... + makeBndLabels(container.trace.good{i}.polygon.Vertices),... + [rootdir 'footprint_' container.data.algolabels{i} '_good.csv']); + end +% if isfield(container.trace.bad{i},'polygon') && ~isempty(container.trace.bad{i}.polygon) +% writeArray2CSV(container.trace.bad{i}.polygon.Vertices, ... +% {'z_1','z_2'},... +% makeBndLabels(container.trace.bad{i}.polygon.Vertices),... +% [rootdir 'footprint_' container.data.algolabels{i} '_bad.csv']); +% end +end + +writeArray2CSV(container.pilot.Z, {'z_1','z_2'}, ... + container.data.instlabels, ... + [rootdir 'coordinates.csv']); +if isfield(container,'cloist') + writeArray2CSV(container.cloist.Zedge, {'z_1','z_2'}, ... + makeBndLabels(container.cloist.Zedge), ... + [rootdir 'bounds.csv']); + writeArray2CSV(container.cloist.Zecorr, {'z_1','z_2'}, ... + makeBndLabels(container.cloist.Zecorr), ... + [rootdir 'bounds_prunned.csv']); +end +writeArray2CSV(container.data.Xraw(:, container.featsel.idx), ... + container.data.featlabels, ... + container.data.instlabels, ... + [rootdir 'feature_raw.csv']); +writeArray2CSV(container.data.X, ... + container.data.featlabels, ... + container.data.instlabels, ... + [rootdir 'feature_process.csv']); +writeArray2CSV(container.data.Yraw, ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_raw.csv']); +writeArray2CSV(container.data.Y, ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_process.csv']); +writeArray2CSV(container.data.Ybin, ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_bin.csv']); +writeArray2CSV(container.data.numGoodAlgos, {'NumGoodAlgos'}, ... + container.data.instlabels, ... + [rootdir 'good_algos.csv']); +writeArray2CSV(container.data.beta, {'IsBetaEasy'}, ... + container.data.instlabels, ... + [rootdir 'beta_easy.csv']); +writeArray2CSV(container.data.P, {'Best_Algorithm'}, ... + container.data.instlabels, ... + [rootdir 'portfolio.csv']); +writeArray2CSV(container.pythia.Yhat, ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_svm.csv']); +writeArray2CSV(container.pythia.selection0, ... + {'Best_Algorithm'}, ... + container.data.instlabels, ... + [rootdir 'portfolio_svm.csv']); +writeCell2CSV(container.trace.summary(2:end,[3 5 6 8 10 11]), ... + container.trace.summary(1,[3 5 6 8 10 11]),... + container.trace.summary(2:end,1),... + [rootdir 'footprint_performance.csv']); +if isfield(container.pilot,'summary') + writeCell2CSV(container.pilot.summary(2:end,2:end), ... + container.pilot.summary(1,2:end),... + container.pilot.summary(2:end,1), ... + [rootdir 'projection_matrix.csv']); +end +writeCell2CSV(container.pythia.summary(2:end,2:end), ... + container.pythia.summary(1,2:end), ... + container.pythia.summary(2:end,1), ... + [rootdir 'svm_table.csv']); diff --git a/InstanceSpace-master/scriptdisc.m b/InstanceSpace-master/scriptdisc.m new file mode 100644 index 0000000..da0de8c --- /dev/null +++ b/InstanceSpace-master/scriptdisc.m @@ -0,0 +1,58 @@ +function scriptdisc(filename) +% ------------------------------------------------------------------------- +% scriptdisc.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +disp('-------------------------------------------------------------------------'); +disp(' '); +disp([' ''' filename ''' ']); +disp(' '); +disp(' Code by: Mario Andres Muñoz Acosta'); +disp(' School of Mathematics and Statistics'); +disp(' The University of Melbourne'); +disp(' Australia'); +disp(' 2019'); +disp(' '); +disp(' Copyright: Mario A. Muñoz'); +disp(' '); +disp('-------------------------------------------------------------------------'); +disp(' '); +disp(' If using this software, please cite as: '); +disp(' '); +disp([' Mario Andrés Muñoz, & Kate Smith-Miles. ' ... + ' andremun/InstanceSpace: February 2021 Update (Version v0.2-beta). '... + ' Zenodo. http://doi.org/10.5281/zenodo.4521336']); +disp(' '); +disp('-------------------------------------------------------------------------'); +disp(' '); +disp(' DISCLAIMER:'); +disp(' '); +disp(' THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'); +disp(' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT'); +disp(' HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY'); +disp(' OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,'); +disp(' THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR'); +disp(' PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM'); +disp(' IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF'); +disp(' ALL NECESSARY SERVICING, REPAIR OR CORRECTION.'); +disp(' '); +disp(' IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING'); +disp(' WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS'); +disp(' THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY'); +disp(' GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE'); +disp(' USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF'); +disp(' DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD'); +disp(' PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),'); +disp(' EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF'); +disp(' SUCH DAMAGES.'); +disp(' '); + +end \ No newline at end of file diff --git a/InstanceSpace-master/scriptfcn.m b/InstanceSpace-master/scriptfcn.m new file mode 100644 index 0000000..e074106 --- /dev/null +++ b/InstanceSpace-master/scriptfcn.m @@ -0,0 +1,227 @@ +function scriptfcn +% ------------------------------------------------------------------------- +% scriptfcn.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +writeArray2CSV = @(data,colnames,rownames,filename) writetable(array2table(data,'VariableNames',colnames,... + 'RowNames',rownames),... + filename,'WriteRowNames',true); +writeCell2CSV = @(data,colnames,rownames,filename) writetable(cell2table(data,'VariableNames',colnames,... + 'RowNames',rownames),... + filename,'WriteRowNames',true); +makeBndLabels = @(data) arrayfun(@(x) strcat('bnd_pnt_',num2str(x)),1:size(data,1),'UniformOutput',false); +colorscale = @(data) round(255.*bsxfun(@rdivide, bsxfun(@minus, data, min(data,[],1)), range(data))); +colorscaleg = @(data) round(255.*bsxfun(@rdivide, bsxfun(@minus, data, min(data(:))), range(data(:)))); + +assignin('caller','writeArray2CSV',writeArray2CSV); +assignin('caller','writeCell2CSV',writeCell2CSV); +assignin('caller','makeBndLabels',makeBndLabels); +assignin('caller','colorscale',colorscale); +assignin('caller','colorscaleg',colorscaleg); +assignin('caller','drawSources',@drawSources); +assignin('caller','drawScatter',@drawScatter); +assignin('caller','drawPortfolioSelections',@drawPortfolioSelections); +assignin('caller','drawPortfolioFootprint',@drawPortfolioFootprint); +assignin('caller','drawGoodBadFootprint',@drawGoodBadFootprint); +assignin('caller','drawFootprint',@drawFootprint); +assignin('caller','drawBinaryPerformance',@drawBinaryPerformance); + +end +% ========================================================================= +% SUBFUNCTIONS +% ========================================================================= +function handle = drawSources(Z, S) + +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +sourcelabels = cellstr(unique(S)); +nsources = length(sourcelabels); +clrs = flipud(lines(nsources)); +handle = zeros(nsources,1); +for i=nsources:-1:1 + line(Z(S==sourcelabels{i},1), ... + Z(S==sourcelabels{i},2), ... + 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', clrs(i,:), ... + 'MarkerFaceColor', clrs(i,:), ... + 'MarkerSize', 4); + handle(i) = patch([0 0],[0 0], clrs(i,:), 'EdgeColor','none'); +end +xlabel('z_{1}'); ylabel('z_{2}'); title('Sources'); +legend(handle, sourcelabels, 'Location', 'NorthEastOutside'); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); + +end +% ========================================================================= +function handle = drawScatter(Z, X, titlelabel) + +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +handle = scatter(Z(:,1), Z(:,2), 8, X, 'filled'); +caxis([0,1]) +xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); +colorbar('EastOutside'); + +end +% ========================================================================= +function drawPortfolioSelections(Z, P, algolabels, titlelabel) + +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +nalgos = length(algolabels); +algolbls = cell(1,nalgos+1); +h = zeros(1,nalgos+1); +isworthy = sum(bsxfun(@eq, P, 0:nalgos))~=0; +clr = flipud(lines(nalgos+1)); +for i=0:nalgos + if ~isworthy(i+1) + continue; + end + line(Z(P==i,1), Z(P==i,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', clr(i+1,:), ... + 'MarkerFaceColor', clr(i+1,:), ... + 'MarkerSize', 4); + h(i+1) = patch([0 0],[0 0], clr(i+1,:), 'EdgeColor','none'); + if i==0 + algolbls{i+1} = 'None'; + else + algolbls{i+1} = strrep(algolabels{i},'_',' '); + end +end +xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); +legend(h(isworthy), algolbls(isworthy), 'Location', 'NorthEastOutside'); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); + +end +% ========================================================================= +function h = drawPortfolioFootprint(Z, best, P, algolabels) + +% Color definitions +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +nalgos = length(algolabels); +algolbls = cell(1,nalgos+1); +isworthy = sum(bsxfun(@eq, P, 0:nalgos))~=0; +clr = flipud(lines(nalgos+1)); +h = zeros(1,nalgos+1); +for i=0:nalgos + if ~isworthy(i+1) + continue; + end + line(Z(P==i,1), Z(P==i,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', clr(i+1,:), ... + 'MarkerFaceColor', clr(i+1,:), ... + 'MarkerSize', 4); + h(i+1) = patch([0 0],[0 0], clr(i+1,:), 'EdgeColor','none'); + if i==0 + algolbls{i+1} = 'None'; + else + drawFootprint(best{i}, clr(i+1,:), 0.3); + algolbls{i+1} = strrep(algolabels{i},'_',' '); + end +end +xlabel('z_{1}'); ylabel('z_{2}'); title('Portfolio footprints'); +legend(h(isworthy), algolbls(isworthy), 'Location', 'NorthEastOutside'); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); + +end +% ========================================================================= +function h = drawGoodBadFootprint(Z, good, Ybin, titlelabel) + +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +orange = [1.0 0.6471 0.0]; +blue = [0.0 0.0 1.0]; +lbls = {'GOOD','BAD'}; +h = zeros(1,2); +if any(~Ybin) + % drawFootprint(bad, orange, 0.2); + line(Z(~Ybin,1), Z(~Ybin,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', orange, ... + 'MarkerFaceColor', orange, ... + 'MarkerSize', 4); + h(2) = patch([0 0],[0 0], orange, 'EdgeColor','none'); +end +if any(Ybin) + line(Z(Ybin,1), Z(Ybin,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', blue, ... + 'MarkerFaceColor', blue, ... + 'MarkerSize', 4); + h(1) = patch([0 0],[0 0], blue, 'EdgeColor','none'); + drawFootprint(good, blue, 0.3); +end +xlabel('z_{1}'); ylabel('z_{2}'); title([titlelabel ' Footprints']); +legend(h(h~=0), lbls(h~=0), 'Location', 'NorthEastOutside'); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); + +end +% ========================================================================= +function handle = drawFootprint(footprint, color, alpha) +% +hold on; +if isempty(footprint) || isempty(footprint.polygon) + handle = patch([0 0],[0 0], color, 'EdgeColor','none'); + return +end + +handle = plot(footprint.polygon,'FaceColor', color, 'EdgeColor','none', 'FaceAlpha', alpha); +hold off; + +end +% ========================================================================= +function h = drawBinaryPerformance(Z, Ybin, titlelabel) + +ubound = ceil(max(Z)); +lbound = floor(min(Z)); +orange = [1.0 0.6471 0.0]; +blue = [0.0 0.0 1.0]; +lbls = {'GOOD','BAD'}; +h = zeros(1,2); +if any(~Ybin) + h(2) = patch([0 0],[0 0], orange, 'EdgeColor','none'); + line(Z(~Ybin,1), Z(~Ybin,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', orange, ... + 'MarkerFaceColor', orange, ... + 'MarkerSize', 4); +end +if any(Ybin) + h(1) = patch([0 0],[0 0], blue, 'EdgeColor','none'); + line(Z(Ybin,1), Z(Ybin,2), 'LineStyle', 'none', ... + 'Marker', '.', ... + 'Color', blue, ... + 'MarkerFaceColor', blue, ... + 'MarkerSize', 4); +end +xlabel('z_{1}'); ylabel('z_{2}'); title(titlelabel); +legend(h(h~=0), lbls(h~=0), 'Location', 'NorthEastOutside'); +set(findall(gcf,'-property','FontSize'),'FontSize',12); +set(findall(gcf,'-property','LineWidth'),'LineWidth',1); +axis square; axis([lbound(1)-1 ubound(1)+1 lbound(2)-1 ubound(2)+1]); + +end +% ========================================================================= \ No newline at end of file diff --git a/InstanceSpace-master/scriptfcn.m~ b/InstanceSpace-master/scriptfcn.m~ new file mode 100644 index 0000000..e69de29 diff --git a/InstanceSpace-master/scriptpng.m b/InstanceSpace-master/scriptpng.m new file mode 100644 index 0000000..b564327 --- /dev/null +++ b/InstanceSpace-master/scriptpng.m @@ -0,0 +1,114 @@ +function scriptpng(container,rootdir) +% ------------------------------------------------------------------------- +% pgnscript.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +% ------------------------------------------------------------------------- +% Preliminaries +scriptfcn; +colormap('parula'); +nfeats = size(container.data.X,2); +nalgos = size(container.data.Y,2); +Xaux = (container.data.X-min(container.data.X,[],1))./range(container.data.X,1); +Yind = (container.data.Yraw-min(container.data.Yraw,[],1))./range(container.data.Yraw,1); +Yglb = log10(container.data.Yraw+1); +Yglb = (Yglb-min(Yglb(:)))./range(Yglb(:)); +if container.opts.trace.usesim + Yfoot = container.pythia.Yhat; + Pfoot = container.pythia.selection0; +else + Yfoot = container.data.Ybin; + Pfoot = container.data.P; +end +% ------------------------------------------------------------------------- +disp('========================================================================='); +disp('-> Producing the plots.'); +% ------------------------------------------------------------------------- +% Drawing feature plots +for i=1:nfeats + clf; + drawScatter(container.pilot.Z, Xaux(:,i),... + strrep(container.data.featlabels{i},'_',' ')); + % line(model.cloist.Zedge(:,1), model.cloist.Zedge(:,2), 'LineStyle', '-', 'Color', 'r'); + print(gcf,'-dpng',[rootdir 'distribution_feature_' container.data.featlabels{i} '.png']); +end +% ------------------------------------------------------------------------- +% Drawing algorithm performance/footprint plots +for i=1:nalgos + % Actual performance, normalized globaly + clf; + drawScatter(container.pilot.Z, Yglb(:,i), ... + strrep(container.data.algolabels{i},'_',' ')); + print(gcf,'-dpng',[rootdir 'distribution_performance_global_normalized_' container.data.algolabels{i} '.png']); + % Actual performance, normalized individualy + clf; + drawScatter(container.pilot.Z, Yind(:,i), ... + strrep(container.data.algolabels{i},'_',' ')); + print(gcf,'-dpng',[rootdir 'distribution_performance_individual_normalized_' container.data.algolabels{i} '.png']); + % Actual binary performance + clf; + drawBinaryPerformance(container.pilot.Z, container.data.Ybin(:,i), ... + strrep(container.data.algolabels{i},'_',' ')); + print(gcf,'-dpng',[rootdir 'binary_performance_' container.data.algolabels{i} '.png']); + % Drawing the SVM's predictions of good performance + try + clf; + drawBinaryPerformance(container.pilot.Z, container.pythia.Yhat(:,i), ... + strrep(container.data.algolabels{i},'_',' ')); + print(gcf,'-dpng',[rootdir 'binary_svm_' container.data.algolabels{i} '.png']); + catch + disp('No SVM model has been trained'); + end + % Drawing the footprints for good and bad performance acording to the + % binary measure + try + clf; + drawGoodBadFootprint(container.pilot.Z, ... + container.trace.good{i}, ... + Yfoot(:,i), ... + strrep(container.data.algolabels{i},'_',' ')); + print(gcf,'-dpng',[rootdir 'footprint_' container.data.algolabels{i} '.png']); + catch + disp('No Footprint has been calculated'); + end +end +% --------------------------------------------------------------------- +% Plotting the number of good algos +clf; +drawScatter(container.pilot.Z, container.data.numGoodAlgos./nalgos, 'Percentage of good algorithms'); +print(gcf,'-dpng',[rootdir 'distribution_number_good_algos.png']); +% --------------------------------------------------------------------- +% Drawing the algorithm performance +clf; +drawPortfolioSelections(container.pilot.Z, container.data.P, container.data.algolabels, 'Best algorithm'); +print(gcf,'-dpng',[rootdir 'distribution_portfolio.png']); +% --------------------------------------------------------------------- +% Drawing the SVM's recommendations +clf; +drawPortfolioSelections(container.pilot.Z, container.pythia.selection0, container.data.algolabels, 'Predicted best algorithm'); +print(gcf,'-dpng',[rootdir 'distribution_svm_portfolio.png']); +% --------------------------------------------------------------------- +% Drawing the footprints as portfolio. +clf; +drawPortfolioFootprint(container.pilot.Z, container.trace.best, Pfoot, container.data.algolabels); +print(gcf,'-dpng',[rootdir 'footprint_portfolio.png']); +% --------------------------------------------------------------------- +% Plotting the model.data.beta score +clf; +drawBinaryPerformance(container.pilot.Z, container.data.beta, '\beta score'); +print(gcf,'-dpng',[rootdir 'distribution_beta_score.png']); +% --------------------------------------------------------------------- +% Drawing the sources of the instances if available +if isfield(container.data,'S') + clf; + drawSources(container.pilot.Z, container.data.S); + print(gcf,'-dpng',[rootdir 'distribution_sources.png']); +end \ No newline at end of file diff --git a/InstanceSpace-master/scriptweb.m b/InstanceSpace-master/scriptweb.m new file mode 100644 index 0000000..be0d032 --- /dev/null +++ b/InstanceSpace-master/scriptweb.m @@ -0,0 +1,49 @@ +function scriptweb(container,rootdir) +% ------------------------------------------------------------------------- +% webscript.m +% ------------------------------------------------------------------------- +% +% By: Mario Andres Munoz Acosta +% School of Mathematics and Statistics +% The University of Melbourne +% Australia +% 2020 +% +% ------------------------------------------------------------------------- + +scriptfcn; + +disp('========================================================================='); +disp('-> Writing the data for the web interfase.'); +% ------------------------------------------------------------------------- +writetable(array2table(uint8(255.*parula(256)), ... + 'VariableNames', {'R','G','B'}), ... + [rootdir 'color_table.csv']); +writeArray2CSV(colorscale(container.data.Xraw(:,container.featsel.idx)), ... + container.data.featlabels, ... + container.data.instlabels, ... + [rootdir 'feature_raw_color.csv']); +writeArray2CSV(colorscale(container.data.Yraw), ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_raw_single_color.csv']); +writeArray2CSV(colorscale(container.data.X), ... + container.data.featlabels, ... + container.data.instlabels, ... + [rootdir 'feature_process_color.csv']); +writeArray2CSV(colorscale(container.data.Y), ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_process_single_color.csv']); +writeArray2CSV(colorscaleg(container.data.Yraw), ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_raw_color.csv']); +writeArray2CSV(colorscaleg(container.data.Y), ... + container.data.algolabels, ... + container.data.instlabels, ... + [rootdir 'algorithm_process_color.csv']); +writeArray2CSV(colorscaleg(container.data.numGoodAlgos), ... + {'NumGoodAlgos'}, ... + container.data.instlabels, ... + [rootdir 'good_algos_color.csv']); \ No newline at end of file diff --git a/InstanceSpace-master/svmpredict.mexw64 b/InstanceSpace-master/svmpredict.mexw64 new file mode 100644 index 0000000..4d2319d Binary files /dev/null and b/InstanceSpace-master/svmpredict.mexw64 differ diff --git a/InstanceSpace-master/svmtrain.mexw64 b/InstanceSpace-master/svmtrain.mexw64 new file mode 100644 index 0000000..d1213bb Binary files /dev/null and b/InstanceSpace-master/svmtrain.mexw64 differ diff --git a/InstanceSpace-master/testInterface.m b/InstanceSpace-master/testInterface.m new file mode 100644 index 0000000..6f39bf9 --- /dev/null +++ b/InstanceSpace-master/testInterface.m @@ -0,0 +1,30 @@ +try + rootdir = 'E:/InstanceSpace_Classification/MATILDA_trial/'; + testingDir = strcat(rootdir, 'test/'); + status = mkdir(testingDir); + if status == 0 + error('Can not create sub-directory to store testing results. '); + else + source_metadata = fullfile(rootdir, 'metadata_test.csv'); + source_model = fullfile(rootdir, 'model.mat'); + status = copyfile(source_metadata, testingDir); + if status == 0 + error('Error: Please place metadata_test inside %s', rootdir ); + end + status = copyfile(source_model, testingDir); + if status == 0 + error('Error: could not find model.mat inside %s', rootdir ); + end + + source_options = fullfile(rootdir, 'options.json'); + status = copyfile(source_options, testingDir); + if status == 0 + error('Error: could not find options.json inside %s', rootdir ); + end + + testIS(testingDir); + end +catch ME + disp('EOF:ERROR'); + rethrow(ME) +end \ No newline at end of file diff --git a/config_spaces/__init__.py b/config_spaces/__init__.py new file mode 100644 index 0000000..3569721 --- /dev/null +++ b/config_spaces/__init__.py @@ -0,0 +1,10 @@ + +class MLModelGenerator: + @classmethod + def generate_algorithm_configuration_space(cls, model_class=None): + + class_attributes = {} + for cls_ in [cls, cls.__base__]: + class_attributes.update({k: v for k, v in vars(cls_).items() if not k.startswith('_') and type(v) != classmethod}) + + return class_attributes diff --git a/config_spaces/ada.py b/config_spaces/ada.py new file mode 100644 index 0000000..3b26bc9 --- /dev/null +++ b/config_spaces/ada.py @@ -0,0 +1,49 @@ +import logging +import pprint +from typing import Tuple, List, Optional, Union + +import numpy as np +import pandas as pd +import timeit + +from hyperopt.pyll import scope +from imbens.ensemble import AdaCostClassifier, AsymBoostClassifier +from imbens.ensemble.reweighting import AdaUBoostClassifier +from matplotlib import pyplot as plt +from openml import flows as openml_flows +from openml import runs as openml_runs +from openml import tasks as openml_tasks +from openml import utils as openml_utils +from abc import ABC, abstractmethod +import numpy as np +from hyperopt import hp +from typing import TypeVar +from sklearn.ensemble import AdaBoostClassifier +from config_spaces import MLModelGenerator + + +logger = logging.getLogger(__name__) + +class AdaBoostGenerator(MLModelGenerator): + n_estimators = scope.int(hp.loguniform('ada.n_estimators', np.log(10.5), np.log(500.5))) + learning_rate = hp.lognormal('ada.learning_rate', np.log(0.01), np.log(20.0)) + + @classmethod + def generate_algorithm_configuration_space(cls, model_class=None): + param_map = super().generate_algorithm_configuration_space() + param_map.update({'model_class': model_class if model_class is not None else AdaBoostClassifier}) + + return param_map + + +class AdaReweightedGenerator(AdaBoostGenerator): + early_termination = True + + @classmethod + def generate_algorithm_configuration_space(cls, model_class=None): + if model_class is None: + raise ValueError("Model class must be specified for AdaReweightedGenerator.") + param_map = super().generate_algorithm_configuration_space() + param_map.update({'model_class': model_class}) + + return param_map diff --git a/config_spaces/classifiers_tpot.py b/config_spaces/classifiers_tpot.py new file mode 100644 index 0000000..49b714a --- /dev/null +++ b/config_spaces/classifiers_tpot.py @@ -0,0 +1,564 @@ +from ConfigSpace import ConfigurationSpace +from ConfigSpace import ConfigurationSpace, Integer, Float, Categorical, Normal +from ConfigSpace import EqualsCondition, OrConjunction, NotEqualsCondition, InCondition +from ..search_spaces.nodes.estimator_node import NONE_SPECIAL_STRING, TRUE_SPECIAL_STRING, FALSE_SPECIAL_STRING +import numpy as np +import sklearn + + +def get_LogisticRegression_ConfigurationSpace(random_state): + + dual = FALSE_SPECIAL_STRING + + space = {"solver":"saga", + "max_iter":1000, + "n_jobs":1, + "dual":dual, + } + + penalty = Categorical('penalty', ['l1', 'l2',"elasticnet"], default='l2') + C = Float('C', (0.01, 1e5), log=True) + l1_ratio = Float('l1_ratio', (0.0, 1.0)) + class_weight = Categorical('class_weight', [NONE_SPECIAL_STRING, 'balanced']) + + l1_ratio_condition = EqualsCondition(l1_ratio, penalty, 'elasticnet') + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + + cs = ConfigurationSpace(space) + cs.add_hyperparameters([penalty, C, l1_ratio, class_weight]) + cs.add_conditions([l1_ratio_condition]) + + return cs + + +def get_KNeighborsClassifier_ConfigurationSpace(n_samples): + return ConfigurationSpace( + + space = { + + 'n_neighbors': Integer("n_neighbors", bounds=(1, min(100,n_samples)), log=True), + 'weights': Categorical("weights", ['uniform', 'distance']), + 'p': Integer("p", bounds=(1, 3)), + 'metric': Categorical("metric", ['euclidean', 'minkowski']), + 'n_jobs': 1, + } + ) + +def get_BaggingClassifier_ConfigurationSpace(random_state): + space = { + 'n_estimators': Integer("n_estimators", bounds=(3, 100)), + 'max_samples': Float("max_samples", bounds=(0.1, 1.0)), + 'max_features': Float("max_features", bounds=(0.1, 1.0)), + + 'bootstrap_features': Categorical("bootstrap_features", [True, False]), + 'n_jobs': 1, + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + bootstrap = Categorical("bootstrap", [True, False]) + oob_score = Categorical("oob_score", [True, False]) + + oob_condition = EqualsCondition(oob_score, bootstrap, True) + + cs = ConfigurationSpace( + space = space + ) + + cs.add_hyperparameters([bootstrap, oob_score]) + cs.add_conditions([oob_condition]) + + return cs + +def get_DecisionTreeClassifier_ConfigurationSpace(n_featues, random_state): + + space = { + 'criterion': Categorical("criterion", ['gini', 'entropy']), + 'max_depth': Integer("max_depth", bounds=(1, min(20,2*n_featues))), #max of 20? log scale? + 'min_samples_split': Integer("min_samples_split", bounds=(1, 20)), + 'min_samples_leaf': Integer("min_samples_leaf", bounds=(1, 20)), + 'max_features': Categorical("max_features", [NONE_SPECIAL_STRING, 'sqrt', 'log2']), + 'min_weight_fraction_leaf': 0.0, + 'class_weight' : Categorical('class_weight', [NONE_SPECIAL_STRING, 'balanced']), + } + + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + +#TODO Does not support predict_proba +def get_LinearSVC_ConfigurationSpace(random_state): + space = {"dual":"auto"} + + penalty = Categorical('penalty', ['l1', 'l2']) + C = Float('C', (0.01, 1e5), log=True) + loss = Categorical('loss', ['hinge', 'squared_hinge']) + loss_condition = EqualsCondition(loss, penalty, 'l2') + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + + cs = ConfigurationSpace(space) + cs.add_hyperparameters([penalty, C, loss]) + cs.add_conditions([loss_condition]) + + return cs + + +def get_SVC_ConfigurationSpace(random_state): + + space = { + 'max_iter': 3000, + 'probability':TRUE_SPECIAL_STRING} + + kernel = Categorical("kernel", ['poly', 'rbf', 'sigmoid', 'linear']) + C = Float('C', (0.01, 1e5), log=True) + degree = Integer("degree", bounds=(1, 5)) + gamma = Float("gamma", bounds=(1e-5, 8), log=True) + shrinking = Categorical("shrinking", [True, False]) + coef0 = Float("coef0", bounds=(-1, 1)) + class_weight = Categorical('class_weight', [NONE_SPECIAL_STRING, 'balanced']) + + degree_condition = EqualsCondition(degree, kernel, 'poly') + gamma_condition = InCondition(gamma, kernel, ['rbf', 'poly']) + coef0_condition = InCondition(coef0, kernel, ['poly', 'sigmoid']) + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + + cs = ConfigurationSpace(space) + cs.add_hyperparameters([kernel, C, coef0, degree, gamma, shrinking, class_weight]) + cs.add_conditions([degree_condition, gamma_condition, coef0_condition]) + + return cs + + +def get_RandomForestClassifier_ConfigurationSpace( random_state): + space = { + 'n_estimators': 128, #as recommended by Oshiro et al. (2012 + 'max_features': Float("max_features", bounds=(0.01,1)), #log scale like autosklearn? + 'criterion': Categorical("criterion", ['gini', 'entropy']), + 'min_samples_split': Integer("min_samples_split", bounds=(2, 20)), + 'min_samples_leaf': Integer("min_samples_leaf", bounds=(1, 20)), + 'bootstrap': Categorical("bootstrap", [True, False]), + 'class_weight': Categorical("class_weight", [NONE_SPECIAL_STRING, 'balanced']), + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + + +def get_XGBClassifier_ConfigurationSpace(random_state,): + + space = { + 'n_estimators': 100, + 'learning_rate': Float("learning_rate", bounds=(1e-3, 1), log=True), + 'subsample': Float("subsample", bounds=(0.5, 1.0)), + 'min_child_weight': Integer("min_child_weight", bounds=(1, 21)), + 'gamma': Float("gamma", bounds=(1e-4, 20), log=True), + 'max_depth': Integer("max_depth", bounds=(3, 18)), + 'reg_alpha': Float("reg_alpha", bounds=(1e-4, 100), log=True), + 'reg_lambda': Float("reg_lambda", bounds=(1e-4, 1), log=True), + 'n_jobs': 1, + 'nthread': 1, + 'verbosity': 0, + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + +def get_LGBMClassifier_ConfigurationSpace(random_state,): + + space = { + 'boosting_type': Categorical("boosting_type", ['gbdt', 'dart', 'goss']), + 'num_leaves': Integer("num_leaves", bounds=(2, 256)), + 'max_depth': Integer("max_depth", bounds=(1, 10)), + 'n_estimators': Integer("n_estimators", bounds=(10, 100)), + 'class_weight': Categorical("class_weight", [NONE_SPECIAL_STRING, 'balanced']), + 'verbose':-1, + 'n_jobs': 1, + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space=space + ) + + +def get_ExtraTreesClassifier_ConfigurationSpace(random_state): + space = { + 'n_estimators': 100, + 'criterion': Categorical("criterion", ["gini", "entropy"]), + 'max_features': Float("max_features", bounds=(0.01, 1.00)), + 'min_samples_split': Integer("min_samples_split", bounds=(2, 20)), + 'min_samples_leaf': Integer("min_samples_leaf", bounds=(1, 20)), + 'bootstrap': Categorical("bootstrap", [True, False]), + 'class_weight': Categorical("class_weight", [NONE_SPECIAL_STRING, 'balanced']), + 'n_jobs': 1, + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + + + +def get_SGDClassifier_ConfigurationSpace(random_state): + + space = { + 'loss': Categorical("loss", ['modified_huber']), #don't include hinge because we have LinearSVC, don't include log because we have LogisticRegression. TODO 'squared_hinge'? doesn't support predict proba + 'penalty': 'elasticnet', + 'alpha': Float("alpha", bounds=(1e-5, 0.01), log=True), + 'l1_ratio': Float("l1_ratio", bounds=(0.0, 1.0)), + 'eta0': Float("eta0", bounds=(0.01, 1.0)), + 'n_jobs': 1, + 'fit_intercept': Categorical("fit_intercept", [True]), + 'class_weight': Categorical("class_weight", [NONE_SPECIAL_STRING, 'balanced']), + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + power_t = Float("power_t", bounds=(1e-5, 100.0), log=True) + learning_rate = Categorical("learning_rate", ['invscaling', 'constant', "optimal"]) + powertcond = EqualsCondition(power_t, learning_rate, 'invscaling') + + + cs = ConfigurationSpace( + space = space + ) + + cs.add_hyperparameters([power_t, learning_rate]) + cs.add_conditions([powertcond]) + + return cs + + +GaussianNB_ConfigurationSpace = {} + +def get_BernoulliNB_ConfigurationSpace(): + return ConfigurationSpace( + space = { + 'alpha': Float("alpha", bounds=(1e-2, 100), log=True), + 'fit_prior': Categorical("fit_prior", [True, False]), + } + ) + + +def get_MultinomialNB_ConfigurationSpace(): + return ConfigurationSpace( + space = { + 'alpha': Float("alpha", bounds=(1e-3, 100), log=True), + 'fit_prior': Categorical("fit_prior", [True, False]), + } + ) + + + +def get_AdaBoostClassifier_ConfigurationSpace(random_state): + space = { + 'n_estimators': Integer("n_estimators", bounds=(50, 500)), + 'learning_rate': Float("learning_rate", bounds=(0.01, 2), log=True), + 'algorithm': Categorical("algorithm", ['SAMME', 'SAMME.R']), + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + + +def get_QuadraticDiscriminantAnalysis_ConfigurationSpace(): + return ConfigurationSpace( + space = { + 'reg_param': Float("reg_param", bounds=(0, 1)), + } + ) + +def get_PassiveAggressiveClassifier_ConfigurationSpace(random_state): + space = { + 'C': Float("C", bounds=(1e-5, 10), log=True), + 'loss': Categorical("loss", ['hinge', 'squared_hinge']), + 'average': Categorical("average", [True, False]), + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) +#TODO support auto shrinkage when solver is svd. may require custom node +def get_LinearDiscriminantAnalysis_ConfigurationSpace(): + + solver = Categorical("solver", ['svd', 'lsqr', 'eigen']) + shrinkage = Float("shrinkage", bounds=(0, 1)) + + shrinkcond = NotEqualsCondition(shrinkage, solver, 'svd') + + cs = ConfigurationSpace() + cs.add_hyperparameters([solver, shrinkage]) + cs.add_conditions([shrinkcond]) + + return cs + + + +#### Gradient Boosting Classifiers + +def get_GradientBoostingClassifier_ConfigurationSpace(n_classes, random_state): + early_stop = Categorical("early_stop", ["off", "valid", "train"]) + n_iter_no_change = Integer("n_iter_no_change",bounds=(1,20)) + validation_fraction = Float("validation_fraction", bounds=(0.01, 0.4)) + + n_iter_no_change_cond = InCondition(n_iter_no_change, early_stop, ["valid", "train"] ) + validation_fraction_cond = EqualsCondition(validation_fraction, early_stop, "valid") + + space = { + 'learning_rate': Float("learning_rate", bounds=(1e-3, 1), log=True), + 'min_samples_leaf': Integer("min_samples_leaf", bounds=(1, 200)), + 'min_samples_split': Integer("min_samples_split", bounds=(2, 20)), + 'subsample': Float("subsample", bounds=(0.1, 1.0)), + 'max_features': Float("max_features", bounds=(0.01, 1.00)), + 'max_leaf_nodes': Integer("max_leaf_nodes", bounds=(3, 2047)), + 'max_depth':NONE_SPECIAL_STRING, # 'max_depth': Integer("max_depth", bounds=(1, 2*n_features)), + 'tol': 1e-4, + } + + if n_classes == 2: + space['loss']= Categorical("loss", ['log_loss', 'exponential']) + else: + space['loss'] = "log_loss" + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + cs = ConfigurationSpace( + space = space + ) + cs.add_hyperparameters([n_iter_no_change, validation_fraction, early_stop ]) + cs.add_conditions([validation_fraction_cond, n_iter_no_change_cond]) + return cs + +def GradientBoostingClassifier_hyperparameter_parser(params): + + final_params = { + 'loss': params['loss'], + 'learning_rate': params['learning_rate'], + 'min_samples_leaf': params['min_samples_leaf'], + 'min_samples_split': params['min_samples_split'], + 'max_features': params['max_features'], + 'max_leaf_nodes': params['max_leaf_nodes'], + 'max_depth': params['max_depth'], + 'tol': params['tol'], + 'subsample': params['subsample'] + } + + if 'random_state' in params: + final_params['random_state'] = params['random_state'] + + if params['early_stop'] == 'off': + final_params['n_iter_no_change'] = None + final_params['validation_fraction'] = None + elif params['early_stop'] == 'valid': + #this is required because in crossover, its possible that n_iter_no_change is not in the params + if 'n_iter_no_change' not in params: + final_params['n_iter_no_change'] = 10 + else: + final_params['n_iter_no_change'] = params['n_iter_no_change'] + if 'validation_fraction' not in params: + final_params['validation_fraction'] = 0.1 + else: + final_params['validation_fraction'] = params['validation_fraction'] + elif params['early_stop'] == 'train': + if 'n_iter_no_change' not in params: + final_params['n_iter_no_change'] = 10 + final_params['validation_fraction'] = None + + + return final_params + + + +#only difference is l2_regularization +def get_HistGradientBoostingClassifier_ConfigurationSpace(random_state): + early_stop = Categorical("early_stop", ["off", "valid", "train"]) + n_iter_no_change = Integer("n_iter_no_change",bounds=(1,20)) + validation_fraction = Float("validation_fraction", bounds=(0.01, 0.4)) + + n_iter_no_change_cond = InCondition(n_iter_no_change, early_stop, ["valid", "train"] ) + validation_fraction_cond = EqualsCondition(validation_fraction, early_stop, "valid") + + space = { + 'learning_rate': Float("learning_rate", bounds=(1e-3, 1), log=True), + 'min_samples_leaf': Integer("min_samples_leaf", bounds=(1, 200)), + 'max_features': Float("max_features", bounds=(0.1,1.0)), + 'max_leaf_nodes': Integer("max_leaf_nodes", bounds=(3, 2047)), + 'max_depth':NONE_SPECIAL_STRING, # 'max_depth': Integer("max_depth", bounds=(1, 2*n_features)), + 'l2_regularization': Float("l2_regularization", bounds=(1e-10, 1), log=True), + 'tol': 1e-4, + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + cs = ConfigurationSpace( + space = space + ) + cs.add_hyperparameters([n_iter_no_change, validation_fraction, early_stop ]) + cs.add_conditions([validation_fraction_cond, n_iter_no_change_cond]) + + return cs + + + +def HistGradientBoostingClassifier_hyperparameter_parser(params): + + final_params = { + 'learning_rate': params['learning_rate'], + 'min_samples_leaf': params['min_samples_leaf'], + 'max_features': params['max_features'], + 'max_leaf_nodes': params['max_leaf_nodes'], + 'max_depth': params['max_depth'], + 'tol': params['tol'], + 'l2_regularization': params['l2_regularization'] + } + + if 'random_state' in params: + final_params['random_state'] = params['random_state'] + + + + if params['early_stop'] == 'off': + # final_params['n_iter_no_change'] = 0 + final_params['validation_fraction'] = None + final_params['early_stopping'] = False + elif params['early_stop'] == 'valid': + + #this is required because in crossover, its possible that n_iter_no_change is not in the params + if 'n_iter_no_change' not in params: + final_params['n_iter_no_change'] = 10 + else: + final_params['n_iter_no_change'] = params['n_iter_no_change'] + if 'validation_fraction' not in params: + final_params['validation_fraction'] = 0.1 + else: + final_params['validation_fraction'] = params['validation_fraction'] + + final_params['early_stopping'] = True + elif params['early_stop'] == 'train': + + if 'n_iter_no_change' not in params: + final_params['n_iter_no_change'] = 10 + else: + final_params['n_iter_no_change'] = params['n_iter_no_change'] + + + final_params['validation_fraction'] = None + final_params['early_stopping'] = True + + + return final_params + + +### + +def get_MLPClassifier_ConfigurationSpace(random_state): + space = {"n_iter_no_change":32} + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + cs = ConfigurationSpace( + space = space + ) + + n_hidden_layers = Integer("n_hidden_layers", bounds=(1, 3)) + n_nodes_per_layer = Integer("n_nodes_per_layer", bounds=(16, 512)) + activation = Categorical("activation", ["identity", "logistic",'tanh', 'relu']) + alpha = Float("alpha", bounds=(1e-4, 1e-1), log=True) + early_stopping = Categorical("early_stopping", [True,False]) + + learning_rate_init = Float("learning_rate_init", bounds=(1e-4, 1e-1), log=True) + learning_rate = Categorical("learning_rate", ['constant', 'invscaling', 'adaptive']) + + cs.add_hyperparameters([n_hidden_layers, n_nodes_per_layer, activation, alpha, learning_rate, early_stopping, learning_rate_init]) + + return cs + +def MLPClassifier_hyperparameter_parser(params): + hyperparameters = { + 'n_iter_no_change': params['n_iter_no_change'], + 'hidden_layer_sizes' : [params['n_nodes_per_layer']]*params['n_hidden_layers'], + 'activation': params['activation'], + 'alpha': params['alpha'], + 'early_stopping': params['early_stopping'], + + 'learning_rate_init': params['learning_rate_init'], + 'learning_rate': params['learning_rate'], + } + + if 'random_state' in params: + hyperparameters['random_state'] = params['random_state'] + return hyperparameters + +### + + +### + +def get_GaussianProcessClassifier_ConfigurationSpace(n_features, random_state): + space = { + 'n_features': n_features, + 'alpha': Float("alpha", bounds=(1e-14, 1.0), log=True), + 'thetaL': Float("thetaL", bounds=(1e-10, 1e-3), log=True), + 'thetaU': Float("thetaU", bounds=(1.0, 100000), log=True), + } + + if random_state is not None: #This is required because configspace doesn't allow None as a value + space['random_state'] = random_state + + return ConfigurationSpace( + space = space + ) + +def GaussianProcessClassifier_hyperparameter_parser(params): + kernel = sklearn.gaussian_process.kernels.RBF( + length_scale = [1.0]*params['n_features'], + length_scale_bounds=[(params['thetaL'], params['thetaU'])] * params['n_features'], + ) + final_params = {"kernel": kernel, + "n_restarts_optimizer": 10, + "optimizer": "fmin_l_bfgs_b", + "copy_X_train": True, + } + + if "random_state" in params: + final_params['random_state'] = params['random_state'] + + return final_params \ No newline at end of file diff --git a/config_spaces/forest.py b/config_spaces/forest.py new file mode 100644 index 0000000..a160782 --- /dev/null +++ b/config_spaces/forest.py @@ -0,0 +1,33 @@ +import numpy as np +from hyperopt import hp +from hyperopt.pyll import scope +from imbens.ensemble.under_sampling import BalancedRandomForestClassifier +from sklearn.ensemble import RandomForestClassifier + +from config_spaces import MLModelGenerator + + +class RandomForestGenerator(MLModelGenerator): + n_estimators = scope.int(hp.loguniform('rf.n_estimators', np.log(9.5), np.log(3000.5))) + bootstrap = hp.choice('rf.bootstrap', [True, False]) + criterion = hp.choice('rf.criterion', ['gini', 'entropy']) + max_features = hp.uniform('rf.max_features', 0.05, 1) + min_samples_split = hp.choice('rf.min_samples_split', [2, 3]) + min_samples_leaf = scope.int(hp.loguniform('rf.min_samples_leaf', np.log(1.5), np.log(50.5))) + class_weight = hp.choice('rf.class_weight', ['balanced', 'balanced_subsample', None]) + + @classmethod + def generate_algorithm_configuration_space(cls): + param_map = super().generate_algorithm_configuration_space() + param_map.update({'model_class': RandomForestClassifier}) + + return param_map + + +class BRFGenerator(RandomForestGenerator): + @classmethod + def generate_algorithm_configuration_space(cls): + param_map = super().generate_algorithm_configuration_space() + param_map.update({'model_class': BalancedRandomForestClassifier}) + + return param_map \ No newline at end of file diff --git a/domain.py b/domain.py new file mode 100644 index 0000000..b103e1c --- /dev/null +++ b/domain.py @@ -0,0 +1,14 @@ +import uuid +from dataclasses import dataclass +from typing import Optional + +import pandas as pd + + +@dataclass +class Dataset: + id: int + name: str + X: pd.DataFrame + y: pd.DataFrame + target_label: Optional[str] = None diff --git a/experiment.sh b/experiment.sh new file mode 100755 index 0000000..79bb79c --- /dev/null +++ b/experiment.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +args=("$@") + + +run_experiment() { + declare out='file' + if [[ ${args[1]} == "c" ]]; then + out="console" + elif [[ ${args[1]} != "f" ]]; then + echo "Invalid second argument. Options available: ['f' (for file), 'c' (for console)]." + return + fi + + declare automl='imba' + if [[ ${args[0]} == "ag" || ${args[0]} == "imba" ]]; then + source devenv/bin/activate + if [[ ${args[0]} == "ag" ]]; then + automl="ag" + fi + "$VIRTUAL_ENV"/bin/python -m experiment.main --automl="$automl" --o="$out" + else + echo "Invalid first argument. Options available: ['imba', 'ag']." + return + fi +} + +run_experiment + diff --git a/experiment/__init__.py b/experiment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/experiment/autogluon.py b/experiment/autogluon.py new file mode 100644 index 0000000..37966d3 --- /dev/null +++ b/experiment/autogluon.py @@ -0,0 +1,93 @@ +import math +import multiprocessing +import os +import pprint +import traceback +from os import walk + +import arff +import numpy as np +import openml +import pandas as pd +import sklearn.metrics +from autogluon.tabular import TabularDataset, TabularPredictor +from autogluon.core.metrics import make_scorer +from imblearn.metrics import geometric_mean_score +from sklearn.exceptions import NotFittedError +from sklearn.metrics import * +from sklearn.model_selection import train_test_split as tts +from imblearn.datasets import make_imbalance +from sklearn.preprocessing import LabelEncoder +from collections import Counter +import torch +import logging +import pickle + +from experiment.runner import ExperimentRunner, OpenMLExperimentRunner, ZenodoExperimentRunner +from utils.decorators import ExceptionWrapper +from sklearn.linear_model import LogisticRegression + +logger = logging.getLogger(__name__) + + +class AGExperimentRunner(ZenodoExperimentRunner): + def __init__(self, preset): + super().__init__() + self._preset = preset + # check how to apply decorators for abstract class inheritance case. + @ExceptionWrapper.log_exception + def predict(self, X_test): + if self._fitted_model is None: + raise NotFittedError() + + dataset_test = TabularDataset(X_test) + predictions = self._fitted_model.predict(dataset_test) + + return predictions + + @ExceptionWrapper.log_exception + def fit(self, + X_train, + y_train, + target_label, + dataset_name + ): + if target_label is None and isinstance(X_train, np.ndarray): + dataset_train = pd.DataFrame(data=np.column_stack([X_train, y_train])) + autogluon_dataset_train = pd.DataFrame(dataset_train) + target_label = list(autogluon_dataset_train.columns)[-1] + else: + dataset_train = pd.DataFrame( + data=np.column_stack([X_train, y_train]), + columns=[*X_train.columns, target_label]) + + autogluon_dataset_train = TabularDataset(pd.DataFrame( + dataset_train, + columns=[*X_train.columns, target_label])) + + autogluon_predictor = TabularPredictor( + problem_type='binary', + label=target_label, + eval_metric='f1', + verbosity=2) \ + .fit( + autogluon_dataset_train, + presets=[self._preset, 'optimize_for_deployment'], + ) + + logger.info(f"Training on dataset {dataset_name} finished.") + + val_scores = autogluon_predictor.leaderboard().get('score_val') + logger.info(val_scores) + if len(val_scores) == 0: + logger.error("No best model found.") + return + + best_model_name = autogluon_predictor.get_model_best() + + val_losses = {best_model_name: val_scores.max()} + self._log_val_loss_alongside_model_class(val_losses) + + autogluon_predictor.delete_models(models_to_keep=best_model_name, dry_run=False) + + self._fitted_model = autogluon_predictor diff --git a/experiment/imba.py b/experiment/imba.py new file mode 100644 index 0000000..9d365bf --- /dev/null +++ b/experiment/imba.py @@ -0,0 +1,160 @@ +import logging +import pprint +import traceback +from abc import abstractmethod, ABC +from typing import Optional, Tuple, Union, Any, TypeVar + +import arff +import openml +import pandas as pd +import numpy as np +from collections import Counter + +import sklearn.metrics +from hyperopt import fmin, tpe, STATUS_OK, Trials, rand, hp, space_eval +from functools import partial + +from ray.tune import Tuner +from ray.tune.search import ConcurrencyLimiter +from sklearn.exceptions import NotFittedError +from sklearn.model_selection import train_test_split as tts, cross_val_score, StratifiedKFold +from sklearn.ensemble import RandomForestClassifier +from sklearn.preprocessing import LabelEncoder +from imblearn.pipeline import Pipeline, make_pipeline +from imblearn.datasets import fetch_datasets, make_imbalance +from imbens.ensemble import AdaUBoostClassifier, AdaCostClassifier, AsymBoostClassifier, OverBoostClassifier, \ + SMOTEBoostClassifier, OverBaggingClassifier, BalancedRandomForestClassifier +from os import walk +from sklearn.metrics import * +from imblearn.over_sampling import SMOTE +from imblearn.under_sampling import RandomUnderSampler +from imblearn.over_sampling import RandomOverSampler + +from config_spaces.ada import AdaReweightedGenerator +from config_spaces.forest import RandomForestGenerator, BRFGenerator +from utils.decorators import ExceptionWrapper +from .runner import ExperimentRunner, OpenMLExperimentRunner, ZenodoExperimentRunner + +import ray +from ray.tune.search.hyperopt import HyperOptSearch + + +logger = logging.getLogger(__name__) + + +class RayTrainable(ray.tune.Trainable): + def setup(self, config): + self.algorithm_configuration = config["algorithm_configuration"] + self.metric = config["metric"] + self.X = config['X'] + self.y = config['y'] + + def step(self): + trial_result = ImbaExperimentRunner.compute_metric_score( + self.algorithm_configuration, + self.metric, + self.X, + self.y) + return {"loss": trial_result['loss']} + + +class ImbaExperimentRunner(ZenodoExperimentRunner): + @classmethod + def compute_metric_score(cls, hyper_parameters, metric, X, y): + hyper_parameters = hyper_parameters.copy() + model_class = hyper_parameters.pop('model_class') + clf = model_class(**hyper_parameters) + + loss_value = cross_val_score( + estimator=clf, + X=X, + y=y, + cv=StratifiedKFold(n_splits=3), + scoring=make_scorer(metric, pos_label=1), + error_score='raise').mean() + + return {'loss': loss_value, 'status': STATUS_OK} + + @ExceptionWrapper.log_exception + def fit( + self, + X_train: Union[np.ndarray, pd.DataFrame], + y_train: Union[np.ndarray, pd.Series], + target_label: str, + dataset_name: str + ): + + number_of_instances = X_train.shape[0] + number_of_columns = X_train.shape[1] + logger.info(f'N = {number_of_instances}. M = {number_of_columns}') + + model_classes = [ + AdaReweightedGenerator.generate_algorithm_configuration_space(AdaUBoostClassifier), + AdaReweightedGenerator.generate_algorithm_configuration_space(AdaCostClassifier), + AdaReweightedGenerator.generate_algorithm_configuration_space(AsymBoostClassifier), + BRFGenerator.generate_algorithm_configuration_space() + ] + + algorithms_configuration = hp.choice("algorithm_configuration", model_classes) + ray_configuration = { + 'X': X_train, + 'y': y_train, + 'metric': f1_score, + 'algorithm_configuration': algorithms_configuration + } + + # HyperOptSearch(points_to_evaluate = promising initial points) + search_algo = ConcurrencyLimiter( + HyperOptSearch( + space=ray_configuration, + metric='loss', + mode='min'), + max_concurrent=4, + batch=True) + + tuner = ray.tune.Tuner( + RayTrainable, + tune_config=ray.tune.TuneConfig( + metric='loss', + mode='max', + search_alg=search_algo, + num_samples=self._n_evals, + reuse_actors=True), + # param_space=ray_configuration + ) + + logger.info(f"Document {dataset_name}") + + results = tuner.fit() + + best_trial = results.get_best_result(metric='loss', mode='min') + + best_trial_metrics = getattr(best_trial, 'metrics') + if best_trial_metrics is None: + raise Exception("Optimization failed. No best trial found.") + + logger.info(f"Training on dataset {dataset_name} finished.") + + best_validation_loss = best_trial_metrics.get('loss') + + best_algorithm_configuration = best_trial_metrics.get('config').get('algorithm_configuration') + + best_model_class = best_algorithm_configuration.get('model_class') + best_algorithm_configuration.pop('model_class') + + best_model = best_model_class(**best_algorithm_configuration) + + val_losses = {best_model: best_validation_loss} + self._log_val_loss_alongside_model_class(val_losses) + + best_model.fit(X_train, y_train) + + self._fitted_model = best_model + + @ExceptionWrapper.log_exception + def predict(self, X_test): + if self._fitted_model is None: + raise NotFittedError() + + predictions = self._fitted_model.predict(X_test) + return predictions diff --git a/experiment/main.py b/experiment/main.py new file mode 100644 index 0000000..6f21a51 --- /dev/null +++ b/experiment/main.py @@ -0,0 +1,72 @@ +import argparse +import logging +import os +import shutil +import sys +from datetime import datetime + +from setuptools import setup + +import numpy as np +from experiment.runner import OpenMLExperimentRunner + + +class ExperimentMain: + @staticmethod + def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--automl', action='store', dest='automl', default='imba') + parser.add_argument('--o', action='store', dest='o', default='file') + parser.add_argument('--preset', action='store', dest='preset', default='good_quality') + + args = parser.parse_args() + automl = getattr(args, 'automl') + logging_output = getattr(args, 'o') + autogluon_preset = getattr(args, 'preset') + + if logging_output == 'file': + if automl == 'ag': + log_file_name = 'logs/AG/' + else: + log_file_name = 'logs/Imba/' + log_file_name += datetime.now().strftime('%Y-%m-%d %H:%M') + '.log' + + logging.basicConfig( + filename=log_file_name, + filemode="a", + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s' + ) + elif logging_output == 'console': + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s' + ) + else: + raise Exception("Invalid --o option. Options available: ['file', 'console'].") + + if automl == 'ag': + if autogluon_preset not in ['medium_quality', 'good_quality']: + raise Exception("Invalid --preset option. Options available: ['medium_quality', 'good_quality'].") + + from experiment.autogluon import AGExperimentRunner + + runner = AGExperimentRunner(autogluon_preset) + elif automl == 'imba': + from experiment.imba import ImbaExperimentRunner + + runner = ImbaExperimentRunner() + else: + raise Exception("Invalid --automl option. Options available: ['imba', 'ag'].") + + runner.define_tasks() + + runner.run(30) + + + + +if __name__ == '__main__': + ExperimentMain.main() + diff --git a/experiment/runner.py b/experiment/runner.py new file mode 100644 index 0000000..95a6754 --- /dev/null +++ b/experiment/runner.py @@ -0,0 +1,255 @@ +import itertools +import logging +import multiprocessing +import os +import pprint +import shutil +import traceback +from abc import ABC, abstractmethod +from collections import Counter +from typing import Tuple, Optional, Union, List, Callable, Any, TypeVar + +import numpy as np +import openml +import pandas as pd +import sklearn.base +from imblearn.datasets import fetch_datasets +from imblearn.metrics import geometric_mean_score +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import train_test_split as tts + +from sklearn.metrics import * + + +from domain import Dataset +from utils.decorators import ExceptionWrapper + +logger = logging.getLogger(__name__) +FittedModel = TypeVar('FittedModel', bound=Any) + +class ExperimentRunner(ABC): + def __init__(self, *args, **kwargs): + self._tasks: List[Dataset, ...] = [] + self._id_counter = itertools.count(start=1) + self._n_evals = 10 + self._fitted_model: FittedModel + + self._configure_environment() + + @abstractmethod + def define_tasks(self, task_range: Optional[Tuple[int, ...]] = None): + raise NotImplementedError() + + @abstractmethod + def fit( + self, + X_train: Union[np.ndarray, pd.DataFrame], + y_train: Union[np.ndarray, pd.Series], + target_label: str, + dataset_name: str): + raise NotImplementedError() + + @abstractmethod + def predict(self, X_test: Union[np.ndarray, pd.DataFrame]) -> np.ndarray: + raise NotImplementedError() + + @abstractmethod + def load_dataset(self, task_id: Optional[int] = None) -> Optional[Dataset]: + raise NotImplementedError() + + def _log_val_loss_alongside_model_class(self, losses): + for m, l in losses.items(): + logger.info(f"Validation loss: {float(l):.3f}") + logger.info(pprint.pformat(f'Model class: {m}')) + + def get_tasks(self): + return self._tasks + + def run(self, n_evals: Optional[int] = None): + if n_evals is not None: + self._n_evals = n_evals + for task in self._tasks: + if task is None: + return + + logger.info(f"{task.id}...Loaded dataset name: {task.name}.") + logger.info(f'N: {task.X.shape[0]}. M: {task.X.shape[1]}') + + if isinstance(task.X, np.ndarray): + X_train, X_test, y_train, y_test = self.split_data_on_train_and_test(task.X, task.y) + elif isinstance(task.X, pd.DataFrame): + preprocessed_data = self.preprocess_data(task.X, task.y.squeeze()) + + if preprocessed_data is None: + return + + X, y = preprocessed_data + X_train, X_test, y_train, y_test = self.split_data_on_train_and_test(X, y.squeeze()) + + class_belongings = Counter(y_train) + logger.info(class_belongings) + + if len(class_belongings) > 2: + logger.info("Multiclass problems are not currently supported.") + return + + # is_dataset_initially_imbalanced = True + + iterator_of_class_belongings = iter(sorted(class_belongings)) + *_, positive_class_label = iterator_of_class_belongings + number_of_positives = class_belongings.get(positive_class_label, None) + + if number_of_positives is None: + logger.error("Unknown positive class label.") + return + + proportion_of_positives = number_of_positives / len(y_train) + + # For extreme case - 0.01, for moderate - 0.2, for mild - 0.4. + # if proportion_of_positives > 0.01: + # coefficient = 0.01 + # updated_number_of_positives = int(coefficient * len(y_train)) + # if len(str(updated_number_of_positives)) < 2: + # logger.info(f"Number of positive class instances is too low.") + # return + # class_belongings[positive_class_label] = updated_number_of_positives + # is_dataset_initially_imbalanced = False + # + # if not is_dataset_initially_imbalanced: + # X_train, y_train = make_imbalance( + # X_train, + # y_train, + # sampling_strategy=class_belongings) + # logger.info("Imbalancing applied.") + + number_of_train_instances_by_class = Counter(y_train) + logger.info(number_of_train_instances_by_class) + + # estimated_dataset_size_in_memory = y_train.memory_usage(deep=True) / (1024 ** 2) + # logger.info(f"Dataset size: {estimated_dataset_size_in_memory}") + + def fit_predict_evaluate(): + self.fit(X_train, y_train, task.target_label, task.name) + y_predictions = self.predict(X_test) + self.examine_quality(y_test, y_predictions, positive_class_label) + # shutil.rmtree("/home/max/ray_results") + # shutil.rmtree("/tmp/ray" + ExceptionWrapper.log_exception(fit_predict_evaluate)() + + def examine_quality(self, y_test, y_pred, pos_label): + f1 = fbeta_score(y_test, y_pred, beta=1, pos_label=pos_label) + logger.info(f"F1: {f1:.3f}") + + balanced_accuracy = balanced_accuracy_score(y_test, y_pred) + logger.info(f"Balanced accuracy: {balanced_accuracy:.3f}") + + recall = recall_score(y_test, y_pred, pos_label=pos_label) + logger.info(f"Recall: {recall:.3f}") + + precision = precision_score(y_test, y_pred, pos_label=pos_label) + logger.info(f"Precision: {precision:.3f}") + + gmean = geometric_mean_score(y_test, y_pred, pos_label=pos_label) + logger.info(f"G-Mean: {gmean:.3f}") + + kappa = cohen_kappa_score(y_test, y_pred) + logger.info(f"Kappa: {kappa:.3f}") + + def _configure_environment(self): + openml.config.set_root_cache_directory("./openml_cache") + + np.random.seed(42) + + os.environ['RAY_IGNORE_UNHANDLED_ERRORS'] = '1' + os.environ['TUNE_DISABLE_AUTO_CALLBACK_LOGGERS'] = '1' + os.environ['TUNE_MAX_PENDING_TRIALS_PG'] = '1' + + logger.info("Prepared env.") + + def preprocess_data(self, X: pd.DataFrame, y: pd.Series) -> Optional[Tuple[pd.DataFrame, pd.Series]]: + X.dropna(inplace=True) + + if type(y.iloc[0]) is str: + label_encoder = LabelEncoder() + y = pd.Series(label_encoder.fit_transform(y)) + + for dataset_feature_name in X.copy(): + dataset_feature = X.get(dataset_feature_name) + + if len(dataset_feature) == 0: + X.drop([dataset_feature_name], axis=1, inplace=True) + continue + if type(dataset_feature.iloc[0]) is str: + dataset_feature_encoded = pd.get_dummies(dataset_feature, prefix=dataset_feature_name) + X.drop([dataset_feature_name], axis=1, inplace=True) + X = pd.concat([X, dataset_feature_encoded], axis=1).reset_index(drop=True) + + if len(X.index) != len(y.index): + logger.warning(f"X index: {X.index} and y index {y.index}.") + logger.error("Unexpected X size.") + return None + + return X, y + + def split_data_on_train_and_test(self, X, y): + return tts( + X, + y, + random_state=42, + test_size=0.2, + stratify=y) + + +class ZenodoExperimentRunner(ExperimentRunner): + def __init__(self): + super().__init__() + self.__datasets = fetch_datasets(data_home='datasets/imbalanced', verbose=True) + + def load_dataset(self, task_id: Optional[int] = None) -> Optional[Dataset]: + for i, (dataset_name, dataset_data) in enumerate(self.__datasets.items()): + # logger.info(i) + if i + 1 == task_id: + return Dataset(id=next(self._id_counter), name=dataset_name, X=dataset_data.get('data'), y=dataset_data.get('target')) + # logger.info(f'i {i}, dataset name {dataset}') + + def define_tasks(self, task_range: Optional[Tuple[int, ...]] = None): + if task_range is None: + task_range = tuple(range(1, len(self.__datasets.keys()))) + logger.info(task_range) + for i in task_range: + self._tasks.append(self.load_dataset(i)) + + +class OpenMLExperimentRunner(ExperimentRunner): + def __init__(self): + super().__init__() + + def load_dataset(self, task_id: Optional[int] = None) -> Optional[Dataset]: + try: + with multiprocessing.Pool(processes=1) as pool: + task = pool.apply_async(openml.tasks.get_task, [task_id]).get(timeout=1800) + dataset = pool.apply_async(task.get_dataset, []).get(timeout=1800) + X, y, categorical_indicator, dataset_feature_names = dataset.get_data( + target=dataset.default_target_attribute) + + except multiprocessing.TimeoutError: + logger.error(f"Fetch from OpenML timed out. Dataset id={task_id} was not loaded.") + return None + except Exception as exc: + logger.error(pprint.pformat(traceback.format_exception(type(exc), exc, exc.__traceback__ ))) + return None + + return Dataset(id=next(self._id_counter), name=dataset.name, target_label=dataset.default_target_attribute, X=X, y=y) + + def define_tasks(self, task_range: Tuple[int, ...] = None): + self._tasks = [] + benchmark_suite = openml.study.get_suite(suite_id=271) + + for i, task_id in enumerate(benchmark_suite.tasks): + # if iteration not in (5, 6, 7, 13, 14, 17, 61, 62, 69): + if task_range is not None and i not in task_range: + continue + + self._tasks.append(self.load_dataset(task_id)) + + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..477a8fe --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,12 @@ +[tool.poetry] +package-mode = false + +[tool.poetry.dependencies] +python = "^3.8.10" + +[tool.poetry.group.dev.dependencies] +"autogluon.tabular" = {version="^1.1.1", python = ">=3.8.10,<3.12"} + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..49ddd42 --- /dev/null +++ b/setup.py @@ -0,0 +1,10 @@ +from setuptools import setup +setup(name='mypackage', + version='0.1', + description='Testing installation of Package', + url='#', + author='malhar', + author_email='mlathkar@gmail.com', + license='MIT', + packages=['domain', 'experiment'], ## here the names + zip_safe=False) diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/decorators.py b/utils/decorators.py new file mode 100644 index 0000000..f2b9b4f --- /dev/null +++ b/utils/decorators.py @@ -0,0 +1,19 @@ +import logging +import pprint +import traceback +from typing import Callable + + +logger = logging.getLogger(__name__) + + +class ExceptionWrapper: + @staticmethod + def log_exception(f: Callable) -> Callable: + def _log_exception(*args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as exc: + logger.error(pprint.pformat(traceback.format_exception(type(exc), exc, exc.__traceback__ ))) + return None + return _log_exception \ No newline at end of file