├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── conda.recipe └── meta.yaml ├── dist ├── gaminet-0.1-py3-none-any.whl ├── gaminet-0.2-py3-none-any.whl ├── gaminet-0.2.1-py3-none-any.whl ├── gaminet-0.3.0-py3-none-any.whl ├── gaminet-0.4.0-py3-none-any.whl ├── gaminet-0.4.1-py3-none-any.whl ├── gaminet-0.5.0-py3-none-any.whl ├── gaminet-0.5.1rc0-py3-none-any.whl ├── gaminet-0.5.2-py3-none-any.whl ├── gaminet-0.5.3-py3-none-any.whl ├── gaminet-0.5.4-py3-none-any.whl ├── gaminet-0.5.5-py3-none-any.whl ├── gaminet-0.5.6-py3-none-any.whl ├── gaminet-0.5.7-py3-none-any.whl └── gaminet-0.5.8-py3-none-any.whl ├── examples ├── Bank_Marketing-demo.ipynb ├── CH.ipynb ├── FicoHeloc.ipynb ├── GAMINet-demo.ipynb ├── bank.csv ├── data_types.json ├── fico │ ├── .ipynb_checkpoints │ │ └── preprocess-checkpoint.ipynb │ ├── data_types.json │ ├── fico.csv │ ├── heloc_data_dictionary-2.xlsx │ ├── heloc_dataset_v1.csv │ ├── load.py │ ├── preprocess.ipynb │ └── test_file1.csv ├── model_saved.pickle └── results │ ├── bank_global.eps │ ├── bank_global.npy │ ├── bank_global.png │ ├── bank_regu.eps │ ├── bank_regu.png │ ├── bank_traj.eps │ ├── bank_traj.png │ ├── ch_global.eps │ ├── ch_global.npy │ ├── ch_global.png │ ├── ch_regu.eps │ ├── ch_regu.png │ ├── ch_traj.eps │ ├── ch_traj.png │ ├── fico_global.eps │ ├── fico_global.npy │ ├── fico_global.png │ ├── fico_regu.eps │ ├── fico_regu.png │ ├── fico_traj.eps │ ├── fico_traj.png │ ├── s1_feature.png │ ├── s1_global.png │ ├── s1_local.png │ ├── s1_regu_plot.png │ └── s1_traj_plot.png ├── gaminet ├── __init__.py ├── gaminet.py ├── interpret.py ├── layers.py ├── lib │ ├── interpret-inline.js │ ├── lib_ebmcore_linux_x64.so │ ├── lib_ebmcore_mac_x64.dylib │ ├── lib_ebmcore_win_x64.dll │ └── lib_ebmcore_win_x64.pdb └── utils.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | examples/.ipynb_checkpoints/* 2 | scripts/* 3 | .ipynb_checkpoints/* 4 | gaminet/__pycache__/* 5 | interpret/*.ipynb 6 | build/* 7 | gaminet.egg-info/* 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GAMI-Net 2 | Generalized additive models with structured interactions 3 | 4 | ## Installation 5 | 6 | The following environments are required: 7 | 8 | - Python 3.7 + (anaconda is preferable) 9 | - tensorflow>=2.0.0 10 | - tensorflow-lattice>=2.0.8 11 | - numpy>=1.15.2 12 | - pandas>=0.19.2 13 | - matplotlib>=3.1.3 14 | - scikit-learn>=0.23.0 15 | 16 | ```shell 17 | pip install gaminet 18 | ``` 19 | 20 | To use it on GPU, conda install tensorflow==2.2, pip install tensorflow-lattice==2.0.8, conda install tensorflow-estimators==2.2 21 | 22 | ## Usage 23 | 24 | Import library 25 | ```python 26 | import os 27 | import numpy as np 28 | import tensorflow as tf 29 | from sklearn.preprocessing import MinMaxScaler 30 | from sklearn.model_selection import train_test_split 31 | 32 | from gaminet import GAMINet 33 | from gaminet.utils import local_visualize 34 | from gaminet.utils import global_visualize_density 35 | from gaminet.utils import feature_importance_visualize 36 | from gaminet.utils import plot_trajectory 37 | from gaminet.utils import plot_regularization 38 | ``` 39 | 40 | Load data 41 | ```python 42 | def metric_wrapper(metric, scaler): 43 | def wrapper(label, pred): 44 | return metric(label, pred, scaler=scaler) 45 | return wrapper 46 | 47 | def rmse(label, pred, scaler): 48 | pred = scaler.inverse_transform(pred.reshape([-1, 1])) 49 | label = scaler.inverse_transform(label.reshape([-1, 1])) 50 | return np.sqrt(np.mean((pred - label)**2)) 51 | 52 | def data_generator1(datanum, dist="uniform", random_state=0): 53 | 54 | nfeatures = 100 55 | np.random.seed(random_state) 56 | x = np.random.uniform(0, 1, [datanum, nfeatures]) 57 | x1, x2, x3, x4, x5, x6 = [x[:, [i]] for i in range(6)] 58 | 59 | def cliff(x1, x2): 60 | # x1: -20,20 61 | # x2: -10,5 62 | x1 = (2 * x1 - 1) * 20 63 | x2 = (2 * x2 - 1) * 7.5 - 2.5 64 | term1 = -0.5 * x1 ** 2 / 100 65 | term2 = -0.5 * (x2 + 0.03 * x1 ** 2 - 3) ** 2 66 | y = 10 * np.exp(term1 + term2) 67 | return y 68 | 69 | y = (8 * (x1 - 0.5) ** 2 70 | + 0.1 * np.exp(-8 * x2 + 4) 71 | + 3 * np.sin(2 * np.pi * x3 * x4) 72 | + cliff(x5, x6)).reshape([-1,1]) + 1 * np.random.normal(0, 1, [datanum, 1]) 73 | 74 | task_type = "Regression" 75 | meta_info = {"X" + str(i + 1):{'type':'continuous'} for i in range(nfeatures)} 76 | meta_info.update({'Y':{'type':'target'}}) 77 | for i, (key, item) in enumerate(meta_info.items()): 78 | if item['type'] == 'target': 79 | sy = MinMaxScaler((0, 1)) 80 | y = sy.fit_transform(y) 81 | meta_info[key]['scaler'] = sy 82 | else: 83 | sx = MinMaxScaler((0, 1)) 84 | sx.fit([[0], [1]]) 85 | x[:,[i]] = sx.transform(x[:,[i]]) 86 | meta_info[key]['scaler'] = sx 87 | 88 | train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.2, random_state=random_state) 89 | return train_x, test_x, train_y, test_y, task_type, meta_info, metric_wrapper(rmse, sy) 90 | 91 | train_x, test_x, train_y, test_y, task_type, meta_info, get_metric = data_generator1(10000, 0) 92 | ``` 93 | 94 | Run GAMI-Net 95 | ```python 96 | ## Note the current GAMINet API requires input features being normalized within 0 to 1. 97 | model = GAMINet(meta_info=meta_info, interact_num=20, 98 | interact_arch=[40] * 5, subnet_arch=[40] * 5, 99 | batch_size=200, task_type=task_type, activation_func=tf.nn.relu, 100 | main_effect_epochs=5000, interaction_epochs=5000, tuning_epochs=500, 101 | lr_bp=[0.0001, 0.0001, 0.0001], early_stop_thres=[50, 50, 50], 102 | heredity=True, loss_threshold=0.01, reg_clarity=1, 103 | mono_increasing_list=[], mono_decreasing_list=[], ## the indices list of features 104 | verbose=False, val_ratio=0.2, random_state=random_state) 105 | 106 | model.fit(train_x, train_y) 107 | 108 | val_x = train_x[model.val_idx, :] 109 | val_y = train_y[model.val_idx, :] 110 | tr_x = train_x[model.tr_idx, :] 111 | tr_y = train_y[model.tr_idx, :] 112 | pred_train = model.predict(tr_x) 113 | pred_val = model.predict(val_x) 114 | pred_test = model.predict(test_x) 115 | gaminet_stat = np.hstack([np.round(get_metric(tr_y, pred_train),5), 116 | np.round(get_metric(val_y, pred_val),5), 117 | np.round(get_metric(test_y, pred_test),5)]) 118 | print(gaminet_stat) 119 | ``` 120 | 121 | Training Logs 122 | ```python 123 | simu_dir = "./results/" 124 | if not os.path.exists(simu_dir): 125 | os.makedirs(simu_dir) 126 | 127 | data_dict_logs = model.summary_logs(save_dict=False) 128 | plot_trajectory(data_dict_logs, folder=simu_dir, name="s1_traj_plot", log_scale=True, save_png=True) 129 | plot_regularization(data_dict_logs, folder=simu_dir, name="s1_regu_plot", log_scale=True, save_png=True) 130 | ``` 131 | ![traj_visu_demo](https://github.com/ZebinYang/gaminet/blob/master/examples/results/s1_traj_plot.png) 132 | ![regu_visu_demo](https://github.com/ZebinYang/gaminet/blob/master/examples/results/s1_regu_plot.png) 133 | 134 | Global Visualization 135 | ```python 136 | data_dict = model.global_explain(save_dict=False) 137 | global_visualize_density(data_dict, save_png=True, folder=simu_dir, name='s1_global') 138 | ``` 139 | ![global_visu_demo](https://github.com/ZebinYang/gaminet/blob/master/examples/results/s1_global.png) 140 | 141 | Feature Importance 142 | ```python 143 | feature_importance_visualize(data_dict, save_png=True, folder=simu_dir, name='s1_feature') 144 | ``` 145 | 146 | 147 | Local Visualization 148 | ```python 149 | data_dict_local = model.local_explain(train_x[:10], train_y[:10], save_dict=False) 150 | local_visualize(data_dict_local[0], save_png=True, folder=simu_dir, name='s1_local') 151 | ``` 152 | 153 | 154 | ## Citations 155 | ---------- 156 | 157 | ```latex 158 | @article{yang2021gami, 159 | title={GAMI-Net: An Explainable Neural Network based on Generalized Additive Models with Structured Interactions}, 160 | author={Yang, Zebin and Zhang, Aijun and Sudjianto, Agus}, 161 | journal={Pattern Recognition}, 162 | volume = {120}, 163 | pages = {108192}, 164 | year={2021} 165 | } 166 | ``` 167 | -------------------------------------------------------------------------------- /conda.recipe/meta.yaml: -------------------------------------------------------------------------------- 1 | package: 2 | name: gaminet 3 | version: "0.1" 4 | 5 | source: 6 | - path: ../ 7 | 8 | build: 9 | noarch: python 10 | number: 0 11 | script: "{{ PYTHON }} -m pip install . -vv" 12 | 13 | 14 | requirements: 15 | host: 16 | - pip 17 | - python 18 | 19 | run: 20 | - python>=3.7 21 | - numpy>=1.15.2 22 | - matplotlib>=3.1.3 23 | - tensorflow>=2.0.0 24 | - pandas>=0.19.2 25 | - scikit-learn>=0.23.0 26 | 27 | tests: 28 | imports: 29 | - gaminet 30 | 31 | about: 32 | home: https://github.com/ZebinYang/gaminet 33 | license: GPL 34 | summary: Generalized additive model with pairwise interactions 35 | -------------------------------------------------------------------------------- /dist/gaminet-0.1-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.1-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.2-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.2-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.2.1-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.2.1-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.3.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.3.0-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.4.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.4.0-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.4.1-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.4.1-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.0-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.1rc0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.1rc0-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.2-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.2-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.3-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.3-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.4-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.4-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.5-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.5-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.6-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.6-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.7-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.7-py3-none-any.whl -------------------------------------------------------------------------------- /dist/gaminet-0.5.8-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/dist/gaminet-0.5.8-py3-none-any.whl -------------------------------------------------------------------------------- /examples/data_types.json: -------------------------------------------------------------------------------- 1 | {"age":{"type":"continuous"}, 2 | "job":{"type":"categorical"}, 3 | "marital":{"type":"categorical"}, 4 | "education":{"type":"categorical"}, 5 | "default":{"type":"categorical"}, 6 | "balance":{"type":"continuous"}, 7 | "housing":{"type":"categorical"}, 8 | "loan":{"type":"categorical"}, 9 | "contact":{"type":"categorical"}, 10 | "day":{"type":"continuous"}, 11 | "month":{"type":"categorical"}, 12 | "duration":{"type":"continuous"}, 13 | "campaign":{"type":"continuous"}, 14 | "pdays":{"type":"continuous"}, 15 | "previous":{"type":"continuous"}, 16 | "poutcome":{"type":"categorical"}, 17 | "term deposit":{"type":"target"}} -------------------------------------------------------------------------------- /examples/fico/.ipynb_checkpoints/preprocess-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2020-05-27T04:16:46.019095Z", 9 | "start_time": "2020-05-27T04:08:26.163560Z" 10 | } 11 | }, 12 | "outputs": [ 13 | { 14 | "name": "stdout", 15 | "output_type": "stream", 16 | "text": [ 17 | "Column being fixed: 1\n", 18 | "Column being fixed: 8\n", 19 | "Column being fixed: 14\n", 20 | "Column being fixed: 17\n", 21 | "Column being fixed: 18\n", 22 | "Column being fixed: 19\n", 23 | "Column being fixed: 20\n", 24 | "Column being fixed: 21\n", 25 | "Column being fixed: 22\n" 26 | ] 27 | } 28 | ], 29 | "source": [ 30 | "# --- Imports section --- \n", 31 | "import numpy as np\n", 32 | "import pandas as pd\n", 33 | "from sklearn.preprocessing import StandardScaler\n", 34 | "from sklearn import datasets, linear_model, preprocessing\n", 35 | "import copy\n", 36 | "\n", 37 | "class ModelError(Exception):\n", 38 | "\tpass\n", 39 | "\n", 40 | "class Data_Cleaner():\n", 41 | "\n", 42 | "\tdef __init__ (self, file_name, data = None):\n", 43 | "\t# --- Retrieves the data from CSV or array, as well as basic organisation ---\n", 44 | "\n", 45 | "\t\t# -- Get data from CSV or given array --\n", 46 | "\t\tif (data == None):\n", 47 | "\t\t\tself.data_set = pd.read_csv(file_name).values\n", 48 | "\n", 49 | "\t\telse:\n", 50 | "\t\t\tself.data_set = data\n", 51 | "\n", 52 | "\t\t# -- Converting target to binary --\n", 53 | "\t\tnp.place(self.data_set, self.data_set == \"Bad\", 0)\n", 54 | "\t\tnp.place(self.data_set, self.data_set == \"Good\", 1)\n", 55 | "\n", 56 | "\t\t# -- Creating Model Variable -- \n", 57 | "\t\tself.model = None\n", 58 | "\n", 59 | "\t\t# -- Creating an Order Column --\n", 60 | "\t\torder = np.arange(self.data_set.shape[0])\n", 61 | "\t\torder = order.reshape((order.shape[0],1))\n", 62 | "\n", 63 | "\t\t# -- Scale and Split --\n", 64 | "\t\t# self.y = self.data_set[:,:1]\n", 65 | "\t\t# scaler = StandardScaler()\n", 66 | "\t\t# self.X = scaler.fit_transform(self.data_set[:,1:])\n", 67 | "\n", 68 | "\t\tself.y = self.data_set[:,:1]\n", 69 | "\t\tself.X = self.data_set[:,1:]\n", 70 | "\n", 71 | "\n", 72 | "\t\t# -- Needs to be retained for inserting new samples\n", 73 | "\t\t# self.mean = scaler.mean_\n", 74 | "\t\t# self.scale = scaler.scale_\n", 75 | "\n", 76 | "\t\t# -- Assiging general useful variables --\n", 77 | "\t\tself.num_samples , self.num_features = self.X.shape\n", 78 | "\n", 79 | "\t\t# -- Add the Order Column -- \n", 80 | "\t\tself.X = np.append(order,self.X,axis=1)\n", 81 | "\t\tself.y = np.append(order,self.y,axis=1)\n", 82 | "\n", 83 | "\tdef shift(self):\n", 84 | "\t# --- Perform the shift for the two categorical features --- \n", 85 | "\n", 86 | "\t\t# -- Shift is hardcoded based on requirements -- \n", 87 | "\t\tfirst_col = self.X[:,10]\n", 88 | "\t\tnp.place(first_col, first_col == 1, 100) # hold value\n", 89 | "\t\tnp.place(first_col, first_col == 6, 1)\n", 90 | "\t\tnp.place(first_col, first_col == 5, 1)\n", 91 | "\t\tnp.place(first_col, first_col == 4, 6)\n", 92 | "\t\tnp.place(first_col, first_col == 3, 5)\n", 93 | "\t\tnp.place(first_col, first_col == 2, 4)\n", 94 | "\t\tnp.place(first_col, first_col == 100, 3)\n", 95 | "\t\tnp.place(first_col, first_col == 0, 2)\n", 96 | "\t\tnp.place(first_col, first_col == 8, 0)\n", 97 | "\t\tnp.place(first_col, first_col == 9, 0)\n", 98 | "\n", 99 | "\t\tsecond_col= self.X[:,11]\n", 100 | "\t\tnp.place(second_col, second_col == 1, 0)\n", 101 | "\t\tnp.place(second_col, second_col == 9, 0)\n", 102 | "\t\tnp.place(second_col, second_col == 7, 1)\n", 103 | "\t\tnp.place(second_col, second_col == 8, 7)\n", 104 | "\n", 105 | "\t\tself.X[:,10] = first_col\n", 106 | "\t\tself.X[:,11] = second_col\n", 107 | "\n", 108 | "\tdef __scaled_row(self,row,scaler):\n", 109 | "\t# --- Returns the Row Scaled ---\n", 110 | "\t\tmean = scaler.mean_\n", 111 | "\t\tscale = scaler.scale_\n", 112 | "\t\tscld = []\n", 113 | "\t\tfor k in range(row.shape[0]):\n", 114 | "\t\t\tscld.append((row[k] - mean[k])/scale[k])\n", 115 | "\t\tscld = np.array(scld)\n", 116 | "\n", 117 | "\t\treturn scld\n", 118 | "\t \n", 119 | "\tdef __masked_arr(self,orig_array, mask):\n", 120 | "\t# --- Returns XOR of Array and Mask --- \n", 121 | "\t\tmasked_array = []\n", 122 | "\n", 123 | "\t\tfor i in range(len(orig_array)):\n", 124 | "\t\t\trow = []\n", 125 | "\t\t\tfor j in range(len(orig_array[0])):\n", 126 | "\t\t\t\tif mask[j] != 0:\n", 127 | "\t\t\t\t\trow.append(orig_array[i][j])\n", 128 | "\t\t\tmasked_array.append(row)\n", 129 | "\n", 130 | "\t\tmasked_array = np.array(masked_array)\n", 131 | "\n", 132 | "\t\treturn masked_array\n", 133 | "\n", 134 | "\tdef __euc_distance(self,row1, row2):\n", 135 | "\t# --- Returns Euclidian Distance between Rows --- \n", 136 | "\t\tdist = 0\n", 137 | "\t\tfor i in range(len(row1)):\n", 138 | "\t\t\tt = (row1[i]-row2[i])**2\n", 139 | "\t\t\tdist += t\n", 140 | "\t\tdist = np.sqrt(dist)\n", 141 | "\t\treturn dist\n", 142 | "\n", 143 | "\tdef __predict_feature_weighted(self,row, good_data_masked, no_neighbours, orig_array, ft_idx):\n", 144 | "\t# --- Returns the single special value replaced by kNN imputation using weights---\n", 145 | "\n", 146 | "\t\tdistances = []\n", 147 | "\t\t# -- Loops through the good data with no special values -- \n", 148 | "\t\t\t# - Good data has the changing feature removed -\n", 149 | "\t\tfor i in range(len(good_data_masked)):\t\n", 150 | "\t\t\tdistances.append(self.__euc_distance(row, good_data_masked[i]))\n", 151 | "\n", 152 | "\t\tdistances = np.array(distances)\n", 153 | "\t\tmax_dist = np.max(distances)\n", 154 | "\t \n", 155 | "\t\t# -- Sorts the first no_neigbours features --\n", 156 | "\t\tidx = np.argpartition(distances, no_neighbours)\n", 157 | "\n", 158 | "\t\tvalues = []\n", 159 | "\t\tmin_dists = []\n", 160 | "\t \n", 161 | "\t\t# -- Retrieving values with which to replace -- \n", 162 | "\t\tfor i in range(no_neighbours):\n", 163 | "\t\t\tvalues.append(orig_array[idx[i]][ft_idx])\n", 164 | "\t\t\tmin_dists.append(distances[idx[i]])\n", 165 | "\n", 166 | "\t\tvalues = np.array(values) \n", 167 | "\t\tmin_dists = np.array(min_dists)\n", 168 | "\n", 169 | "\t\t# -- Assigning the weights -- \n", 170 | "\t\tweights = []\n", 171 | "\t\tfor i in min_dists:\n", 172 | "\t\t\tweights.append(1 - (i/max_dist))\n", 173 | "\t \n", 174 | "\t # -- Calculating final result -- \n", 175 | "\t\timputed_val = 0\n", 176 | "\t\tfor i in range(len(weights)):\n", 177 | "\t\t\timputed_val += weights[i] * values[i]\n", 178 | "\t \n", 179 | "\t\treturn imputed_val \n", 180 | "\n", 181 | "\tdef __predict_feature_mean(self,row, good_data_masked, no_neighbours, orig_array, ft_idx):\n", 182 | "\t# --- Returns the single special value replaced by kNN imputation using the mean ---\n", 183 | "\n", 184 | "\t\tdistances = []\n", 185 | "\t\t# -- Loops through the good data with no special values -- \n", 186 | "\t \t# - Good data has the changing feature removed -\n", 187 | "\t\tfor i in range(len(good_data_masked)):\n", 188 | "\t\t\tdistances.append(self.__euc_distance(row,good_data_masked[i]))\n", 189 | "\t\tdistances = np.array(distances)\n", 190 | "\t \n", 191 | "\t\t# -- Sorts the first no_neigbours features --\n", 192 | "\t\tidx = np.argpartition(distances, no_neighbours)\n", 193 | "\n", 194 | "\t\tvalues = []\n", 195 | "\t\tmin_dists = []\n", 196 | "\t \n", 197 | "\t\t# -- Retrieving values with which to replace -- \n", 198 | "\t\tfor i in range(no_neighbours):\n", 199 | "\t\t\tvalues.append(orig_array[idx[i]][ft_idx])\n", 200 | "\t\t\tmin_dists.append(distances[idx[i]])\n", 201 | "\n", 202 | "\t\tvalues = np.array(values) \n", 203 | "\t\tmin_dists = np.array(min_dists)\n", 204 | "\t \n", 205 | "\t\t# -- Calculating final result -- \n", 206 | "\t\timputed_val = 0\n", 207 | "\t\tfor i in range(len(values)):\n", 208 | "\t\t\timputed_val += values[i]\n", 209 | "\n", 210 | "\t\timputed_val = imputed_val/len(values)\n", 211 | "\n", 212 | "\t\treturn imputed_val\n", 213 | "\n", 214 | "\tdef __remove_row_with_vals(self, data, target, vals):\n", 215 | "\t# --- Returns the data/target without the rows that have any instance of vals list ---\n", 216 | "\t\tremoved_data = []\n", 217 | "\t\tremoved_target = []\n", 218 | "\n", 219 | "\t\trow_no = 0 \n", 220 | "\t\tfor row in data:\n", 221 | "\t\t\tfor col in row:\n", 222 | "\t\t\t\tif (col in vals):\n", 223 | "\t\t\t\t\tremoved_data.append(data[row_no])\n", 224 | "\t\t\t\t\tdata = np.delete(data, row_no, 0)\n", 225 | "\n", 226 | "\t\t\t\t\tremoved_target.append(target[row_no])\n", 227 | "\t\t\t\t\ttarget = np.delete(target, row_no, 0) \n", 228 | "\t\t\t\t\trow_no -= 1\n", 229 | "\t\t\t\t\tbreak\n", 230 | "\t\t\trow_no += 1\n", 231 | "\n", 232 | "\t\tremoved_data = np.array(removed_data)\n", 233 | "\t\tremoved_target = np.array(removed_target)\n", 234 | "\n", 235 | "\t\treturn data, target, removed_data, removed_target\n", 236 | "\n", 237 | "\tdef __remove_col_with_vals(self, data, vals):\n", 238 | "\t# --- Returns the data without the coloumns that have the desired special values ---\n", 239 | "\t\tno_cols = data.shape[1]\n", 240 | "\t\tno_rows = data.shape[0]\n", 241 | "\t\trow = 0\n", 242 | "\t\twhile (no_rows > row):\n", 243 | "\t\t\tcol = 0\n", 244 | "\t\t\twhile (no_cols > col):\n", 245 | "\t\t\t\tif (data[row][col] in vals):\n", 246 | "\t\t\t\t\tdata = np.delete(data, col, 1)\n", 247 | "\t\t\t\t\tno_cols -= 1\n", 248 | "\t\t\t\telse:\n", 249 | "\t\t\t\t\tcol += 1\n", 250 | "\t\t\trow += 1 \n", 251 | "\t\treturn data\n", 252 | "\n", 253 | "\tdef __predict_values_lin_reg(self,X_tr,y_tr,X_test):\n", 254 | "\t# --- Uses linear regression to extrapolate values ---\n", 255 | "\t\tmodel = linear_model.LinearRegression()\n", 256 | "\t\tmodel.fit(X_tr, y_tr)\n", 257 | "\t\tpred = model.predict(X_test)\n", 258 | "\t\treturn pred\n", 259 | "\n", 260 | "\tdef __data_spliter(self,all_data,target_col,target_val):\n", 261 | "\t# --- Splits the data such to identify target col --- \n", 262 | "\t\ttarget_col += 1\n", 263 | "\n", 264 | "\t\ty = all_data[:,target_col:target_col+1]\n", 265 | "\t\tX = np.delete(all_data,target_col,1)\n", 266 | "\t \n", 267 | "\t\t# -- Will hold the X for the y values that need to be predicted--\n", 268 | "\t\tX_target = np.zeros((1,X.shape[1]))\n", 269 | "\n", 270 | "\t\trow_no = 0 \n", 271 | "\t\t# -- Finds the rows with a target val -- \n", 272 | "\t\tfor val in y:\n", 273 | "\t\t\tif (val[0] == target_val):\n", 274 | "\t\t\t\tX_target = np.append(X_target,X[row_no:row_no+1,:],axis=0)\n", 275 | "\t\t\t\tX = np.delete(X, row_no, 0)\n", 276 | "\t\t\t\ty = np.delete(y, row_no, 0) \n", 277 | "\t\t\telse:\n", 278 | "\t\t\t\trow_no += 1\n", 279 | "\n", 280 | "\t\tX_target = np.delete(X_target,0,0)\n", 281 | "\t \n", 282 | "\t\treturn X,y,X_target # Note that the order column is still attached\n", 283 | "\n", 284 | "\tdef __combine_parts_inorder(self,X,y,X_target,y_target,target_col):\n", 285 | "\t# --- Combines all the small parts into a single data matrix ---\n", 286 | "\t\ttarget_col += 1 # To account for the order column\n", 287 | "\n", 288 | "\t\ty_target = y_target.reshape((y_target.shape[0],1))\n", 289 | "\t\ty_full = np.append(y_target,y,axis=0)\n", 290 | "\t\tX_full = np.append(X_target,X,axis=0)\n", 291 | "\n", 292 | "\t\tdata = np.append(X_full[:,:target_col],y_full,axis=1)\n", 293 | "\t\tdata = np.append(data,X_full[:,target_col:],axis=1)\n", 294 | "\t\treturn data\n", 295 | "\n", 296 | "\tdef __average_each_feature(self,X):\n", 297 | "\t# --- Finds the mean values for each feature ---\n", 298 | "\n", 299 | "\t\tX_target = np.zeros((1,X.shape[1]))\n", 300 | "\t \n", 301 | "\t\tfor i in range(X.shape[1]):\n", 302 | "\t\t\tcol = X[:,i]\n", 303 | "\t\t\tcol = np.mean(col,axis=0)\n", 304 | "\t\t\tX_target[:,i] = col\n", 305 | "\t \n", 306 | "\t\treturn X_target\n", 307 | "\n", 308 | "\tdef __process_and_predict(self,all_data,target_col,target_val,exclude=None,model=\"linear\"):\n", 309 | "\t\t# -- Split data --\n", 310 | "\t\tX,y,X_target = self.__data_spliter(all_data,target_col,target_val)\n", 311 | "\t\t# -- Record order columns -- \n", 312 | "\n", 313 | "\t\torder_data = X[:,0:1]\n", 314 | "\t\torder_target = X_target[:,0:1]\n", 315 | "\t \n", 316 | "\t # -- Remove certain columns --\n", 317 | "\t\tif (exclude != None or exclude == []):\n", 318 | "\t\t\ty_tr = np.copy(y)\n", 319 | "\t\t\tX_tr = self.__remove_col_with_vals(X,exclude)\n", 320 | "\t\t\tX_tr = np.delete(X_tr,0,axis=1) # Removes the order column\n", 321 | "\t\t\tX_pred = self.__remove_col_with_vals(X_target,exclude) # The x used to predict\n", 322 | "\t\t\tX_pred = np.delete(X_pred,0,axis=1)\n", 323 | "\n", 324 | "\n", 325 | "\t\telse:\n", 326 | "\t\t\ty_tr = np.copy(y)\n", 327 | "\t\t\tX_tr = np.delete(X,0,axis=1) # Removes the order column\n", 328 | "\t\t\tX_pred = np.delete(X_target,0,axis=1)\n", 329 | "\n", 330 | "\n", 331 | "\t # -- Run regression --\n", 332 | "\t\tif (model == \"linear\"):\n", 333 | "\t\t\ty_target = self.__predict_values_lin_reg(X_tr,y_tr,X_pred)\n", 334 | "\n", 335 | "\t\telif (model == \"polynomial\"):\n", 336 | "\t\t\tpass\n", 337 | "\n", 338 | "\t\telif (model == \"special\"):\n", 339 | "\t\t\tX_avg = self.__average_each_feature(X_pred)\n", 340 | "\t\t\tpred = self.__predict_values_lin_reg(X_tr,y_tr,X_avg)\n", 341 | "\t \n", 342 | "\t\telse:\n", 343 | "\t\t\traise ModelError(\"Model currently not available\")\n", 344 | "\t \n", 345 | "\t\tfinal_data = self.__combine_parts_inorder(X,y,X_target,y_target,target_col)\n", 346 | "\t\treturn final_data\n", 347 | "\t# --- Processes the data and uses linear regression to extrapolate --- \n", 348 | "\n", 349 | "\tdef remove_8(self, kNN, prediction_type):\n", 350 | "\t# --- Removes all the -8 values using kNN imputation ---\n", 351 | "\t\t# -- Remove the order column -- \n", 352 | "\t\torder = self.X[:,0]\n", 353 | "\t\torder = order.reshape((order.shape[0],1))\n", 354 | "\t\tself.X = np.delete(self.X, 0, axis = 1)\n", 355 | "\n", 356 | "\t\t# -- Removes all special values (-7,-8,-9) --\n", 357 | "\t\tX_good, hold1, hold2, hold3 = self.__remove_row_with_vals(self.X, self.y, [-7,-8,-9])\n", 358 | "\n", 359 | "\t\tscaler = StandardScaler()\n", 360 | "\t\tX_good_scaled = scaler.fit_transform(X_good)\n", 361 | "\n", 362 | "\t\t# -- Create a copy of the data matrix X to edit -- \n", 363 | "\t\tX_no_8 = np.copy(self.X)\n", 364 | "\n", 365 | "\t\tcols_with_8 = [1,8,14,17,18,19,20,21,22]\n", 366 | "\n", 367 | "\t\t# -- Fixing each -8 column -- \n", 368 | "\t\tfor fix_col in cols_with_8:\n", 369 | "\t\t\tprint(\"Column being fixed:\", str(fix_col))\n", 370 | "\t\t\t# -- Looping through all samples -- \n", 371 | "\t\t\tfor row in range(self.num_samples):\n", 372 | "\n", 373 | "\t\t\t\tif self.X[row][fix_col] == -8:\n", 374 | "\t\t\t\t\trow_to_comp = []\n", 375 | "\t\t\t\t\tmask = []\n", 376 | "\t\t\t\t\tscaled = self.__scaled_row(self.X[row],scaler)\n", 377 | "\n", 378 | "\t\t\t\t\t# -- Looping through each value --\n", 379 | "\t\t\t\t\tfor col in range(self.num_features):\n", 380 | "\t\t\t\t\t\tif self.X[row][col] >= 0:\n", 381 | "\t\t\t\t\t\t\tmask.append(1)\n", 382 | "\t\t\t\t\t\t\trow_to_comp.append(scaled[col])\n", 383 | "\t\t\t\t\t\telse:\n", 384 | "\t\t\t\t\t\t\tmask.append(0)\n", 385 | "\n", 386 | "\t\t\t\t\trow_to_comp = np.array(row_to_comp)\n", 387 | "\t\t\t\t\tmask = np.array(mask)\n", 388 | "\t\t \n", 389 | "\t\t\t\t\t# -- Getting the array of samples without special values in the good datasets-- \n", 390 | "\t\t\t\t\tX_good_masked = self.__masked_arr(X_good_scaled, mask)\n", 391 | "\n", 392 | "\t\t\t\t\tif (prediction_type == \"mean\"):\n", 393 | "\t\t\t\t\t\timputed = self.__predict_feature_mean(row_to_comp, X_good_masked, kNN, X_good_scaled, fix_col)\n", 394 | "\n", 395 | "\t\t\t\t\telif (prediction_type == \"weighted\"):\n", 396 | "\t\t\t\t\t\timputed = self.__predict_feature_weighted(row_to_comp, X_good_masked, kNN, X_good_scaled, fix_col)\n", 397 | "\t\t\t\t\t\n", 398 | "\t\t\t\t\tX_no_8[row][fix_col] = imputed*scaler.scale_[fix_col] + scaler.mean_[fix_col]\n", 399 | "\n", 400 | "\t\tself.X = X_no_8\n", 401 | "\n", 402 | "\t\t# -- Add back order column -- \n", 403 | "\t\tself.X = np.append(order,self.X,axis=1)\n", 404 | "\n", 405 | "\tdef remove_all_9(self):\n", 406 | "\t# --- Removes the columns with all -9 values -- \n", 407 | "\t\tself.rem_X = []\n", 408 | "\t\tself.rem_y = []\n", 409 | "\t\trow_no = 0 \n", 410 | "\t\tfor row in self.X:\n", 411 | "\t\t\tfor col_i in range(1,row.shape[0]):\n", 412 | "\t\t\t\tif (row[col_i] == -9):\n", 413 | "\t\t\t\t\tremove = True\n", 414 | "\t\t\t\telse:\n", 415 | "\t\t\t\t\tremove = False\n", 416 | "\t\t\t\t\tbreak\n", 417 | "\t\t\tif remove:\n", 418 | "\t\t\t\tself.rem_X.append(self.X[row_no])\n", 419 | "\t\t\t\tself.X = np.delete(self.X, row_no, 0)\n", 420 | "\n", 421 | "\t\t\t\tself.rem_y.append(self.y[row_no])\n", 422 | "\t\t\t\tself.y = np.delete(self.y, row_no, 0) \n", 423 | "\n", 424 | "\t\t\telse:\n", 425 | "\t\t\t\trow_no += 1\n", 426 | "\n", 427 | "\t\tself.rem_X = np.array(self.rem_X)\n", 428 | "\t\tself.rem_y = np.array(self.rem_y)\n", 429 | "\n", 430 | "\tdef remove_9(self):\n", 431 | "\t# --- Removes the -9 values by using linear regression ---\n", 432 | "\t\tself.X = self.__process_and_predict(self.X,0,-9,[-7])\n", 433 | "\n", 434 | "\tdef remove_7_est(self):\n", 435 | "\t# --- Removes the -7 values by using an approximated value ---\n", 436 | "\t\tvalue_replace = 150\n", 437 | "\t\tnp.place(self.X, self.X == -7, value_replace)\n", 438 | "\n", 439 | "\tdef output_all_data(self):\n", 440 | "\t# --- Combines all the data into a single array in order and outputs it ---\n", 441 | "\t\tall_X = np.append(self.X,self.rem_X,axis=0)\n", 442 | "\t\tall_y = np.append(self.y,self.rem_y,axis=0)\n", 443 | "\n", 444 | "\t\tall_X = all_X[all_X[:,0].argsort()]\n", 445 | "\t\tall_y = all_y[all_y[:,0].argsort()]\n", 446 | "\n", 447 | "\t\tall_X = np.delete(all_X, 0, axis=1) \n", 448 | "\t\tall_y = np.delete(all_y, 0, axis=1) \n", 449 | "\t\t\n", 450 | "\t\tdata_output = np.append(all_y,all_X,axis=1)\n", 451 | "\n", 452 | "\t\treturn data_output\n", 453 | "\n", 454 | "\tdef output_to_CSV(self, filename):\n", 455 | "\t# --- Outputs the data to a CSV according to assigned filename --- \n", 456 | "\t\tdata_output = self.output_all_data()\n", 457 | "\n", 458 | "\t\tnp.savetxt(filename, data_output.astype(int), fmt='%i', delimiter=\",\")\n", 459 | "\n", 460 | "\tdef revert_to_original(self):\n", 461 | "\t# --- Allows to retrieve the original dataset ---\n", 462 | "\t\tself.__init__(\"pass\",self.data_set)\n", 463 | "\n", 464 | "testing123 = Data_Cleaner(\"./heloc_dataset_v1.csv\")\n", 465 | "testing123.shift()\n", 466 | "testing123.remove_8(5,\"mean\")\n", 467 | "testing123.remove_all_9()\n", 468 | "testing123.remove_9()\n", 469 | "testing123.remove_7_est()\n", 470 | "testing123.output_to_CSV(\"test_file1.csv\")" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": 69, 476 | "metadata": { 477 | "ExecuteTime": { 478 | "end_time": "2020-05-28T02:34:55.972490Z", 479 | "start_time": "2020-05-28T02:34:55.852496Z" 480 | } 481 | }, 482 | "outputs": [], 483 | "source": [ 484 | "pd.DataFrame(np.hstack([testing123.X, testing123.y])).to_csv(\"fico.csv\")" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": 74, 490 | "metadata": { 491 | "ExecuteTime": { 492 | "end_time": "2020-05-28T02:36:57.680689Z", 493 | "start_time": "2020-05-28T02:36:57.624935Z" 494 | } 495 | }, 496 | "outputs": [], 497 | "source": [ 498 | "data = pd.read_csv(\"fico.csv\", index_col=[0, 1])\n", 499 | "x, y = data.iloc[:,0:].values, data.iloc[:,[-1]].values" 500 | ] 501 | } 502 | ], 503 | "metadata": { 504 | "kernelspec": { 505 | "display_name": "Python (tf2)", 506 | "language": "python", 507 | "name": "tf2" 508 | }, 509 | "language_info": { 510 | "codemirror_mode": { 511 | "name": "ipython", 512 | "version": 3 513 | }, 514 | "file_extension": ".py", 515 | "mimetype": "text/x-python", 516 | "name": "python", 517 | "nbconvert_exporter": "python", 518 | "pygments_lexer": "ipython3", 519 | "version": "3.6.8" 520 | }, 521 | "latex_envs": { 522 | "LaTeX_envs_menu_present": true, 523 | "autoclose": false, 524 | "autocomplete": true, 525 | "bibliofile": "biblio.bib", 526 | "cite_by": "apalike", 527 | "current_citInitial": 1, 528 | "eqLabelWithNumbers": true, 529 | "eqNumInitial": 1, 530 | "hotkeys": { 531 | "equation": "Ctrl-E", 532 | "itemize": "Ctrl-I" 533 | }, 534 | "labels_anchors": false, 535 | "latex_user_defs": false, 536 | "report_style_numbering": false, 537 | "user_envs_cfg": false 538 | }, 539 | "varInspector": { 540 | "cols": { 541 | "lenName": 16, 542 | "lenType": 16, 543 | "lenVar": 40 544 | }, 545 | "kernels_config": { 546 | "python": { 547 | "delete_cmd_postfix": "", 548 | "delete_cmd_prefix": "del ", 549 | "library": "var_list.py", 550 | "varRefreshCmd": "print(var_dic_list())" 551 | }, 552 | "r": { 553 | "delete_cmd_postfix": ") ", 554 | "delete_cmd_prefix": "rm(", 555 | "library": "var_list.r", 556 | "varRefreshCmd": "cat(var_dic_list()) " 557 | } 558 | }, 559 | "types_to_exclude": [ 560 | "module", 561 | "function", 562 | "builtin_function_or_method", 563 | "instance", 564 | "_Feature" 565 | ], 566 | "window_display": false 567 | } 568 | }, 569 | "nbformat": 4, 570 | "nbformat_minor": 2 571 | } 572 | -------------------------------------------------------------------------------- /examples/fico/data_types.json: -------------------------------------------------------------------------------- 1 | {"ExternalRiskEstimate":{"type":"continuous"}, 2 | "MSinceOldestTradeOpen":{"type":"continuous"}, 3 | "MSinceMostRecentTradeOpen":{"type":"continuous"}, 4 | "AverageMInFile":{"type":"continuous"}, 5 | "NumSatisfactoryTrades":{"type":"continuous"}, 6 | "NumTrades60Ever2DerogPubRec":{"type":"continuous"}, 7 | "NumTrades90Ever2DerogPubRec":{"type":"continuous"}, 8 | "PercentTradesNeverDelq":{"type":"continuous"}, 9 | "MSinceMostRecentDelq":{"type":"continuous"}, 10 | "MaxDelq2PublicRecLast12M":{"type":"continuous"}, 11 | "MaxDelqEver":{"type":"continuous"}, 12 | "NumTotalTrades":{"type":"continuous"}, 13 | "NumTradesOpeninLast12M":{"type":"continuous"}, 14 | "PercentInstallTrades":{"type":"continuous"}, 15 | "MSinceMostRecentInqexcl7days":{"type":"continuous"}, 16 | "NumInqLast6M":{"type":"continuous"}, 17 | "NumInqLast6Mexcl7days":{"type":"continuous"}, 18 | "NetFractionRevolvingBurden":{"type":"continuous"}, 19 | "NetFractionInstallBurden":{"type":"continuous"}, 20 | "NumRevolvingTradesWBalance":{"type":"continuous"}, 21 | "NumInstallTradesWBalance":{"type":"continuous"}, 22 | "NumBank2NatlTradesWHighUtilization":{"type":"continuous"}, 23 | "PercentTradesWBalance":{"type":"continuous"}, 24 | "RiskPerformance":{"type":"target"}} 25 | -------------------------------------------------------------------------------- /examples/fico/heloc_data_dictionary-2.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/fico/heloc_data_dictionary-2.xlsx -------------------------------------------------------------------------------- /examples/fico/load.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | import pandas as pd 4 | 5 | def load_fico_challange(path="./"): 6 | 7 | data = pd.read_csv(path + "heloc_dataset_v1.csv") 8 | meta_info = json.load(open(path + "data_types.json")) 9 | data = data.replace(-9, np.nan).replace(-8, np.nan).replace(-7, np.nan) 10 | 11 | imp = SimpleImputer(missing_values=np.nan, strategy="median") 12 | imp.fit(data.iloc[:,1:]) 13 | data.iloc[:,1:] = imp.transform(data.iloc[:,1:]) 14 | x, y = data.iloc[:,1:].values, data.iloc[:,[0]].values 15 | return x, y, "Regression", meta_info 16 | -------------------------------------------------------------------------------- /examples/fico/preprocess.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2020-05-27T04:16:46.019095Z", 9 | "start_time": "2020-05-27T04:08:26.163560Z" 10 | } 11 | }, 12 | "outputs": [ 13 | { 14 | "name": "stdout", 15 | "output_type": "stream", 16 | "text": [ 17 | "Column being fixed: 1\n", 18 | "Column being fixed: 8\n", 19 | "Column being fixed: 14\n", 20 | "Column being fixed: 17\n", 21 | "Column being fixed: 18\n", 22 | "Column being fixed: 19\n", 23 | "Column being fixed: 20\n", 24 | "Column being fixed: 21\n", 25 | "Column being fixed: 22\n" 26 | ] 27 | } 28 | ], 29 | "source": [ 30 | "# --- Imports section --- \n", 31 | "import numpy as np\n", 32 | "import pandas as pd\n", 33 | "from sklearn.preprocessing import StandardScaler\n", 34 | "from sklearn import datasets, linear_model, preprocessing\n", 35 | "import copy\n", 36 | "\n", 37 | "class ModelError(Exception):\n", 38 | "\tpass\n", 39 | "\n", 40 | "class Data_Cleaner():\n", 41 | "\n", 42 | "\tdef __init__ (self, file_name, data = None):\n", 43 | "\t# --- Retrieves the data from CSV or array, as well as basic organisation ---\n", 44 | "\n", 45 | "\t\t# -- Get data from CSV or given array --\n", 46 | "\t\tif (data == None):\n", 47 | "\t\t\tself.data_set = pd.read_csv(file_name).values\n", 48 | "\n", 49 | "\t\telse:\n", 50 | "\t\t\tself.data_set = data\n", 51 | "\n", 52 | "\t\t# -- Converting target to binary --\n", 53 | "\t\tnp.place(self.data_set, self.data_set == \"Bad\", 0)\n", 54 | "\t\tnp.place(self.data_set, self.data_set == \"Good\", 1)\n", 55 | "\n", 56 | "\t\t# -- Creating Model Variable -- \n", 57 | "\t\tself.model = None\n", 58 | "\n", 59 | "\t\t# -- Creating an Order Column --\n", 60 | "\t\torder = np.arange(self.data_set.shape[0])\n", 61 | "\t\torder = order.reshape((order.shape[0],1))\n", 62 | "\n", 63 | "\t\t# -- Scale and Split --\n", 64 | "\t\t# self.y = self.data_set[:,:1]\n", 65 | "\t\t# scaler = StandardScaler()\n", 66 | "\t\t# self.X = scaler.fit_transform(self.data_set[:,1:])\n", 67 | "\n", 68 | "\t\tself.y = self.data_set[:,:1]\n", 69 | "\t\tself.X = self.data_set[:,1:]\n", 70 | "\n", 71 | "\n", 72 | "\t\t# -- Needs to be retained for inserting new samples\n", 73 | "\t\t# self.mean = scaler.mean_\n", 74 | "\t\t# self.scale = scaler.scale_\n", 75 | "\n", 76 | "\t\t# -- Assiging general useful variables --\n", 77 | "\t\tself.num_samples , self.num_features = self.X.shape\n", 78 | "\n", 79 | "\t\t# -- Add the Order Column -- \n", 80 | "\t\tself.X = np.append(order,self.X,axis=1)\n", 81 | "\t\tself.y = np.append(order,self.y,axis=1)\n", 82 | "\n", 83 | "\tdef shift(self):\n", 84 | "\t# --- Perform the shift for the two categorical features --- \n", 85 | "\n", 86 | "\t\t# -- Shift is hardcoded based on requirements -- \n", 87 | "\t\tfirst_col = self.X[:,10]\n", 88 | "\t\tnp.place(first_col, first_col == 1, 100) # hold value\n", 89 | "\t\tnp.place(first_col, first_col == 6, 1)\n", 90 | "\t\tnp.place(first_col, first_col == 5, 1)\n", 91 | "\t\tnp.place(first_col, first_col == 4, 6)\n", 92 | "\t\tnp.place(first_col, first_col == 3, 5)\n", 93 | "\t\tnp.place(first_col, first_col == 2, 4)\n", 94 | "\t\tnp.place(first_col, first_col == 100, 3)\n", 95 | "\t\tnp.place(first_col, first_col == 0, 2)\n", 96 | "\t\tnp.place(first_col, first_col == 8, 0)\n", 97 | "\t\tnp.place(first_col, first_col == 9, 0)\n", 98 | "\n", 99 | "\t\tsecond_col= self.X[:,11]\n", 100 | "\t\tnp.place(second_col, second_col == 1, 0)\n", 101 | "\t\tnp.place(second_col, second_col == 9, 0)\n", 102 | "\t\tnp.place(second_col, second_col == 7, 1)\n", 103 | "\t\tnp.place(second_col, second_col == 8, 7)\n", 104 | "\n", 105 | "\t\tself.X[:,10] = first_col\n", 106 | "\t\tself.X[:,11] = second_col\n", 107 | "\n", 108 | "\tdef __scaled_row(self,row,scaler):\n", 109 | "\t# --- Returns the Row Scaled ---\n", 110 | "\t\tmean = scaler.mean_\n", 111 | "\t\tscale = scaler.scale_\n", 112 | "\t\tscld = []\n", 113 | "\t\tfor k in range(row.shape[0]):\n", 114 | "\t\t\tscld.append((row[k] - mean[k])/scale[k])\n", 115 | "\t\tscld = np.array(scld)\n", 116 | "\n", 117 | "\t\treturn scld\n", 118 | "\t \n", 119 | "\tdef __masked_arr(self,orig_array, mask):\n", 120 | "\t# --- Returns XOR of Array and Mask --- \n", 121 | "\t\tmasked_array = []\n", 122 | "\n", 123 | "\t\tfor i in range(len(orig_array)):\n", 124 | "\t\t\trow = []\n", 125 | "\t\t\tfor j in range(len(orig_array[0])):\n", 126 | "\t\t\t\tif mask[j] != 0:\n", 127 | "\t\t\t\t\trow.append(orig_array[i][j])\n", 128 | "\t\t\tmasked_array.append(row)\n", 129 | "\n", 130 | "\t\tmasked_array = np.array(masked_array)\n", 131 | "\n", 132 | "\t\treturn masked_array\n", 133 | "\n", 134 | "\tdef __euc_distance(self,row1, row2):\n", 135 | "\t# --- Returns Euclidian Distance between Rows --- \n", 136 | "\t\tdist = 0\n", 137 | "\t\tfor i in range(len(row1)):\n", 138 | "\t\t\tt = (row1[i]-row2[i])**2\n", 139 | "\t\t\tdist += t\n", 140 | "\t\tdist = np.sqrt(dist)\n", 141 | "\t\treturn dist\n", 142 | "\n", 143 | "\tdef __predict_feature_weighted(self,row, good_data_masked, no_neighbours, orig_array, ft_idx):\n", 144 | "\t# --- Returns the single special value replaced by kNN imputation using weights---\n", 145 | "\n", 146 | "\t\tdistances = []\n", 147 | "\t\t# -- Loops through the good data with no special values -- \n", 148 | "\t\t\t# - Good data has the changing feature removed -\n", 149 | "\t\tfor i in range(len(good_data_masked)):\t\n", 150 | "\t\t\tdistances.append(self.__euc_distance(row, good_data_masked[i]))\n", 151 | "\n", 152 | "\t\tdistances = np.array(distances)\n", 153 | "\t\tmax_dist = np.max(distances)\n", 154 | "\t \n", 155 | "\t\t# -- Sorts the first no_neigbours features --\n", 156 | "\t\tidx = np.argpartition(distances, no_neighbours)\n", 157 | "\n", 158 | "\t\tvalues = []\n", 159 | "\t\tmin_dists = []\n", 160 | "\t \n", 161 | "\t\t# -- Retrieving values with which to replace -- \n", 162 | "\t\tfor i in range(no_neighbours):\n", 163 | "\t\t\tvalues.append(orig_array[idx[i]][ft_idx])\n", 164 | "\t\t\tmin_dists.append(distances[idx[i]])\n", 165 | "\n", 166 | "\t\tvalues = np.array(values) \n", 167 | "\t\tmin_dists = np.array(min_dists)\n", 168 | "\n", 169 | "\t\t# -- Assigning the weights -- \n", 170 | "\t\tweights = []\n", 171 | "\t\tfor i in min_dists:\n", 172 | "\t\t\tweights.append(1 - (i/max_dist))\n", 173 | "\t \n", 174 | "\t # -- Calculating final result -- \n", 175 | "\t\timputed_val = 0\n", 176 | "\t\tfor i in range(len(weights)):\n", 177 | "\t\t\timputed_val += weights[i] * values[i]\n", 178 | "\t \n", 179 | "\t\treturn imputed_val \n", 180 | "\n", 181 | "\tdef __predict_feature_mean(self,row, good_data_masked, no_neighbours, orig_array, ft_idx):\n", 182 | "\t# --- Returns the single special value replaced by kNN imputation using the mean ---\n", 183 | "\n", 184 | "\t\tdistances = []\n", 185 | "\t\t# -- Loops through the good data with no special values -- \n", 186 | "\t \t# - Good data has the changing feature removed -\n", 187 | "\t\tfor i in range(len(good_data_masked)):\n", 188 | "\t\t\tdistances.append(self.__euc_distance(row,good_data_masked[i]))\n", 189 | "\t\tdistances = np.array(distances)\n", 190 | "\t \n", 191 | "\t\t# -- Sorts the first no_neigbours features --\n", 192 | "\t\tidx = np.argpartition(distances, no_neighbours)\n", 193 | "\n", 194 | "\t\tvalues = []\n", 195 | "\t\tmin_dists = []\n", 196 | "\t \n", 197 | "\t\t# -- Retrieving values with which to replace -- \n", 198 | "\t\tfor i in range(no_neighbours):\n", 199 | "\t\t\tvalues.append(orig_array[idx[i]][ft_idx])\n", 200 | "\t\t\tmin_dists.append(distances[idx[i]])\n", 201 | "\n", 202 | "\t\tvalues = np.array(values) \n", 203 | "\t\tmin_dists = np.array(min_dists)\n", 204 | "\t \n", 205 | "\t\t# -- Calculating final result -- \n", 206 | "\t\timputed_val = 0\n", 207 | "\t\tfor i in range(len(values)):\n", 208 | "\t\t\timputed_val += values[i]\n", 209 | "\n", 210 | "\t\timputed_val = imputed_val/len(values)\n", 211 | "\n", 212 | "\t\treturn imputed_val\n", 213 | "\n", 214 | "\tdef __remove_row_with_vals(self, data, target, vals):\n", 215 | "\t# --- Returns the data/target without the rows that have any instance of vals list ---\n", 216 | "\t\tremoved_data = []\n", 217 | "\t\tremoved_target = []\n", 218 | "\n", 219 | "\t\trow_no = 0 \n", 220 | "\t\tfor row in data:\n", 221 | "\t\t\tfor col in row:\n", 222 | "\t\t\t\tif (col in vals):\n", 223 | "\t\t\t\t\tremoved_data.append(data[row_no])\n", 224 | "\t\t\t\t\tdata = np.delete(data, row_no, 0)\n", 225 | "\n", 226 | "\t\t\t\t\tremoved_target.append(target[row_no])\n", 227 | "\t\t\t\t\ttarget = np.delete(target, row_no, 0) \n", 228 | "\t\t\t\t\trow_no -= 1\n", 229 | "\t\t\t\t\tbreak\n", 230 | "\t\t\trow_no += 1\n", 231 | "\n", 232 | "\t\tremoved_data = np.array(removed_data)\n", 233 | "\t\tremoved_target = np.array(removed_target)\n", 234 | "\n", 235 | "\t\treturn data, target, removed_data, removed_target\n", 236 | "\n", 237 | "\tdef __remove_col_with_vals(self, data, vals):\n", 238 | "\t# --- Returns the data without the coloumns that have the desired special values ---\n", 239 | "\t\tno_cols = data.shape[1]\n", 240 | "\t\tno_rows = data.shape[0]\n", 241 | "\t\trow = 0\n", 242 | "\t\twhile (no_rows > row):\n", 243 | "\t\t\tcol = 0\n", 244 | "\t\t\twhile (no_cols > col):\n", 245 | "\t\t\t\tif (data[row][col] in vals):\n", 246 | "\t\t\t\t\tdata = np.delete(data, col, 1)\n", 247 | "\t\t\t\t\tno_cols -= 1\n", 248 | "\t\t\t\telse:\n", 249 | "\t\t\t\t\tcol += 1\n", 250 | "\t\t\trow += 1 \n", 251 | "\t\treturn data\n", 252 | "\n", 253 | "\tdef __predict_values_lin_reg(self,X_tr,y_tr,X_test):\n", 254 | "\t# --- Uses linear regression to extrapolate values ---\n", 255 | "\t\tmodel = linear_model.LinearRegression()\n", 256 | "\t\tmodel.fit(X_tr, y_tr)\n", 257 | "\t\tpred = model.predict(X_test)\n", 258 | "\t\treturn pred\n", 259 | "\n", 260 | "\tdef __data_spliter(self,all_data,target_col,target_val):\n", 261 | "\t# --- Splits the data such to identify target col --- \n", 262 | "\t\ttarget_col += 1\n", 263 | "\n", 264 | "\t\ty = all_data[:,target_col:target_col+1]\n", 265 | "\t\tX = np.delete(all_data,target_col,1)\n", 266 | "\t \n", 267 | "\t\t# -- Will hold the X for the y values that need to be predicted--\n", 268 | "\t\tX_target = np.zeros((1,X.shape[1]))\n", 269 | "\n", 270 | "\t\trow_no = 0 \n", 271 | "\t\t# -- Finds the rows with a target val -- \n", 272 | "\t\tfor val in y:\n", 273 | "\t\t\tif (val[0] == target_val):\n", 274 | "\t\t\t\tX_target = np.append(X_target,X[row_no:row_no+1,:],axis=0)\n", 275 | "\t\t\t\tX = np.delete(X, row_no, 0)\n", 276 | "\t\t\t\ty = np.delete(y, row_no, 0) \n", 277 | "\t\t\telse:\n", 278 | "\t\t\t\trow_no += 1\n", 279 | "\n", 280 | "\t\tX_target = np.delete(X_target,0,0)\n", 281 | "\t \n", 282 | "\t\treturn X,y,X_target # Note that the order column is still attached\n", 283 | "\n", 284 | "\tdef __combine_parts_inorder(self,X,y,X_target,y_target,target_col):\n", 285 | "\t# --- Combines all the small parts into a single data matrix ---\n", 286 | "\t\ttarget_col += 1 # To account for the order column\n", 287 | "\n", 288 | "\t\ty_target = y_target.reshape((y_target.shape[0],1))\n", 289 | "\t\ty_full = np.append(y_target,y,axis=0)\n", 290 | "\t\tX_full = np.append(X_target,X,axis=0)\n", 291 | "\n", 292 | "\t\tdata = np.append(X_full[:,:target_col],y_full,axis=1)\n", 293 | "\t\tdata = np.append(data,X_full[:,target_col:],axis=1)\n", 294 | "\t\treturn data\n", 295 | "\n", 296 | "\tdef __average_each_feature(self,X):\n", 297 | "\t# --- Finds the mean values for each feature ---\n", 298 | "\n", 299 | "\t\tX_target = np.zeros((1,X.shape[1]))\n", 300 | "\t \n", 301 | "\t\tfor i in range(X.shape[1]):\n", 302 | "\t\t\tcol = X[:,i]\n", 303 | "\t\t\tcol = np.mean(col,axis=0)\n", 304 | "\t\t\tX_target[:,i] = col\n", 305 | "\t \n", 306 | "\t\treturn X_target\n", 307 | "\n", 308 | "\tdef __process_and_predict(self,all_data,target_col,target_val,exclude=None,model=\"linear\"):\n", 309 | "\t\t# -- Split data --\n", 310 | "\t\tX,y,X_target = self.__data_spliter(all_data,target_col,target_val)\n", 311 | "\t\t# -- Record order columns -- \n", 312 | "\n", 313 | "\t\torder_data = X[:,0:1]\n", 314 | "\t\torder_target = X_target[:,0:1]\n", 315 | "\t \n", 316 | "\t # -- Remove certain columns --\n", 317 | "\t\tif (exclude != None or exclude == []):\n", 318 | "\t\t\ty_tr = np.copy(y)\n", 319 | "\t\t\tX_tr = self.__remove_col_with_vals(X,exclude)\n", 320 | "\t\t\tX_tr = np.delete(X_tr,0,axis=1) # Removes the order column\n", 321 | "\t\t\tX_pred = self.__remove_col_with_vals(X_target,exclude) # The x used to predict\n", 322 | "\t\t\tX_pred = np.delete(X_pred,0,axis=1)\n", 323 | "\n", 324 | "\n", 325 | "\t\telse:\n", 326 | "\t\t\ty_tr = np.copy(y)\n", 327 | "\t\t\tX_tr = np.delete(X,0,axis=1) # Removes the order column\n", 328 | "\t\t\tX_pred = np.delete(X_target,0,axis=1)\n", 329 | "\n", 330 | "\n", 331 | "\t # -- Run regression --\n", 332 | "\t\tif (model == \"linear\"):\n", 333 | "\t\t\ty_target = self.__predict_values_lin_reg(X_tr,y_tr,X_pred)\n", 334 | "\n", 335 | "\t\telif (model == \"polynomial\"):\n", 336 | "\t\t\tpass\n", 337 | "\n", 338 | "\t\telif (model == \"special\"):\n", 339 | "\t\t\tX_avg = self.__average_each_feature(X_pred)\n", 340 | "\t\t\tpred = self.__predict_values_lin_reg(X_tr,y_tr,X_avg)\n", 341 | "\t \n", 342 | "\t\telse:\n", 343 | "\t\t\traise ModelError(\"Model currently not available\")\n", 344 | "\t \n", 345 | "\t\tfinal_data = self.__combine_parts_inorder(X,y,X_target,y_target,target_col)\n", 346 | "\t\treturn final_data\n", 347 | "\t# --- Processes the data and uses linear regression to extrapolate --- \n", 348 | "\n", 349 | "\tdef remove_8(self, kNN, prediction_type):\n", 350 | "\t# --- Removes all the -8 values using kNN imputation ---\n", 351 | "\t\t# -- Remove the order column -- \n", 352 | "\t\torder = self.X[:,0]\n", 353 | "\t\torder = order.reshape((order.shape[0],1))\n", 354 | "\t\tself.X = np.delete(self.X, 0, axis = 1)\n", 355 | "\n", 356 | "\t\t# -- Removes all special values (-7,-8,-9) --\n", 357 | "\t\tX_good, hold1, hold2, hold3 = self.__remove_row_with_vals(self.X, self.y, [-7,-8,-9])\n", 358 | "\n", 359 | "\t\tscaler = StandardScaler()\n", 360 | "\t\tX_good_scaled = scaler.fit_transform(X_good)\n", 361 | "\n", 362 | "\t\t# -- Create a copy of the data matrix X to edit -- \n", 363 | "\t\tX_no_8 = np.copy(self.X)\n", 364 | "\n", 365 | "\t\tcols_with_8 = [1,8,14,17,18,19,20,21,22]\n", 366 | "\n", 367 | "\t\t# -- Fixing each -8 column -- \n", 368 | "\t\tfor fix_col in cols_with_8:\n", 369 | "\t\t\tprint(\"Column being fixed:\", str(fix_col))\n", 370 | "\t\t\t# -- Looping through all samples -- \n", 371 | "\t\t\tfor row in range(self.num_samples):\n", 372 | "\n", 373 | "\t\t\t\tif self.X[row][fix_col] == -8:\n", 374 | "\t\t\t\t\trow_to_comp = []\n", 375 | "\t\t\t\t\tmask = []\n", 376 | "\t\t\t\t\tscaled = self.__scaled_row(self.X[row],scaler)\n", 377 | "\n", 378 | "\t\t\t\t\t# -- Looping through each value --\n", 379 | "\t\t\t\t\tfor col in range(self.num_features):\n", 380 | "\t\t\t\t\t\tif self.X[row][col] >= 0:\n", 381 | "\t\t\t\t\t\t\tmask.append(1)\n", 382 | "\t\t\t\t\t\t\trow_to_comp.append(scaled[col])\n", 383 | "\t\t\t\t\t\telse:\n", 384 | "\t\t\t\t\t\t\tmask.append(0)\n", 385 | "\n", 386 | "\t\t\t\t\trow_to_comp = np.array(row_to_comp)\n", 387 | "\t\t\t\t\tmask = np.array(mask)\n", 388 | "\t\t \n", 389 | "\t\t\t\t\t# -- Getting the array of samples without special values in the good datasets-- \n", 390 | "\t\t\t\t\tX_good_masked = self.__masked_arr(X_good_scaled, mask)\n", 391 | "\n", 392 | "\t\t\t\t\tif (prediction_type == \"mean\"):\n", 393 | "\t\t\t\t\t\timputed = self.__predict_feature_mean(row_to_comp, X_good_masked, kNN, X_good_scaled, fix_col)\n", 394 | "\n", 395 | "\t\t\t\t\telif (prediction_type == \"weighted\"):\n", 396 | "\t\t\t\t\t\timputed = self.__predict_feature_weighted(row_to_comp, X_good_masked, kNN, X_good_scaled, fix_col)\n", 397 | "\t\t\t\t\t\n", 398 | "\t\t\t\t\tX_no_8[row][fix_col] = imputed*scaler.scale_[fix_col] + scaler.mean_[fix_col]\n", 399 | "\n", 400 | "\t\tself.X = X_no_8\n", 401 | "\n", 402 | "\t\t# -- Add back order column -- \n", 403 | "\t\tself.X = np.append(order,self.X,axis=1)\n", 404 | "\n", 405 | "\tdef remove_all_9(self):\n", 406 | "\t# --- Removes the columns with all -9 values -- \n", 407 | "\t\tself.rem_X = []\n", 408 | "\t\tself.rem_y = []\n", 409 | "\t\trow_no = 0 \n", 410 | "\t\tfor row in self.X:\n", 411 | "\t\t\tfor col_i in range(1,row.shape[0]):\n", 412 | "\t\t\t\tif (row[col_i] == -9):\n", 413 | "\t\t\t\t\tremove = True\n", 414 | "\t\t\t\telse:\n", 415 | "\t\t\t\t\tremove = False\n", 416 | "\t\t\t\t\tbreak\n", 417 | "\t\t\tif remove:\n", 418 | "\t\t\t\tself.rem_X.append(self.X[row_no])\n", 419 | "\t\t\t\tself.X = np.delete(self.X, row_no, 0)\n", 420 | "\n", 421 | "\t\t\t\tself.rem_y.append(self.y[row_no])\n", 422 | "\t\t\t\tself.y = np.delete(self.y, row_no, 0) \n", 423 | "\n", 424 | "\t\t\telse:\n", 425 | "\t\t\t\trow_no += 1\n", 426 | "\n", 427 | "\t\tself.rem_X = np.array(self.rem_X)\n", 428 | "\t\tself.rem_y = np.array(self.rem_y)\n", 429 | "\n", 430 | "\tdef remove_9(self):\n", 431 | "\t# --- Removes the -9 values by using linear regression ---\n", 432 | "\t\tself.X = self.__process_and_predict(self.X,0,-9,[-7])\n", 433 | "\n", 434 | "\tdef remove_7_est(self):\n", 435 | "\t# --- Removes the -7 values by using an approximated value ---\n", 436 | "\t\tvalue_replace = 150\n", 437 | "\t\tnp.place(self.X, self.X == -7, value_replace)\n", 438 | "\n", 439 | "\tdef output_all_data(self):\n", 440 | "\t# --- Combines all the data into a single array in order and outputs it ---\n", 441 | "\t\tall_X = np.append(self.X,self.rem_X,axis=0)\n", 442 | "\t\tall_y = np.append(self.y,self.rem_y,axis=0)\n", 443 | "\n", 444 | "\t\tall_X = all_X[all_X[:,0].argsort()]\n", 445 | "\t\tall_y = all_y[all_y[:,0].argsort()]\n", 446 | "\n", 447 | "\t\tall_X = np.delete(all_X, 0, axis=1) \n", 448 | "\t\tall_y = np.delete(all_y, 0, axis=1) \n", 449 | "\t\t\n", 450 | "\t\tdata_output = np.append(all_y,all_X,axis=1)\n", 451 | "\n", 452 | "\t\treturn data_output\n", 453 | "\n", 454 | "\tdef output_to_CSV(self, filename):\n", 455 | "\t# --- Outputs the data to a CSV according to assigned filename --- \n", 456 | "\t\tdata_output = self.output_all_data()\n", 457 | "\n", 458 | "\t\tnp.savetxt(filename, data_output.astype(int), fmt='%i', delimiter=\",\")\n", 459 | "\n", 460 | "\tdef revert_to_original(self):\n", 461 | "\t# --- Allows to retrieve the original dataset ---\n", 462 | "\t\tself.__init__(\"pass\",self.data_set)\n", 463 | "\n", 464 | "testing123 = Data_Cleaner(\"./heloc_dataset_v1.csv\")\n", 465 | "testing123.shift()\n", 466 | "testing123.remove_8(5,\"mean\")\n", 467 | "testing123.remove_all_9()\n", 468 | "testing123.remove_9()\n", 469 | "testing123.remove_7_est()\n", 470 | "testing123.output_to_CSV(\"test_file1.csv\")" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": 69, 476 | "metadata": { 477 | "ExecuteTime": { 478 | "end_time": "2020-05-28T02:34:55.972490Z", 479 | "start_time": "2020-05-28T02:34:55.852496Z" 480 | } 481 | }, 482 | "outputs": [], 483 | "source": [ 484 | "pd.DataFrame(np.hstack([testing123.X, testing123.y])).to_csv(\"fico.csv\")" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": 74, 490 | "metadata": { 491 | "ExecuteTime": { 492 | "end_time": "2020-05-28T02:36:57.680689Z", 493 | "start_time": "2020-05-28T02:36:57.624935Z" 494 | } 495 | }, 496 | "outputs": [], 497 | "source": [ 498 | "data = pd.read_csv(\"fico.csv\", index_col=[0, 1])\n", 499 | "x, y = data.iloc[:,0:].values, data.iloc[:,[-1]].values" 500 | ] 501 | } 502 | ], 503 | "metadata": { 504 | "kernelspec": { 505 | "display_name": "Python (tf2)", 506 | "language": "python", 507 | "name": "tf2" 508 | }, 509 | "language_info": { 510 | "codemirror_mode": { 511 | "name": "ipython", 512 | "version": 3 513 | }, 514 | "file_extension": ".py", 515 | "mimetype": "text/x-python", 516 | "name": "python", 517 | "nbconvert_exporter": "python", 518 | "pygments_lexer": "ipython3", 519 | "version": "3.6.8" 520 | }, 521 | "latex_envs": { 522 | "LaTeX_envs_menu_present": true, 523 | "autoclose": false, 524 | "autocomplete": true, 525 | "bibliofile": "biblio.bib", 526 | "cite_by": "apalike", 527 | "current_citInitial": 1, 528 | "eqLabelWithNumbers": true, 529 | "eqNumInitial": 1, 530 | "hotkeys": { 531 | "equation": "Ctrl-E", 532 | "itemize": "Ctrl-I" 533 | }, 534 | "labels_anchors": false, 535 | "latex_user_defs": false, 536 | "report_style_numbering": false, 537 | "user_envs_cfg": false 538 | }, 539 | "varInspector": { 540 | "cols": { 541 | "lenName": 16, 542 | "lenType": 16, 543 | "lenVar": 40 544 | }, 545 | "kernels_config": { 546 | "python": { 547 | "delete_cmd_postfix": "", 548 | "delete_cmd_prefix": "del ", 549 | "library": "var_list.py", 550 | "varRefreshCmd": "print(var_dic_list())" 551 | }, 552 | "r": { 553 | "delete_cmd_postfix": ") ", 554 | "delete_cmd_prefix": "rm(", 555 | "library": "var_list.r", 556 | "varRefreshCmd": "cat(var_dic_list()) " 557 | } 558 | }, 559 | "types_to_exclude": [ 560 | "module", 561 | "function", 562 | "builtin_function_or_method", 563 | "instance", 564 | "_Feature" 565 | ], 566 | "window_display": false 567 | } 568 | }, 569 | "nbformat": 4, 570 | "nbformat_minor": 2 571 | } 572 | -------------------------------------------------------------------------------- /examples/model_saved.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/model_saved.pickle -------------------------------------------------------------------------------- /examples/results/bank_global.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/bank_global.npy -------------------------------------------------------------------------------- /examples/results/bank_global.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/bank_global.png -------------------------------------------------------------------------------- /examples/results/bank_regu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/bank_regu.png -------------------------------------------------------------------------------- /examples/results/bank_traj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/bank_traj.png -------------------------------------------------------------------------------- /examples/results/ch_global.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/ch_global.npy -------------------------------------------------------------------------------- /examples/results/ch_global.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/ch_global.png -------------------------------------------------------------------------------- /examples/results/ch_regu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/ch_regu.png -------------------------------------------------------------------------------- /examples/results/ch_traj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/ch_traj.png -------------------------------------------------------------------------------- /examples/results/fico_global.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/fico_global.npy -------------------------------------------------------------------------------- /examples/results/fico_global.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/fico_global.png -------------------------------------------------------------------------------- /examples/results/fico_regu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/fico_regu.png -------------------------------------------------------------------------------- /examples/results/fico_traj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/fico_traj.png -------------------------------------------------------------------------------- /examples/results/s1_feature.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/s1_feature.png -------------------------------------------------------------------------------- /examples/results/s1_global.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/s1_global.png -------------------------------------------------------------------------------- /examples/results/s1_local.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/s1_local.png -------------------------------------------------------------------------------- /examples/results/s1_regu_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/s1_regu_plot.png -------------------------------------------------------------------------------- /examples/results/s1_traj_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/examples/results/s1_traj_plot.png -------------------------------------------------------------------------------- /gaminet/__init__.py: -------------------------------------------------------------------------------- 1 | from .gaminet import GAMINet 2 | 3 | __all__ = ["GAMINet"] 4 | 5 | __version__ = '0.5.8' 6 | __author__ = 'Zebin Yang and Aijun Zhang' 7 | -------------------------------------------------------------------------------- /gaminet/interpret.py: -------------------------------------------------------------------------------- 1 | # All the codes in this file are derived from interpret package by Microsoft Corporation 2 | 3 | # Distributed under the MIT software license 4 | 5 | import os 6 | import struct 7 | import numpy as np 8 | import ctypes as ct 9 | from sys import platform 10 | from numpy.ctypeslib import ndpointer 11 | from collections import OrderedDict 12 | from pandas.core.generic import NDFrame 13 | from sklearn.utils.validation import check_is_fitted 14 | from sklearn.base import BaseEstimator, TransformerMixin 15 | try: 16 | from pandas.api.types import is_numeric_dtype, is_string_dtype 17 | except ImportError: # pragma: no cover 18 | from pandas.core.dtypes.common import is_numeric_dtype, is_string_dtype 19 | 20 | def gen_attributes(col_types, col_n_bins): 21 | # Create Python form of attributes 22 | # Undocumented. 23 | attributes = [None] * len(col_types) 24 | for col_idx, _ in enumerate(attributes): 25 | attributes[col_idx] = { 26 | # NOTE: Ordinal only handled at native, override. 27 | # 'type': col_types[col_idx], 28 | "type": "continuous", 29 | # NOTE: Missing not implemented at native, always set to false. 30 | "has_missing": False, 31 | "n_bins": col_n_bins[col_idx], 32 | } 33 | return attributes 34 | 35 | 36 | def gen_attribute_sets(attribute_indices): 37 | attribute_sets = [None] * len(attribute_indices) 38 | for i, indices in enumerate(attribute_indices): 39 | attribute_set = {"n_attributes": len(indices), "attributes": indices} 40 | attribute_sets[i] = attribute_set 41 | return attribute_sets 42 | 43 | 44 | def autogen_schema(X, ordinal_max_items=2, feature_names=None, feature_types=None): 45 | """ Generates data schema for a given dataset as JSON representable. 46 | Args: 47 | X: Dataframe/ndarray to build schema from. 48 | ordinal_max_items: If a numeric column's cardinality 49 | is at most this integer, 50 | consider it as ordinal instead of continuous. 51 | feature_names: Feature names 52 | feature_types: Feature types 53 | Returns: 54 | A dictionary - schema that encapsulates column information, 55 | such as type and domain. 56 | """ 57 | col_number = 0 58 | schema = OrderedDict() 59 | for idx, (name, col_dtype) in enumerate(zip(X.dtypes.index, X.dtypes)): 60 | schema[name] = {} 61 | if feature_types is not None: 62 | schema[name]["type"] = feature_types[idx] 63 | else: 64 | if is_numeric_dtype(col_dtype): 65 | if len(set(X[name])) > ordinal_max_items: 66 | schema[name]["type"] = "continuous" 67 | else: 68 | # TODO: Work with ordinal later. 69 | schema[name]["type"] = "categorical" 70 | # schema[name]['type'] = 'ordinal' 71 | # schema[name]['order'] = list(set(X[name])) 72 | elif is_string_dtype(col_dtype): 73 | schema[name]["type"] = "categorical" 74 | else: # pragma: no cover 75 | warnings.warn("Unknown column: " + name, RuntimeWarning) 76 | schema[name]["type"] = "unknown" 77 | schema[name]["column_number"] = col_number 78 | col_number += 1 79 | return schema 80 | 81 | 82 | class EBMPreprocessor(BaseEstimator, TransformerMixin): 83 | """ Transformer that preprocesses data to be ready before EBM. """ 84 | 85 | def __init__( 86 | self, 87 | schema=None, 88 | max_n_bins=255, 89 | missing_constant=0, 90 | unknown_constant=0, 91 | feature_names=None, 92 | binning_strategy="uniform", 93 | ): 94 | """ Initializes EBM preprocessor. 95 | Args: 96 | schema: A dictionary that encapsulates column information, 97 | such as type and domain. 98 | max_n_bins: Max number of bins to process numeric features. 99 | missing_constant: Missing encoded as this constant. 100 | unknown_constant: Unknown encoded as this constant. 101 | feature_names: Feature names as list. 102 | binning_strategy: Strategy to compute bins according to density if "quantile" or equidistant if "uniform". 103 | """ 104 | self.schema = schema 105 | self.max_n_bins = max_n_bins 106 | self.missing_constant = missing_constant 107 | self.unknown_constant = unknown_constant 108 | self.feature_names = feature_names 109 | self.binning_strategy = binning_strategy 110 | 111 | def fit(self, X): 112 | """ Fits transformer to provided instances. 113 | Args: 114 | X: Numpy array for training instances. 115 | Returns: 116 | Itself. 117 | """ 118 | # self.col_bin_counts_ = {} 119 | self.col_bin_edges_ = {} 120 | 121 | self.hist_counts_ = {} 122 | self.hist_edges_ = {} 123 | 124 | self.col_mapping_ = {} 125 | self.col_mapping_counts_ = {} 126 | 127 | self.col_n_bins_ = {} 128 | 129 | self.col_names_ = [] 130 | self.col_types_ = [] 131 | self.has_fitted_ = False 132 | 133 | self.schema_ = ( 134 | self.schema 135 | if self.schema is not None 136 | else autogen_schema(X, feature_names=self.feature_names) 137 | ) 138 | schema = self.schema_ 139 | 140 | for col_idx in range(X.shape[1]): 141 | col_name = list(schema.keys())[col_idx] 142 | self.col_names_.append(col_name) 143 | 144 | col_info = schema[col_name] 145 | assert col_info["column_number"] == col_idx 146 | col_data = X[:, col_idx] 147 | 148 | self.col_types_.append(col_info["type"]) 149 | if col_info["type"] == "continuous": 150 | col_data = col_data.astype(float) 151 | col_data = col_data[~np.isnan(col_data)] 152 | 153 | iteration = 0 154 | uniq_vals = set() 155 | batch_size = 1000 156 | small_unival = True 157 | while True: 158 | start = iteration * batch_size 159 | end = (iteration + 1) * batch_size 160 | uniq_vals.update(set(col_data[start:end])) 161 | iteration += 1 162 | if len(uniq_vals) >= self.max_n_bins: 163 | small_unival = False 164 | break 165 | if end >= col_data.shape[0]: 166 | break 167 | 168 | if small_unival: 169 | bins = list(sorted(uniq_vals)) 170 | else: 171 | if self.binning_strategy == "uniform": 172 | bins = self.max_n_bins 173 | elif self.binning_strategy == "quantile": 174 | bins = np.unique( 175 | np.quantile( 176 | col_data, q=np.linspace(0, 1, self.max_n_bins + 1) 177 | ) 178 | ) 179 | else: 180 | raise ValueError( 181 | "Unknown binning_strategy: '{}'.".format( 182 | self.binning_strategy 183 | ) 184 | ) 185 | 186 | _, bin_edges = np.histogram(col_data, bins=bins) 187 | 188 | # hist_counts, hist_edges = np.histogram(col_data, bins="doane") 189 | self.col_bin_edges_[col_idx] = bin_edges 190 | 191 | # self.hist_edges_[col_idx] = hist_edges 192 | # self.hist_counts_[col_idx] = hist_counts 193 | self.col_n_bins_[col_idx] = len(bin_edges) 194 | elif col_info["type"] == "ordinal": 195 | mapping = {val: indx for indx, val in enumerate(col_info["order"])} 196 | self.col_mapping_[col_idx] = mapping 197 | self.col_n_bins_[col_idx] = len(col_info["order"]) 198 | elif col_info["type"] == "categorical": 199 | uniq_vals, counts = np.unique(col_data, return_counts=True) 200 | 201 | non_nan_index = ~np.isnan(counts) 202 | uniq_vals = uniq_vals[non_nan_index] 203 | counts = counts[non_nan_index] 204 | 205 | mapping = {val: indx for indx, val in enumerate(uniq_vals)} 206 | self.col_mapping_counts_[col_idx] = counts 207 | self.col_mapping_[col_idx] = mapping 208 | 209 | # TODO: Review NA as we don't support it yet. 210 | self.col_n_bins_[col_idx] = len(uniq_vals) 211 | 212 | self.has_fitted_ = True 213 | return self 214 | 215 | def transform(self, X): 216 | """ Transform on provided instances. 217 | Args: 218 | X: Numpy array for instances. 219 | Returns: 220 | Transformed numpy array. 221 | """ 222 | check_is_fitted(self, "has_fitted_") 223 | 224 | schema = self.schema 225 | X_new = np.copy(X) 226 | for col_idx in range(X.shape[1]): 227 | col_info = schema[list(schema.keys())[col_idx]] 228 | assert col_info["column_number"] == col_idx 229 | col_data = X[:, col_idx] 230 | if col_info["type"] == "continuous": 231 | col_data = col_data.astype(float) 232 | bin_edges = self.col_bin_edges_[col_idx].copy() 233 | 234 | digitized = np.digitize(col_data, bin_edges, right=False) 235 | digitized[digitized == 0] = 1 236 | digitized -= 1 237 | 238 | # NOTE: NA handling done later. 239 | # digitized[np.isnan(col_data)] = self.missing_constant 240 | X_new[:, col_idx] = digitized 241 | elif col_info["type"] == "ordinal": 242 | mapping = self.col_mapping_[col_idx] 243 | mapping[np.nan] = self.missing_constant 244 | vec_map = np.vectorize( 245 | lambda x: mapping[x] if x in mapping else self.unknown_constant 246 | ) 247 | X_new[:, col_idx] = vec_map(col_data) 248 | elif col_info["type"] == "categorical": 249 | mapping = self.col_mapping_[col_idx] 250 | mapping[np.nan] = self.missing_constant 251 | vec_map = np.vectorize( 252 | lambda x: mapping[x] if x in mapping else self.unknown_constant 253 | ) 254 | X_new[:, col_idx] = vec_map(col_data) 255 | 256 | return X_new.astype(np.int64) 257 | 258 | 259 | class Native: 260 | """Layer/Class responsible for native function calls.""" 261 | 262 | # enum FeatureType : int64_t 263 | # Ordinal = 0 264 | FeatureTypeOrdinal = 0 265 | # Nominal = 1 266 | FeatureTypeNominal = 1 267 | 268 | class EbmCoreFeature(ct.Structure): 269 | _fields_ = [ 270 | # FeatureType featureType; 271 | ("featureType", ct.c_longlong), 272 | # int64_t hasMissing; 273 | ("hasMissing", ct.c_longlong), 274 | # int64_t countBins; 275 | ("countBins", ct.c_longlong), 276 | ] 277 | 278 | class EbmCoreFeatureCombination(ct.Structure): 279 | _fields_ = [ 280 | # int64_t countFeaturesInCombination; 281 | ("countFeaturesInCombination", ct.c_longlong) 282 | ] 283 | 284 | LogFuncType = ct.CFUNCTYPE(None, ct.c_char, ct.c_char_p) 285 | 286 | # const signed char TraceLevelOff = 0; 287 | TraceLevelOff = 0 288 | # const signed char TraceLevelError = 1; 289 | TraceLevelError = 1 290 | # const signed char TraceLevelWarning = 2; 291 | TraceLevelWarning = 2 292 | # const signed char TraceLevelInfo = 3; 293 | TraceLevelInfo = 3 294 | # const signed char TraceLevelVerbose = 4; 295 | TraceLevelVerbose = 4 296 | 297 | def __init__(self): 298 | 299 | self.lib = ct.cdll.LoadLibrary(self.get_ebm_lib_path()) 300 | self.harden_function_signatures() 301 | 302 | def harden_function_signatures(self): 303 | """ Adds types to function signatures. """ 304 | 305 | self.lib.InitializeInteractionClassification.argtypes = [ 306 | # int64_t countFeatures 307 | ct.c_longlong, 308 | # EbmCoreFeature * features 309 | ct.POINTER(self.EbmCoreFeature), 310 | # int64_t countTargetClasses 311 | ct.c_longlong, 312 | # int64_t countInstances 313 | ct.c_longlong, 314 | # int64_t * targets 315 | ndpointer(dtype=ct.c_longlong, flags="F_CONTIGUOUS", ndim=1), 316 | # int64_t * binnedData 317 | ndpointer(dtype=ct.c_longlong, flags="F_CONTIGUOUS", ndim=2), 318 | # double * predictorScores 319 | ndpointer(dtype=ct.c_double, flags="F_CONTIGUOUS", ndim=1), 320 | ] 321 | self.lib.InitializeInteractionClassification.restype = ct.c_void_p 322 | 323 | self.lib.InitializeInteractionRegression.argtypes = [ 324 | # int64_t countFeatures 325 | ct.c_longlong, 326 | # EbmCoreFeature * features 327 | ct.POINTER(self.EbmCoreFeature), 328 | # int64_t countInstances 329 | ct.c_longlong, 330 | # double * targets 331 | ndpointer(dtype=ct.c_double, flags="F_CONTIGUOUS", ndim=1), 332 | # int64_t * binnedData 333 | ndpointer(dtype=ct.c_longlong, flags="F_CONTIGUOUS", ndim=2), 334 | # double * predictorScores 335 | ndpointer(dtype=ct.c_double, flags="F_CONTIGUOUS", ndim=1), 336 | ] 337 | self.lib.InitializeInteractionRegression.restype = ct.c_void_p 338 | 339 | self.lib.GetInteractionScore.argtypes = [ 340 | # void * ebmInteraction 341 | ct.c_void_p, 342 | # int64_t countFeaturesInCombination 343 | ct.c_longlong, 344 | # int64_t * featureIndexes 345 | ndpointer(dtype=ct.c_longlong, flags="F_CONTIGUOUS", ndim=1), 346 | # double * interactionScoreReturn 347 | ct.POINTER(ct.c_double), 348 | ] 349 | self.lib.GetInteractionScore.restype = ct.c_longlong 350 | 351 | self.lib.FreeInteraction.argtypes = [ 352 | # void * ebmInteraction 353 | ct.c_void_p 354 | ] 355 | 356 | def get_ebm_lib_path(self): 357 | """ Returns filepath of core EBM library. 358 | Returns: 359 | A string representing filepath. 360 | """ 361 | bitsize = struct.calcsize("P") * 8 362 | is_64_bit = bitsize == 64 363 | 364 | script_path = os.path.dirname(os.path.abspath(__file__)) 365 | package_path = script_path # os.path.join(script_path, "..", "..") 366 | 367 | debug_str = "" 368 | if platform == "linux" or platform == "linux2" and is_64_bit: 369 | return os.path.join( 370 | package_path, "lib", "lib_ebmcore_linux_x64{0}.so".format(debug_str) 371 | ) 372 | elif platform == "win32" and is_64_bit: 373 | return os.path.join( 374 | package_path, "lib", "lib_ebmcore_win_x64{0}.dll".format(debug_str) 375 | ) 376 | elif platform == "darwin" and is_64_bit: 377 | return os.path.join( 378 | package_path, "lib", "lib_ebmcore_mac_x64{0}.dylib".format(debug_str) 379 | ) 380 | else: 381 | msg = "Platform {0} at {1} bit not supported for EBM".format( 382 | platform, bitsize 383 | ) 384 | raise Exception(msg) 385 | 386 | 387 | class NativeEBM: 388 | """Lightweight wrapper for EBM C code. 389 | """ 390 | 391 | def __init__( 392 | self, 393 | attributes, 394 | attribute_sets, 395 | X_train, 396 | y_train, 397 | X_val, 398 | y_val, 399 | model_type="regression", 400 | num_inner_bags=0, 401 | num_classification_states=2, 402 | training_scores=None, 403 | validation_scores=None, 404 | random_state=1337, 405 | ): 406 | 407 | # TODO: Update documentation for training/val scores args. 408 | """ Initializes internal wrapper for EBM C code. 409 | Args: 410 | attributes: List of attributes represented individually as 411 | dictionary of keys ('type', 'has_missing', 'n_bins'). 412 | attribute_sets: List of attribute sets represented as 413 | a dictionary of keys ('n_attributes', 'attributes') 414 | X_train: Training design matrix as 2-D ndarray. 415 | y_train: Training response as 1-D ndarray. 416 | X_val: Validation design matrix as 2-D ndarray. 417 | y_val: Validation response as 1-D ndarray. 418 | model_type: 'regression'/'classification'. 419 | num_inner_bags: Per feature training step, number of inner bags. 420 | num_classification_states: Specific to classification, 421 | number of unique classes. 422 | training_scores: Undocumented. 423 | validation_scores: Undocumented. 424 | random_state: Random seed as integer. 425 | """ 426 | if not hasattr(self, "native"): 427 | self.native = Native() 428 | 429 | # Store args 430 | self.attributes = attributes 431 | self.attribute_sets = attribute_sets 432 | self.attribute_array, self.attribute_sets_array, self.attribute_set_indexes = self._convert_attribute_info_to_c( 433 | attributes, attribute_sets 434 | ) 435 | 436 | self.X_train = X_train 437 | self.y_train = y_train 438 | self.X_val = X_val 439 | self.y_val = y_val 440 | self.model_type = model_type 441 | self.num_inner_bags = num_inner_bags 442 | self.num_classification_states = num_classification_states 443 | 444 | # # Set train/val scores to zeros if not passed. 445 | # if isinstance(intercept, numbers.Number) or len(intercept) == 1: 446 | # score_vector = np.zeros(X.shape[0]) 447 | # else: 448 | # score_vector = np.zeros((X.shape[0], len(intercept))) 449 | 450 | self.training_scores = training_scores 451 | self.validation_scores = validation_scores 452 | if self.training_scores is None: 453 | if self.num_classification_states > 2: 454 | self.training_scores = np.zeros( 455 | (X_train.shape[0], self.num_classification_states) 456 | ).reshape(-1) 457 | else: 458 | self.training_scores = np.zeros(X_train.shape[0]) 459 | if self.validation_scores is None: 460 | if self.num_classification_states > 2: 461 | self.validation_scores = np.zeros( 462 | (X_train.shape[0], self.num_classification_states) 463 | ).reshape(-1) 464 | else: 465 | self.validation_scores = np.zeros(X_train.shape[0]) 466 | self.random_state = random_state 467 | 468 | # Convert n-dim arrays ready for C. 469 | self.X_train_f = np.asfortranarray(self.X_train) 470 | self.X_val_f = np.asfortranarray(self.X_val) 471 | 472 | # Define extra properties 473 | self.model_pointer = None 474 | self.interaction_pointer = None 475 | 476 | # Allocate external resources 477 | if self.model_type == "regression": 478 | self.y_train = self.y_train.astype("float64") 479 | self.y_val = self.y_val.astype("float64") 480 | self._initialize_interaction_regression() 481 | elif self.model_type == "classification": 482 | self.y_train = self.y_train.astype("int64") 483 | self.y_val = self.y_val.astype("int64") 484 | self._initialize_interaction_classification() 485 | 486 | def _convert_attribute_info_to_c(self, attributes, attribute_sets): 487 | # Create C form of attributes 488 | attribute_ar = (self.native.EbmCoreFeature * len(attributes))() 489 | for idx, attribute in enumerate(attributes): 490 | if attribute["type"] == "categorical": 491 | attribute_ar[idx].featureType = self.native.FeatureTypeNominal 492 | else: 493 | attribute_ar[idx].featureType = self.native.FeatureTypeOrdinal 494 | attribute_ar[idx].hasMissing = 1 * attribute["has_missing"] 495 | attribute_ar[idx].countBins = attribute["n_bins"] 496 | 497 | attribute_set_indexes = [] 498 | attribute_sets_ar = ( 499 | self.native.EbmCoreFeatureCombination * len(attribute_sets) 500 | )() 501 | for idx, attribute_set in enumerate(attribute_sets): 502 | attribute_sets_ar[idx].countFeaturesInCombination = attribute_set[ 503 | "n_attributes" 504 | ] 505 | 506 | for attr_idx in attribute_set["attributes"]: 507 | attribute_set_indexes.append(attr_idx) 508 | 509 | attribute_set_indexes = np.array(attribute_set_indexes, dtype="int64") 510 | 511 | return attribute_ar, attribute_sets_ar, attribute_set_indexes 512 | 513 | def _initialize_interaction_regression(self): 514 | self.interaction_pointer = self.native.lib.InitializeInteractionRegression( 515 | len(self.attribute_array), 516 | self.attribute_array, 517 | self.X_train.shape[0], 518 | self.y_train, 519 | self.X_train_f, 520 | self.training_scores, 521 | ) 522 | 523 | def _initialize_interaction_classification(self): 524 | self.interaction_pointer = self.native.lib.InitializeInteractionClassification( 525 | len(self.attribute_array), 526 | self.attribute_array, 527 | self.num_classification_states, 528 | self.X_train.shape[0], 529 | self.y_train, 530 | self.X_train_f, 531 | self.training_scores, 532 | ) 533 | 534 | def close(self): 535 | """ Deallocates C objects used to train EBM. """ 536 | self.native.lib.FreeInteraction(self.interaction_pointer) 537 | 538 | def fast_interaction_score(self, attribute_index_tuple): 539 | """ Provides score for an attribute interaction. Higher is better.""" 540 | score = ct.c_double(0.0) 541 | self.native.lib.GetInteractionScore( 542 | self.interaction_pointer, 543 | len(attribute_index_tuple), 544 | np.array(attribute_index_tuple, dtype=np.int64), 545 | ct.byref(score), 546 | ) 547 | return score.value 548 | -------------------------------------------------------------------------------- /gaminet/layers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | import tensorflow_lattice as tfl 4 | from tensorflow.keras import layers 5 | 6 | 7 | class CategNet(tf.keras.layers.Layer): 8 | 9 | def __init__(self, category_num, cagetnet_id): 10 | super(CategNet, self).__init__() 11 | self.category_num = category_num 12 | self.cagetnet_id = cagetnet_id 13 | 14 | self.output_layer_bias = self.add_weight(name="output_layer_bias_" + str(self.cagetnet_id), 15 | shape=[1, 1], 16 | initializer=tf.zeros_initializer(), 17 | trainable=False) 18 | self.categ_bias = self.add_weight(name="cate_bias_" + str(self.cagetnet_id), 19 | shape=[self.category_num, 1], 20 | initializer=tf.zeros_initializer(), 21 | trainable=True) 22 | self.moving_mean = self.add_weight(name="mean" + str(self.cagetnet_id), shape=[1], 23 | initializer=tf.zeros_initializer(), trainable=False) 24 | self.moving_norm = self.add_weight(name="norm" + str(self.cagetnet_id), shape=[1], 25 | initializer=tf.ones_initializer(), trainable=False) 26 | 27 | def call(self, inputs, sample_weight=None, training=False): 28 | 29 | dummy = tf.one_hot(indices=tf.cast(inputs[:, 0], tf.int32), depth=self.category_num) 30 | self.output_original = tf.matmul(dummy, self.categ_bias) + self.output_layer_bias 31 | 32 | if training: 33 | if sample_weight is None: 34 | if inputs.shape[0] is not None: 35 | sample_weight = tf.ones([inputs.shape[0], 1]) 36 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 37 | frequency_weights=sample_weight, axes=0) 38 | else: 39 | sample_weight = tf.reshape(sample_weight, shape=(-1, 1)) 40 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 41 | frequency_weights=sample_weight, axes=0) 42 | self.moving_mean.assign(self.subnet_mean) 43 | self.moving_norm.assign(self.subnet_norm) 44 | else: 45 | self.subnet_mean = self.moving_mean 46 | self.subnet_norm = self.moving_norm 47 | 48 | output = self.output_original 49 | return output 50 | 51 | 52 | class NumerNet(tf.keras.layers.Layer): 53 | 54 | def __init__(self, subnet_arch, activation_func, subnet_id): 55 | super(NumerNet, self).__init__() 56 | self.layers = [] 57 | self.subnet_arch = subnet_arch 58 | self.activation_func = activation_func 59 | self.subnet_id = subnet_id 60 | 61 | for nodes in self.subnet_arch: 62 | self.layers.append(layers.Dense(nodes, activation=self.activation_func, kernel_initializer=tf.keras.initializers.Orthogonal())) 63 | self.output_layer = layers.Dense(1, activation=tf.identity, kernel_initializer=tf.keras.initializers.Orthogonal()) 64 | 65 | self.min_value = self.add_weight(name="min" + str(self.subnet_id), shape=[1], initializer=tf.constant_initializer(np.inf), trainable=False) 66 | self.max_value = self.add_weight(name="max" + str(self.subnet_id), shape=[1], initializer=tf.constant_initializer(-np.inf), trainable=False) 67 | self.moving_mean = self.add_weight(name="mean" + str(self.subnet_id), shape=[1], initializer=tf.zeros_initializer(), trainable=False) 68 | self.moving_norm = self.add_weight(name="norm" + str(self.subnet_id), shape=[1], initializer=tf.ones_initializer(), trainable=False) 69 | 70 | def call(self, inputs, sample_weight=None, training=False): 71 | 72 | if training: 73 | self.min_value.assign(tf.minimum(self.min_value, tf.reduce_min(inputs))) 74 | self.max_value.assign(tf.maximum(self.max_value, tf.reduce_max(inputs))) 75 | 76 | x = tf.clip_by_value(inputs, self.min_value, self.max_value) 77 | for dense_layer in self.layers: 78 | x = dense_layer(x) 79 | self.output_original = self.output_layer(x) 80 | 81 | if training: 82 | if sample_weight is None: 83 | if inputs.shape[0] is not None: 84 | sample_weight = tf.ones([inputs.shape[0], 1]) 85 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 86 | frequency_weights=sample_weight, axes=0) 87 | else: 88 | sample_weight = tf.reshape(sample_weight, shape=(-1, 1)) 89 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 90 | frequency_weights=sample_weight, axes=0) 91 | self.moving_mean.assign(self.subnet_mean) 92 | self.moving_norm.assign(self.subnet_norm) 93 | else: 94 | self.subnet_mean = self.moving_mean 95 | self.subnet_norm = self.moving_norm 96 | 97 | output = self.output_original 98 | return output 99 | 100 | 101 | class MonoConNumerNet(tf.keras.layers.Layer): 102 | 103 | def __init__(self, monotonicity, convexity, lattice_size, subnet_id): 104 | super(MonoConNumerNet, self).__init__() 105 | 106 | self.subnet_id = subnet_id 107 | self.monotonicity = monotonicity 108 | self.convexity = convexity 109 | self.lattice_size = lattice_size 110 | self.lattice_layer = tfl.layers.Lattice(lattice_sizes=[self.lattice_size], monotonicities=['increasing']) 111 | 112 | self.lattice_layer_input = tfl.layers.PWLCalibration(input_keypoints=np.linspace(0, 1, num=8, dtype=np.float32), 113 | output_min=0.0, output_max=self.lattice_size - 1.0) 114 | if monotonicity: 115 | self.lattice_layer_input.monotonicity = monotonicity 116 | if convexity: 117 | self.lattice_layer_input.convexity = convexity 118 | self.lattice_layer_bias = self.add_weight(name="lattice_layer_bias_" + str(self.subnet_id), shape=[1], 119 | initializer=tf.zeros_initializer(), trainable=False) 120 | 121 | self.min_value = self.add_weight(name="min" + str(self.subnet_id), shape=[1], initializer=tf.constant_initializer(np.inf), trainable=False) 122 | self.max_value = self.add_weight(name="max" + str(self.subnet_id), shape=[1], initializer=tf.constant_initializer(-np.inf), trainable=False) 123 | self.moving_mean = self.add_weight(name="mean" + str(self.subnet_id), shape=[1], initializer=tf.zeros_initializer(), trainable=False) 124 | self.moving_norm = self.add_weight(name="norm" + str(self.subnet_id), shape=[1], initializer=tf.ones_initializer(), trainable=False) 125 | 126 | def call(self, inputs, sample_weight=None, training=False): 127 | 128 | if training: 129 | self.min_value.assign(tf.minimum(self.min_value, tf.reduce_min(inputs))) 130 | self.max_value.assign(tf.maximum(self.max_value, tf.reduce_max(inputs))) 131 | 132 | x = tf.clip_by_value(inputs, self.min_value, self.max_value) 133 | lattice_input = self.lattice_layer_input(x) 134 | self.output_original = self.lattice_layer(lattice_input) + self.lattice_layer_bias 135 | 136 | if training: 137 | if sample_weight is None: 138 | if inputs.shape[0] is not None: 139 | sample_weight = tf.ones([inputs.shape[0], 1]) 140 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 141 | frequency_weights=sample_weight, axes=0) 142 | else: 143 | sample_weight = tf.reshape(sample_weight, shape=(-1, 1)) 144 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 145 | frequency_weights=sample_weight, axes=0) 146 | self.moving_mean.assign(self.subnet_mean) 147 | self.moving_norm.assign(self.subnet_norm) 148 | else: 149 | self.subnet_mean = self.moving_mean 150 | self.subnet_norm = self.moving_norm 151 | 152 | output = self.output_original 153 | return output 154 | 155 | 156 | class MainEffectBlock(tf.keras.layers.Layer): 157 | 158 | def __init__(self, feature_list, nfeature_index_list, cfeature_index_list, dummy_values, 159 | subnet_arch, activation_func, mono_increasing_list, mono_decreasing_list, convex_list, concave_list, lattice_size): 160 | super(MainEffectBlock, self).__init__() 161 | 162 | self.subnet_arch = subnet_arch 163 | self.lattice_size = lattice_size 164 | self.activation_func = activation_func 165 | 166 | self.dummy_values = dummy_values 167 | self.feature_list = feature_list 168 | self.subnet_num = len(feature_list) 169 | self.nfeature_index_list = nfeature_index_list 170 | self.cfeature_index_list = cfeature_index_list 171 | self.mono_increasing_list = mono_increasing_list 172 | self.mono_decreasing_list = mono_decreasing_list 173 | self.convex_list = convex_list 174 | self.concave_list = concave_list 175 | 176 | self.subnets = [] 177 | for i in range(self.subnet_num): 178 | if i in self.nfeature_index_list: 179 | convexity = None 180 | monotonicity = None 181 | if i in self.mono_increasing_list: 182 | monotonicity = "increasing" 183 | elif i in self.mono_decreasing_list: 184 | monotonicity = "decreasing" 185 | if i in self.convex_list: 186 | convexity = "convex" 187 | elif i in self.concave_list: 188 | convexity = "concave" 189 | if monotonicity or convexity: 190 | self.subnets.append(MonoConNumerNet(monotonicity, convexity, self.lattice_size, subnet_id=i)) 191 | else: 192 | self.subnets.append(NumerNet(self.subnet_arch, self.activation_func, subnet_id=i)) 193 | elif i in self.cfeature_index_list: 194 | feature_name = self.feature_list[i] 195 | self.subnets.append(CategNet(category_num=len(self.dummy_values[feature_name]), cagetnet_id=i)) 196 | 197 | def call(self, inputs, sample_weight=None, training=False): 198 | 199 | self.subnet_outputs = [] 200 | for i in range(self.subnet_num): 201 | subnet = self.subnets[i] 202 | subnet_output = subnet(tf.gather(inputs, [i], axis=1), sample_weight=sample_weight, training=training) 203 | self.subnet_outputs.append(subnet_output) 204 | output = tf.reshape(tf.squeeze(tf.stack(self.subnet_outputs, 1)), [-1, self.subnet_num]) 205 | 206 | return output 207 | 208 | 209 | class Interactnetwork(tf.keras.layers.Layer): 210 | 211 | def __init__(self, feature_list, cfeature_index_list, dummy_values, interact_arch, 212 | activation_func, interact_id): 213 | super(Interactnetwork, self).__init__() 214 | 215 | self.feature_list = feature_list 216 | self.dummy_values = dummy_values 217 | self.cfeature_index_list = cfeature_index_list 218 | 219 | self.layers = [] 220 | self.interact_arch = interact_arch 221 | self.activation_func = activation_func 222 | self.interact_id = interact_id 223 | self.interaction = None 224 | 225 | def set_interaction(self, interaction): 226 | 227 | self.interaction = interaction 228 | for nodes in self.interact_arch: 229 | self.layers.append(layers.Dense(nodes, activation=self.activation_func, kernel_initializer=tf.keras.initializers.Orthogonal())) 230 | self.output_layer = layers.Dense(1, activation=tf.identity, kernel_initializer=tf.keras.initializers.Orthogonal()) 231 | 232 | self.min_value1 = self.add_weight(name="min1" + str(self.interact_id), shape=[1], 233 | initializer=tf.constant_initializer(np.inf), trainable=False) 234 | self.max_value1 = self.add_weight(name="max1" + str(self.interact_id), shape=[1], 235 | initializer=tf.constant_initializer(-np.inf), trainable=False) 236 | self.min_value2 = self.add_weight(name="min2" + str(self.interact_id), shape=[1], 237 | initializer=tf.constant_initializer(np.inf), trainable=False) 238 | self.max_value2 = self.add_weight(name="max2" + str(self.interact_id), shape=[1], 239 | initializer=tf.constant_initializer(-np.inf), trainable=False) 240 | 241 | self.moving_mean = self.add_weight(name="mean_" + str(self.interact_id), 242 | shape=[1], initializer=tf.zeros_initializer(), trainable=False) 243 | self.moving_norm = self.add_weight(name="norm_" + str(self.interact_id), 244 | shape=[1], initializer=tf.ones_initializer(), trainable=False) 245 | 246 | def preprocessing(self, inputs): 247 | 248 | interact_input_list = [] 249 | if self.interaction[0] in self.cfeature_index_list: 250 | interact_input1 = tf.one_hot(indices=tf.cast(inputs[:, 0], tf.int32), 251 | depth=len(self.dummy_values[self.feature_list[self.interaction[0]]])) 252 | interact_input_list.extend(tf.unstack(interact_input1, axis=-1)) 253 | else: 254 | interact_input_list.append(tf.clip_by_value(inputs[:, 0], self.min_value1, self.max_value1)) 255 | if self.interaction[1] in self.cfeature_index_list: 256 | interact_input2 = tf.one_hot(indices=tf.cast(inputs[:, 1], tf.int32), 257 | depth=len(self.dummy_values[self.feature_list[self.interaction[1]]])) 258 | interact_input_list.extend(tf.unstack(interact_input2, axis=-1)) 259 | else: 260 | interact_input_list.append(tf.clip_by_value(inputs[:, 1], self.min_value2, self.max_value2)) 261 | return interact_input_list 262 | 263 | def call(self, inputs, sample_weight=None, training=False): 264 | 265 | if training: 266 | self.min_value1.assign(tf.minimum(self.min_value1, tf.reduce_min(inputs[:, 0]))) 267 | self.max_value1.assign(tf.maximum(self.max_value1, tf.reduce_max(inputs[:, 0]))) 268 | self.min_value2.assign(tf.minimum(self.min_value2, tf.reduce_min(inputs[:, 1]))) 269 | self.max_value2.assign(tf.maximum(self.max_value2, tf.reduce_max(inputs[:, 1]))) 270 | 271 | x = tf.stack(self.preprocessing(inputs), 1) 272 | for dense_layer in self.layers: 273 | x = dense_layer(x) 274 | self.output_original = self.output_layer(x) 275 | 276 | if training: 277 | if sample_weight is None: 278 | if inputs.shape[0] is not None: 279 | sample_weight = tf.ones([inputs.shape[0], 1]) 280 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 281 | frequency_weights=sample_weight, axes=0) 282 | else: 283 | sample_weight = tf.reshape(sample_weight, shape=(-1, 1)) 284 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 285 | frequency_weights=sample_weight, axes=0) 286 | self.moving_mean.assign(self.subnet_mean) 287 | self.moving_norm.assign(self.subnet_norm) 288 | else: 289 | self.subnet_mean = self.moving_mean 290 | self.subnet_norm = self.moving_norm 291 | 292 | output = self.output_original 293 | return output 294 | 295 | 296 | class MonoConInteractnetwork(tf.keras.layers.Layer): 297 | 298 | def __init__(self, feature_list, cfeature_index_list, dummy_values, lattice_size, monotonicity, convexity, interact_id): 299 | super(MonoConInteractnetwork, self).__init__() 300 | 301 | self.feature_list = feature_list 302 | self.dummy_values = dummy_values 303 | self.cfeature_index_list = cfeature_index_list 304 | 305 | self.monotonicity = monotonicity 306 | self.convexity = convexity 307 | self.lattice_size = lattice_size 308 | self.interact_id = interact_id 309 | self.interaction = None 310 | 311 | def set_interaction(self, interaction): 312 | 313 | self.interaction = interaction 314 | if self.interaction[0] in self.cfeature_index_list: 315 | depth = len(self.dummy_values[self.feature_list[self.interaction[0]]]) 316 | self.lattice_layer_input1 = tfl.layers.CategoricalCalibration(num_buckets=depth, output_min=0.0, output_max=1.0) 317 | else: 318 | self.lattice_layer_input1 = tfl.layers.PWLCalibration(input_keypoints=np.linspace(0, 1, num=8, dtype=np.float32), 319 | output_min=0.0, output_max=self.lattice_size[0] - 1.0) 320 | if self.monotonicity[0]: 321 | self.lattice_layer_input1.monotonicity = self.monotonicity[0] 322 | if self.convexity[0]: 323 | self.lattice_layer_input1.convexity = self.convexity[0] 324 | 325 | if self.interaction[1] in self.cfeature_index_list: 326 | depth = len(self.dummy_values[self.feature_list[self.interaction[1]]]) 327 | self.lattice_layer_input2 = tfl.layers.CategoricalCalibration(num_buckets=depth, output_min=0.0, output_max=1.0) 328 | else: 329 | self.lattice_layer_input2 = tfl.layers.PWLCalibration(input_keypoints=np.linspace(0, 1, num=8, dtype=np.float32), 330 | output_min=0.0, output_max=self.lattice_size[1] - 1.0) 331 | if self.monotonicity[1]: 332 | self.lattice_layer_input2.monotonicity = self.monotonicity[1] 333 | if self.convexity[1]: 334 | self.lattice_layer_input2.convexity = self.convexity[1] 335 | 336 | self.lattice_layer2d = tfl.layers.Lattice(lattice_sizes=self.lattice_size, monotonicities=['increasing', 'increasing']) 337 | self.lattice_layer_bias = self.add_weight(name="lattice_layer2d_bias_" + str(self.interact_id), shape=[1], 338 | initializer=tf.zeros_initializer(), trainable=False) 339 | 340 | self.min_value1 = self.add_weight(name="min1" + str(self.interact_id), shape=[1], 341 | initializer=tf.constant_initializer(np.inf), trainable=False) 342 | self.max_value1 = self.add_weight(name="max1" + str(self.interact_id), shape=[1], 343 | initializer=tf.constant_initializer(-np.inf), trainable=False) 344 | self.min_value2 = self.add_weight(name="min2" + str(self.interact_id), shape=[1], 345 | initializer=tf.constant_initializer(np.inf), trainable=False) 346 | self.max_value2 = self.add_weight(name="max2" + str(self.interact_id), shape=[1], 347 | initializer=tf.constant_initializer(-np.inf), trainable=False) 348 | 349 | self.moving_mean = self.add_weight(name="mean_" + str(self.interact_id), 350 | shape=[1], initializer=tf.zeros_initializer(), trainable=False) 351 | self.moving_norm = self.add_weight(name="norm_" + str(self.interact_id), 352 | shape=[1], initializer=tf.ones_initializer(), trainable=False) 353 | 354 | def preprocessing(self, inputs): 355 | 356 | interact_input_list = [] 357 | if self.interaction[0] in self.cfeature_index_list: 358 | interact_input_list.append(tf.reshape(inputs[:, 0], (-1, 1))) 359 | else: 360 | interact_input_list.append(tf.reshape(tf.clip_by_value(inputs[:, 0], self.min_value1, self.max_value1), (-1, 1))) 361 | if self.interaction[1] in self.cfeature_index_list: 362 | interact_input_list.append(tf.reshape(inputs[:, 1], (-1, 1))) 363 | else: 364 | interact_input_list.append(tf.reshape(tf.clip_by_value(inputs[:, 1], self.min_value2, self.max_value2), (-1, 1))) 365 | return interact_input_list 366 | 367 | def call(self, inputs, sample_weight=None, training=False): 368 | 369 | if training: 370 | self.min_value1.assign(tf.minimum(self.min_value1, tf.reduce_min(inputs[:, 0]))) 371 | self.max_value1.assign(tf.maximum(self.max_value1, tf.reduce_max(inputs[:, 0]))) 372 | self.min_value2.assign(tf.minimum(self.min_value2, tf.reduce_min(inputs[:, 1]))) 373 | self.max_value2.assign(tf.maximum(self.max_value2, tf.reduce_max(inputs[:, 1]))) 374 | 375 | x = self.preprocessing(inputs) 376 | lattice_input2d = tf.keras.layers.Concatenate(axis=1)([self.lattice_layer_input1(x[0]), self.lattice_layer_input2(x[1])]) 377 | self.output_original = self.lattice_layer2d(lattice_input2d) + self.lattice_layer_bias 378 | 379 | if training: 380 | if sample_weight is None: 381 | if inputs.shape[0] is not None: 382 | sample_weight = tf.ones([inputs.shape[0], 1]) 383 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 384 | frequency_weights=sample_weight, axes=0) 385 | else: 386 | sample_weight = tf.reshape(sample_weight, shape=(-1, 1)) 387 | self.subnet_mean, self.subnet_norm = tf.nn.weighted_moments(self.output_original, 388 | frequency_weights=sample_weight, axes=0) 389 | self.moving_mean.assign(self.subnet_mean) 390 | self.moving_norm.assign(self.subnet_norm) 391 | else: 392 | self.subnet_mean = self.moving_mean 393 | self.subnet_norm = self.moving_norm 394 | 395 | output = self.output_original 396 | return output 397 | 398 | 399 | class InteractionBlock(tf.keras.layers.Layer): 400 | 401 | def __init__(self, interact_num, feature_list, cfeature_index_list, dummy_values, 402 | interact_arch, activation_func, mono_increasing_list, mono_decreasing_list, convex_list, concave_list, lattice_size): 403 | 404 | super(InteractionBlock, self).__init__() 405 | 406 | self.feature_list = feature_list 407 | self.dummy_values = dummy_values 408 | self.cfeature_index_list = cfeature_index_list 409 | 410 | self.interact_num_added = 0 411 | self.interact_num = interact_num 412 | self.interact_arch = interact_arch 413 | self.activation_func = activation_func 414 | self.lattice_size = lattice_size 415 | self.mono_increasing_list = mono_increasing_list 416 | self.mono_decreasing_list = mono_decreasing_list 417 | self.mono_list = mono_increasing_list + mono_decreasing_list 418 | self.convex_list = convex_list 419 | self.concave_list = concave_list 420 | self.con_list = convex_list + concave_list 421 | 422 | def set_interaction_list(self, interaction_list): 423 | 424 | self.interacts = [] 425 | self.interaction_list = interaction_list 426 | self.interact_num_added = len(interaction_list) 427 | for i in range(self.interact_num_added): 428 | if (interaction_list[i][0] in self.mono_list + self.con_list) or (interaction_list[i][1] in self.mono_list + self.con_list): 429 | lattice_size = [2, 2] 430 | convexity = [None, None] 431 | monotonicity = [None, None] 432 | if interaction_list[i][0] in self.mono_increasing_list: 433 | monotonicity[0] = "increasing" 434 | lattice_size[0] = self.lattice_size 435 | elif interaction_list[i][0] in self.mono_decreasing_list: 436 | monotonicity[0] = "decreasing" 437 | lattice_size[0] = self.lattice_size 438 | if interaction_list[i][0] in self.convex_list: 439 | convexity[0] = "convex" 440 | lattice_size[0] = self.lattice_size 441 | elif interaction_list[i][0] in self.concave_list: 442 | convexity[0] = "concave" 443 | lattice_size[0] = self.lattice_size 444 | 445 | if interaction_list[i][1] in self.mono_increasing_list: 446 | monotonicity[1] = "increasing" 447 | lattice_size[1] = self.lattice_size 448 | elif interaction_list[i][1] in self.mono_decreasing_list: 449 | monotonicity[1] = "decreasing" 450 | lattice_size[1] = self.lattice_size 451 | if interaction_list[i][1] in self.convex_list: 452 | convexity[1] = "convex" 453 | lattice_size[1] = self.lattice_size 454 | elif interaction_list[i][1] in self.concave_list: 455 | convexity[1] = "concave" 456 | lattice_size[1] = self.lattice_size 457 | 458 | interact = MonoConInteractnetwork(self.feature_list, 459 | self.cfeature_index_list, 460 | self.dummy_values, 461 | monotonicity=monotonicity, 462 | convexity=convexity, 463 | lattice_size=lattice_size, 464 | interact_id=i) 465 | else: 466 | interact = Interactnetwork(self.feature_list, 467 | self.cfeature_index_list, 468 | self.dummy_values, 469 | self.interact_arch, 470 | self.activation_func, 471 | interact_id=i) 472 | interact.set_interaction(interaction_list[i]) 473 | self.interacts.append(interact) 474 | 475 | def call(self, inputs, sample_weight=None, training=False): 476 | 477 | self.interact_outputs = [] 478 | for i in range(self.interact_num): 479 | if i >= self.interact_num_added: 480 | self.interact_outputs.append(tf.zeros([inputs.shape[0], 1])) 481 | else: 482 | interact = self.interacts[i] 483 | interact_input = tf.gather(inputs, self.interaction_list[i], axis=1) 484 | interact_output = interact(interact_input, sample_weight=sample_weight, training=training) 485 | self.interact_outputs.append(interact_output) 486 | 487 | if len(self.interact_outputs) > 0: 488 | output = tf.reshape(tf.squeeze(tf.stack(self.interact_outputs, 1)), [-1, self.interact_num]) 489 | else: 490 | output = 0 491 | return output 492 | 493 | 494 | class NonNegative(tf.keras.constraints.Constraint): 495 | 496 | def __init__(self, mono_increasing_list, mono_decreasing_list, convex_list, concave_list): 497 | 498 | self.mono_increasing_list = mono_increasing_list 499 | self.mono_decreasing_list = mono_decreasing_list 500 | self.convex_list = convex_list 501 | self.concave_list = concave_list 502 | 503 | def __call__(self, w): 504 | 505 | if len(self.mono_increasing_list) > 0: 506 | mono_increasing_weights = tf.abs(tf.gather(w, self.mono_increasing_list)) 507 | w = tf.tensor_scatter_nd_update(w, [[item] for item in self.mono_increasing_list], mono_increasing_weights) 508 | if len(self.mono_decreasing_list) > 0: 509 | mono_decreasing_weights = tf.abs(tf.gather(w, self.mono_decreasing_list)) 510 | w = tf.tensor_scatter_nd_update(w, [[item] for item in self.mono_decreasing_list], mono_decreasing_weights) 511 | if len(self.convex_list) > 0: 512 | convex_weights = tf.abs(tf.gather(w, self.convex_list)) 513 | w = tf.tensor_scatter_nd_update(w, [[item] for item in self.convex_list], convex_weights) 514 | if len(self.concave_list) > 0: 515 | concave_weights = tf.abs(tf.gather(w, self.concave_list)) 516 | w = tf.tensor_scatter_nd_update(w, [[item] for item in self.concave_list], concave_weights) 517 | return w 518 | 519 | class OutputLayer(tf.keras.layers.Layer): 520 | 521 | def __init__(self, input_num, interact_num, mono_increasing_list, mono_decreasing_list, convex_list, concave_list): 522 | 523 | super(OutputLayer, self).__init__() 524 | 525 | self.interaction = [] 526 | self.input_num = input_num 527 | self.interact_num_added = 0 528 | self.interact_num = interact_num 529 | self.mono_increasing_list = mono_increasing_list 530 | self.mono_decreasing_list = mono_decreasing_list 531 | self.convex_list = convex_list 532 | self.concave_list = concave_list 533 | 534 | self.main_effect_weights = self.add_weight(name="subnet_weights", 535 | shape=[self.input_num, 1], 536 | initializer=tf.keras.initializers.Orthogonal(), 537 | constraint=NonNegative(self.mono_increasing_list, self.mono_decreasing_list, 538 | self.convex_list, self.concave_list), 539 | trainable=True) 540 | self.main_effect_switcher = self.add_weight(name="subnet_switcher", 541 | shape=[self.input_num, 1], 542 | initializer=tf.ones_initializer(), 543 | trainable=False) 544 | 545 | self.interaction_weights = self.add_weight(name="interaction_weights", 546 | shape=[self.interact_num, 1], 547 | initializer=tf.keras.initializers.Orthogonal(), 548 | constraint=NonNegative([], [], [], []), 549 | trainable=True) 550 | self.interaction_switcher = self.add_weight(name="interaction_switcher", 551 | shape=[self.interact_num, 1], 552 | initializer=tf.ones_initializer(), 553 | trainable=False) 554 | self.output_bias = self.add_weight(name="output_bias", 555 | shape=[1], 556 | initializer=tf.zeros_initializer(), 557 | trainable=True) 558 | 559 | def set_interaction_list(self, interaction_list): 560 | 561 | self.convex_interact_list = [] 562 | self.concave_interact_list = [] 563 | self.mono_increasing_interact_list = [] 564 | self.mono_decreasing_interact_list = [] 565 | self.interaction_list = interaction_list 566 | self.interact_num_added = len(interaction_list) 567 | for i, interaction in enumerate(self.interaction_list): 568 | if (interaction[0] in self.mono_increasing_list) or (interaction[1] in self.mono_increasing_list): 569 | self.mono_increasing_interact_list.append(i) 570 | if (interaction[0] in self.mono_decreasing_list) or (interaction[1] in self.mono_decreasing_list): 571 | self.mono_decreasing_interact_list.append(i) 572 | 573 | if (interaction[0] in self.convex_list) or (interaction[1] in self.convex_list): 574 | self.convex_interact_list.append(i) 575 | if (interaction[0] in self.concave_list) or (interaction[1] in self.concave_list): 576 | self.concave_interact_list.append(i) 577 | 578 | self.interaction_weights.constraint.mono_increasing_list = self.mono_increasing_interact_list 579 | self.interaction_weights.constraint.mono_decreasing_list = self.mono_decreasing_interact_list 580 | self.interaction_weights.constraint.convex_list = self.convex_interact_list 581 | self.interaction_weights.constraint.concave_list = self.concave_interact_list 582 | 583 | def call(self, inputs): 584 | 585 | self.input_main_effect = inputs[:, :self.input_num] 586 | if self.interact_num_added > 0: 587 | self.input_interaction = inputs[:, self.input_num:] 588 | output = (tf.matmul(self.input_main_effect, self.main_effect_switcher * self.main_effect_weights) 589 | + tf.matmul(self.input_interaction, self.interaction_switcher * self.interaction_weights) 590 | + self.output_bias) 591 | else: 592 | output = (tf.matmul(self.input_main_effect, self.main_effect_switcher * self.main_effect_weights) 593 | + self.output_bias) 594 | return output 595 | -------------------------------------------------------------------------------- /gaminet/lib/lib_ebmcore_linux_x64.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/gaminet/lib/lib_ebmcore_linux_x64.so -------------------------------------------------------------------------------- /gaminet/lib/lib_ebmcore_mac_x64.dylib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/gaminet/lib/lib_ebmcore_mac_x64.dylib -------------------------------------------------------------------------------- /gaminet/lib/lib_ebmcore_win_x64.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/gaminet/lib/lib_ebmcore_win_x64.dll -------------------------------------------------------------------------------- /gaminet/lib/lib_ebmcore_win_x64.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SelfExplainML/GamiNet/62aed4fec32aa31fd18fed549aa68e29d20d98bc/gaminet/lib/lib_ebmcore_win_x64.pdb -------------------------------------------------------------------------------- /gaminet/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import pandas as pd 4 | from contextlib import closing 5 | from itertools import combinations 6 | 7 | import matplotlib 8 | from matplotlib import gridspec 9 | from matplotlib import pyplot as plt 10 | from matplotlib.ticker import MaxNLocator 11 | from joblib import Parallel, delayed 12 | 13 | from .interpret import * 14 | 15 | 16 | def get_interaction_list(tr_x, val_x, tr_y, val_y, pred_tr, pred_val, feature_list, feature_type_list, 17 | active_main_effect_index, task_type="Regression", n_jobs=1): 18 | 19 | if task_type == "Regression": 20 | num_classes_ = -1 21 | model_type = "regression" 22 | elif task_type == "Classification": 23 | num_classes_ = 2 24 | model_type = "classification" 25 | pred_tr = np.minimum(np.maximum(pred_tr, 0.0000001), 0.9999999) 26 | pred_val = np.minimum(np.maximum(pred_val, 0.0000001), 0.9999999) 27 | pred_tr = np.log(pred_tr / (1 - pred_tr)) 28 | pred_val = np.log(pred_val / (1 - pred_val)) 29 | 30 | train_num = tr_x.shape[0] 31 | x = np.vstack([tr_x, val_x]) 32 | schema_ = autogen_schema(pd.DataFrame(x), feature_names=feature_list, feature_types=feature_type_list) 33 | preprocessor_ = EBMPreprocessor(schema=schema_) 34 | preprocessor_.fit(x) 35 | xt = preprocessor_.transform(x) 36 | 37 | tr_x, val_x = xt[:train_num, :], xt[train_num:, :] 38 | attributes_ = gen_attributes(preprocessor_.col_types_, preprocessor_.col_n_bins_) 39 | main_attr_sets = gen_attribute_sets([[item] for item in range(len(attributes_))]) 40 | 41 | with closing( 42 | NativeEBM( 43 | attributes_, 44 | main_attr_sets, 45 | tr_x, 46 | tr_y, 47 | val_x, 48 | val_y, 49 | num_inner_bags=0, 50 | num_classification_states=num_classes_, 51 | model_type=model_type, 52 | training_scores=pred_tr, 53 | validation_scores=pred_val, 54 | ) 55 | ) as native_ebm: 56 | 57 | def evaluate_parallel(pair): 58 | return pair, native_ebm.fast_interaction_score(pair) 59 | 60 | all_pairs = [pair for pair in combinations(range(len(preprocessor_.col_types_)), 2) 61 | if (pair[0] in active_main_effect_index) or (pair[1] in active_main_effect_index)] 62 | interaction_scores = Parallel(n_jobs=n_jobs, backend="threading")(delayed(evaluate_parallel)(pair) for pair in all_pairs) 63 | 64 | ranked_scores = list(sorted(interaction_scores, key=lambda item: item[1], reverse=True)) 65 | interaction_list = [ranked_scores[i][0] for i in range(len(ranked_scores))] 66 | return interaction_list 67 | 68 | 69 | def plot_regularization(data_dict_logs, log_scale=True, save_eps=False, save_png=False, folder="./results/", name="demo"): 70 | 71 | main_loss = data_dict_logs["main_effect_val_loss"] 72 | inter_loss = data_dict_logs["interaction_val_loss"] 73 | active_main_effect_index = data_dict_logs["active_main_effect_index"] 74 | active_interaction_index = data_dict_logs["active_interaction_index"] 75 | 76 | fig = plt.figure(figsize=(14, 4)) 77 | if len(main_loss) > 0: 78 | ax1 = plt.subplot(1, 2, 1) 79 | ax1.plot(np.arange(0, len(main_loss), 1), main_loss) 80 | ax1.axvline(np.argmin(main_loss), linestyle="dotted", color="red") 81 | ax1.axvline(len(active_main_effect_index), linestyle="dotted", color="red") 82 | ax1.plot(np.argmin(main_loss), np.min(main_loss), "*", markersize=12, color="red") 83 | ax1.plot(len(active_main_effect_index), main_loss[len(active_main_effect_index)], "o", markersize=8, color="red") 84 | ax1.set_xlabel("Number of Main Effects", fontsize=12) 85 | ax1.set_xlim(-0.5, len(main_loss) - 0.5) 86 | ax1.xaxis.set_major_locator(MaxNLocator(integer=True)) 87 | if log_scale: 88 | ax1.set_yscale("log") 89 | ax1.set_yticks((10 ** np.linspace(np.log10(np.nanmin(main_loss)), np.log10(np.nanmax(main_loss)), 5)).round(5)) 90 | ax1.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 91 | ax1.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 92 | ax1.set_ylabel("Validation Loss (Log Scale)", fontsize=12) 93 | else: 94 | ax1.set_yticks((np.linspace(np.nanmin(main_loss), np.nanmax(main_loss), 5)).round(5)) 95 | ax1.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 96 | ax1.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 97 | ax1.set_ylabel("Validation Loss", fontsize=12) 98 | 99 | if len(inter_loss) > 0: 100 | ax2 = plt.subplot(1, 2, 2) 101 | ax2.plot(np.arange(0, len(inter_loss), 1), inter_loss) 102 | ax2.axvline(np.argmin(inter_loss), linestyle="dotted", color="red") 103 | ax2.axvline(len(active_interaction_index), linestyle="dotted", color="red") 104 | ax2.plot(np.argmin(inter_loss), np.min(inter_loss), "*", markersize=12, color="red") 105 | ax2.plot(len(active_interaction_index), inter_loss[len(active_interaction_index)], "o", markersize=8, color="red") 106 | ax2.set_xlabel("Number of Interactions", fontsize=12) 107 | ax2.set_xlim(-0.5, len(inter_loss) - 0.5) 108 | ax2.xaxis.set_major_locator(MaxNLocator(integer=True)) 109 | if log_scale: 110 | ax2.set_yscale("log") 111 | ax2.set_yticks((10 ** np.linspace(np.log10(np.nanmin(inter_loss)), np.log10(np.nanmax(inter_loss)), 5)).round(5)) 112 | ax2.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 113 | ax2.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 114 | ax2.set_ylabel("Validation Loss (Log Scale)", fontsize=12) 115 | else: 116 | ax2.set_yticks((np.linspace(np.nanmin(inter_loss), np.nanmax(inter_loss), 5)).round(5)) 117 | ax2.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 118 | ax2.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 119 | ax2.set_ylabel("Validation Loss", fontsize=12) 120 | plt.show() 121 | 122 | save_path = folder + name 123 | if save_eps: 124 | if not os.path.exists(folder): 125 | os.makedirs(folder) 126 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 127 | if save_png: 128 | if not os.path.exists(folder): 129 | os.makedirs(folder) 130 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 131 | 132 | 133 | def plot_trajectory(data_dict_logs, log_scale=True, save_eps=False, save_png=False, folder="./results/", name="demo"): 134 | 135 | t1, t2, t3 = [data_dict_logs["err_train_main_effect_training"], 136 | data_dict_logs["err_train_interaction_training"], data_dict_logs["err_train_tuning"]] 137 | v1, v2, v3= [data_dict_logs["err_val_main_effect_training"], 138 | data_dict_logs["err_val_interaction_training"], data_dict_logs["err_val_tuning"]] 139 | 140 | fig = plt.figure(figsize=(14, 4)) 141 | ax1 = plt.subplot(1, 2, 1) 142 | ax1.plot(np.arange(1, len(t1) + 1, 1), t1, color="r") 143 | ax1.plot(np.arange(len(t1) + 1, len(t1 + t2) + 1, 1), t2, color="b") 144 | ax1.plot(np.arange(len(t1 + t2) + 1, len(t1 + t2 + t3) + 1, 1), t3, color="y") 145 | if log_scale: 146 | ax1.set_yscale("log") 147 | ax1.set_yticks((10 ** np.linspace(np.log10(np.nanmin(t1 + t2 + t3)), np.log10(np.nanmax(t1 + t2 + t3)), 5)).round(5)) 148 | ax1.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 149 | ax1.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 150 | ax1.set_xlabel("Number of Epochs", fontsize=12) 151 | ax1.set_ylabel("Training Loss (Log Scale)", fontsize=12) 152 | else: 153 | ax1.set_yticks((np.linspace(np.nanmin(t1 + t2), np.nanmax(t1 + t2), 5)).round(5)) 154 | ax1.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 155 | ax1.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 156 | ax1.set_xlabel("Number of Epochs", fontsize=12) 157 | ax1.set_ylabel("Training Loss", fontsize=12) 158 | 159 | ax1.legend(["Stage 1: Training Main Effects", "Stage 2: Training Interactions", "Stage 3: Fine Tuning"]) 160 | 161 | ax2 = plt.subplot(1, 2, 2) 162 | ax2.plot(np.arange(1, len(v1) + 1, 1), v1, color="r") 163 | ax2.plot(np.arange(len(v1) + 1, len(v1 + v2) + 1, 1), v2, color="b") 164 | ax2.plot(np.arange(len(v1 + v2) + 1, len(v1 + v2 + v3) + 1, 1), v3, color="y") 165 | if log_scale: 166 | ax2.set_yscale("log") 167 | ax2.set_yticks((10 ** np.linspace(np.log10(np.nanmin(v1 + v2 + v3)), np.log10(np.nanmax(v1 + v2 + v3)), 5)).round(5)) 168 | ax2.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 169 | ax2.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 170 | ax2.set_xlabel("Number of Epochs", fontsize=12) 171 | ax2.set_ylabel("Validation Loss (Log Scale)", fontsize=12) 172 | else: 173 | ax2.set_yticks((np.linspace(np.nanmin(v1 + v2 + v3), np.nanmax(v1 + v2 + v3), 5)).round(5)) 174 | ax2.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 175 | ax2.get_yaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 176 | ax2.set_xlabel("Number of Epochs", fontsize=12) 177 | ax2.set_ylabel("Validation Loss", fontsize=12) 178 | ax2.legend(["Stage 1: Training Main Effects", "Stage 2: Training Interactions", "Stage 3: Fine Tuning"]) 179 | plt.show() 180 | 181 | save_path = folder + name 182 | if save_eps: 183 | if not os.path.exists(folder): 184 | os.makedirs(folder) 185 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 186 | if save_png: 187 | if not os.path.exists(folder): 188 | os.makedirs(folder) 189 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 190 | 191 | 192 | def feature_importance_visualize(data_dict_global, folder="./results/", name="demo", save_png=False, save_eps=False): 193 | 194 | all_ir = [] 195 | all_names = [] 196 | for key, item in data_dict_global.items(): 197 | if item["importance"] > 0: 198 | all_ir.append(item["importance"]) 199 | all_names.append(key) 200 | 201 | max_ids = len(all_names) 202 | if max_ids > 0: 203 | fig = plt.figure(figsize=(0.4 + 0.6 * max_ids, 4)) 204 | ax = plt.axes() 205 | ax.bar(np.arange(len(all_ir)), [ir for ir, _ in sorted(zip(all_ir, all_names))][::-1]) 206 | ax.set_xticks(np.arange(len(all_ir))) 207 | ax.set_xticklabels([name for _, name in sorted(zip(all_ir, all_names))][::-1], rotation=60) 208 | plt.xlabel("Feature Name", fontsize=12) 209 | plt.ylim(0, np.max(all_ir) + 0.05) 210 | plt.xlim(-1, len(all_names)) 211 | plt.title("Feature Importance") 212 | 213 | save_path = folder + name 214 | if save_eps: 215 | if not os.path.exists(folder): 216 | os.makedirs(folder) 217 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 218 | if save_png: 219 | if not os.path.exists(folder): 220 | os.makedirs(folder) 221 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 222 | 223 | 224 | def global_visualize_density(data_dict_global, main_effect_num=None, interaction_num=None, cols_per_row=4, 225 | save_png=False, save_eps=False, folder="./results/", name="demo"): 226 | 227 | maineffect_count = 0 228 | componment_scales = [] 229 | for key, item in data_dict_global.items(): 230 | componment_scales.append(item["importance"]) 231 | if item["type"] != "pairwise": 232 | maineffect_count += 1 233 | 234 | componment_scales = np.array(componment_scales) 235 | sorted_index = np.argsort(componment_scales) 236 | active_index = sorted_index[componment_scales[sorted_index].cumsum() > 0][::-1] 237 | active_univariate_index = active_index[active_index < maineffect_count][:main_effect_num] 238 | active_interaction_index = active_index[active_index >= maineffect_count][:interaction_num] 239 | max_ids = len(active_univariate_index) + len(active_interaction_index) 240 | 241 | idx = 0 242 | fig = plt.figure(figsize=(6 * cols_per_row, 4.6 * int(np.ceil(max_ids / cols_per_row)))) 243 | outer = gridspec.GridSpec(int(np.ceil(max_ids / cols_per_row)), cols_per_row, wspace=0.25, hspace=0.35) 244 | for indice in active_univariate_index: 245 | 246 | feature_name = list(data_dict_global.keys())[indice] 247 | if data_dict_global[feature_name]["type"] == "continuous": 248 | 249 | inner = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=outer[idx], wspace=0.1, hspace=0.1, height_ratios=[6, 1]) 250 | ax1 = plt.Subplot(fig, inner[0]) 251 | ax1.plot(data_dict_global[feature_name]["inputs"], data_dict_global[feature_name]["outputs"]) 252 | ax1.set_xticklabels([]) 253 | fig.add_subplot(ax1) 254 | 255 | ax2 = plt.Subplot(fig, inner[1]) 256 | xint = ((np.array(data_dict_global[feature_name]["density"]["names"][1:]) 257 | + np.array(data_dict_global[feature_name]["density"]["names"][:-1])) / 2).reshape([-1, 1]).reshape([-1]) 258 | ax2.bar(xint, data_dict_global[feature_name]["density"]["scores"], width=xint[1] - xint[0]) 259 | ax2.get_shared_x_axes().join(ax1, ax2) 260 | ax2.set_yticklabels([]) 261 | ax2.autoscale() 262 | fig.add_subplot(ax2) 263 | 264 | elif data_dict_global[feature_name]["type"] == "categorical": 265 | 266 | inner = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=outer[idx], 267 | wspace=0.1, hspace=0.1, height_ratios=[6, 1]) 268 | ax1 = plt.Subplot(fig, inner[0]) 269 | ax1.bar(np.arange(len(data_dict_global[feature_name]["inputs"])), 270 | data_dict_global[feature_name]["outputs"]) 271 | ax1.set_xticklabels([]) 272 | fig.add_subplot(ax1) 273 | 274 | ax2 = plt.Subplot(fig, inner[1]) 275 | ax2.bar(np.arange(len(data_dict_global[feature_name]["density"]["names"])), 276 | data_dict_global[feature_name]["density"]["scores"]) 277 | ax2.get_shared_x_axes().join(ax1, ax2) 278 | ax2.autoscale() 279 | ax2.set_xticks(data_dict_global[feature_name]["input_ticks"]) 280 | ax2.set_xticklabels(data_dict_global[feature_name]["input_labels"]) 281 | ax2.set_yticklabels([]) 282 | fig.add_subplot(ax2) 283 | 284 | idx = idx + 1 285 | if len(str(ax2.get_xticks())) > 60: 286 | ax2.xaxis.set_tick_params(rotation=20) 287 | ax1.set_title(feature_name + " (" + str(np.round(100 * data_dict_global[feature_name]["importance"], 1)) + "%)", fontsize=12) 288 | 289 | for indice in active_interaction_index: 290 | 291 | feature_name = list(data_dict_global.keys())[indice] 292 | feature_name1 = feature_name.split(" vs. ")[0] 293 | feature_name2 = feature_name.split(" vs. ")[1] 294 | axis_extent = data_dict_global[feature_name]["axis_extent"] 295 | 296 | inner = gridspec.GridSpecFromSubplotSpec(2, 4, subplot_spec=outer[idx], 297 | wspace=0.1, hspace=0.1, height_ratios=[6, 1], width_ratios=[0.6, 3, 0.15, 0.2]) 298 | ax_main = plt.Subplot(fig, inner[1]) 299 | interact_plot = ax_main.imshow(data_dict_global[feature_name]["outputs"], interpolation="nearest", 300 | aspect="auto", extent=axis_extent) 301 | ax_main.set_xticklabels([]) 302 | ax_main.set_yticklabels([]) 303 | ax_main.set_title(feature_name + " (" + str(np.round(100 * data_dict_global[feature_name]["importance"], 1)) + "%)", fontsize=12) 304 | fig.add_subplot(ax_main) 305 | 306 | ax_bottom = plt.Subplot(fig, inner[5]) 307 | if data_dict_global[feature_name]["xtype"] == "categorical": 308 | xint = np.arange(len(data_dict_global[feature_name1]["density"]["names"])) 309 | ax_bottom.bar(xint, data_dict_global[feature_name1]["density"]["scores"]) 310 | ax_bottom.set_xticks(data_dict_global[feature_name]["input1_ticks"]) 311 | ax_bottom.set_xticklabels(data_dict_global[feature_name]["input1_labels"]) 312 | else: 313 | xint = ((np.array(data_dict_global[feature_name1]["density"]["names"][1:]) 314 | + np.array(data_dict_global[feature_name1]["density"]["names"][:-1])) / 2).reshape([-1]) 315 | ax_bottom.bar(xint, data_dict_global[feature_name1]["density"]["scores"], width=xint[1] - xint[0]) 316 | ax_bottom.set_yticklabels([]) 317 | ax_bottom.set_xlim([axis_extent[0], axis_extent[1]]) 318 | ax_bottom.get_shared_x_axes().join(ax_bottom, ax_main) 319 | ax_bottom.autoscale() 320 | fig.add_subplot(ax_bottom) 321 | if len(str(ax_bottom.get_xticks())) > 60: 322 | ax_bottom.xaxis.set_tick_params(rotation=20) 323 | 324 | ax_left = plt.Subplot(fig, inner[0]) 325 | if data_dict_global[feature_name]["ytype"] == "categorical": 326 | xint = np.arange(len(data_dict_global[feature_name2]["density"]["names"])) 327 | ax_left.barh(xint, data_dict_global[feature_name2]["density"]["scores"]) 328 | ax_left.set_yticks(data_dict_global[feature_name]["input2_ticks"]) 329 | ax_left.set_yticklabels(data_dict_global[feature_name]["input2_labels"]) 330 | else: 331 | xint = ((np.array(data_dict_global[feature_name2]["density"]["names"][1:]) 332 | + np.array(data_dict_global[feature_name2]["density"]["names"][:-1])) / 2).reshape([-1]) 333 | ax_left.barh(xint, data_dict_global[feature_name2]["density"]["scores"], height=xint[1] - xint[0]) 334 | ax_left.set_xticklabels([]) 335 | ax_left.set_ylim([axis_extent[2], axis_extent[3]]) 336 | ax_left.get_shared_y_axes().join(ax_left, ax_main) 337 | ax_left.autoscale() 338 | fig.add_subplot(ax_left) 339 | 340 | ax_colorbar = plt.Subplot(fig, inner[2]) 341 | response_precision = max(int(- np.log10(np.max(data_dict_global[feature_name]["outputs"]) 342 | - np.min(data_dict_global[feature_name]["outputs"]))) + 2, 0) 343 | fig.colorbar(interact_plot, cax=ax_colorbar, orientation="vertical", 344 | format="%0." + str(response_precision) + "f", use_gridspec=True) 345 | fig.add_subplot(ax_colorbar) 346 | idx = idx + 1 347 | 348 | if max_ids > 0: 349 | save_path = folder + name 350 | if save_eps: 351 | if not os.path.exists(folder): 352 | os.makedirs(folder) 353 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 354 | if save_png: 355 | if not os.path.exists(folder): 356 | os.makedirs(folder) 357 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 358 | 359 | 360 | def global_visualize_wo_density(data_dict_global, main_effect_num=None, interaction_num=None, cols_per_row=4, 361 | save_png=False, save_eps=False, folder="./results/", name="demo"): 362 | 363 | maineffect_count = 0 364 | componment_scales = [] 365 | for key, item in data_dict_global.items(): 366 | componment_scales.append(item["importance"]) 367 | if item["type"] != "pairwise": 368 | maineffect_count += 1 369 | 370 | componment_scales = np.array(componment_scales) 371 | sorted_index = np.argsort(componment_scales) 372 | active_index = sorted_index[componment_scales[sorted_index].cumsum() > 0][::-1] 373 | active_univariate_index = active_index[active_index < maineffect_count][:main_effect_num] 374 | active_interaction_index = active_index[active_index >= maineffect_count][:interaction_num] 375 | max_ids = len(active_univariate_index) + len(active_interaction_index) 376 | 377 | idx = 0 378 | fig = plt.figure(figsize=(5.2 * cols_per_row, 4 * int(np.ceil(max_ids / cols_per_row)))) 379 | outer = gridspec.GridSpec(int(np.ceil(max_ids / cols_per_row)), cols_per_row, wspace=0.25, hspace=0.35) 380 | for indice in active_univariate_index: 381 | 382 | feature_name = list(data_dict_global.keys())[indice] 383 | if data_dict_global[feature_name]["type"] == "continuous": 384 | 385 | ax1 = plt.Subplot(fig, outer[idx]) 386 | ax1.plot(data_dict_global[feature_name]["inputs"], data_dict_global[feature_name]["outputs"]) 387 | ax1.set_title(feature_name, fontsize=12) 388 | fig.add_subplot(ax1) 389 | if len(str(ax1.get_xticks())) > 80: 390 | ax1.xaxis.set_tick_params(rotation=20) 391 | 392 | elif data_dict_global[feature_name]["type"] == "categorical": 393 | 394 | ax1 = plt.Subplot(fig, outer[idx]) 395 | ax1.bar(np.arange(len(data_dict_global[feature_name]["inputs"])), 396 | data_dict_global[feature_name]["outputs"]) 397 | ax1.set_title(feature_name, fontsize=12) 398 | ax1.set_xticks(data_dict_global[feature_name]["input_ticks"]) 399 | ax1.set_xticklabels(data_dict_global[feature_name]["input_labels"]) 400 | fig.add_subplot(ax1) 401 | 402 | idx = idx + 1 403 | if len(str(ax1.get_xticks())) > 60: 404 | ax1.xaxis.set_tick_params(rotation=20) 405 | ax1.set_title(feature_name + " (" + str(np.round(100 * data_dict_global[feature_name]["importance"], 1)) + "%)", fontsize=12) 406 | 407 | for indice in active_interaction_index: 408 | 409 | feature_name = list(data_dict_global.keys())[indice] 410 | axis_extent = data_dict_global[feature_name]["axis_extent"] 411 | 412 | ax_main = plt.Subplot(fig, outer[idx]) 413 | interact_plot = ax_main.imshow(data_dict_global[feature_name]["outputs"], interpolation="nearest", 414 | aspect="auto", extent=axis_extent) 415 | 416 | if data_dict_global[feature_name]["xtype"] == "categorical": 417 | ax_main.set_xticks(data_dict_global[feature_name]["input1_ticks"]) 418 | ax_main.set_xticklabels(data_dict_global[feature_name]["input1_labels"]) 419 | if data_dict_global[feature_name]["ytype"] == "categorical": 420 | ax_main.set_yticks(data_dict_global[feature_name]["input2_ticks"]) 421 | ax_main.set_yticklabels(data_dict_global[feature_name]["input2_labels"]) 422 | 423 | response_precision = max(int(- np.log10(np.max(data_dict_global[feature_name]["outputs"]) 424 | - np.min(data_dict_global[feature_name]["outputs"]))) + 2, 0) 425 | fig.colorbar(interact_plot, ax=ax_main, orientation="vertical", 426 | format="%0." + str(response_precision) + "f", use_gridspec=True) 427 | 428 | ax_main.set_title(feature_name + " (" + str(np.round(100 * data_dict_global[feature_name]["importance"], 1)) + "%)", fontsize=12) 429 | fig.add_subplot(ax_main) 430 | 431 | idx = idx + 1 432 | if len(str(ax_main.get_xticks())) > 60: 433 | ax_main.xaxis.set_tick_params(rotation=20) 434 | 435 | if max_ids > 0: 436 | save_path = folder + name 437 | if save_eps: 438 | if not os.path.exists(folder): 439 | os.makedirs(folder) 440 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 441 | if save_png: 442 | if not os.path.exists(folder): 443 | os.makedirs(folder) 444 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 445 | 446 | 447 | def local_visualize(data_dict_local, folder="./results/", name="demo", save_png=False, save_eps=False): 448 | 449 | idx = np.argsort(np.abs(data_dict_local["scores"][data_dict_local["active_indice"]]))[::-1] 450 | 451 | max_ids = len(data_dict_local["active_indice"]) 452 | fig = plt.figure(figsize=(round((len(data_dict_local["active_indice"]) + 1) * 0.6), 4)) 453 | plt.bar(np.arange(len(data_dict_local["active_indice"])), data_dict_local["scores"][data_dict_local["active_indice"]][idx]) 454 | plt.xticks(np.arange(len(data_dict_local["active_indice"])), 455 | data_dict_local["effect_names"][data_dict_local["active_indice"]][idx], rotation=60) 456 | 457 | if "actual" in data_dict_local.keys(): 458 | title = "Predicted: %0.4f | Actual: %0.4f" % (data_dict_local["predicted"], data_dict_local["actual"]) 459 | else: 460 | title = "Predicted: %0.4f" % (data_dict_local["predicted"]) 461 | plt.title(title, fontsize=12) 462 | 463 | if max_ids > 0: 464 | save_path = folder + name 465 | if save_eps: 466 | if not os.path.exists(folder): 467 | os.makedirs(folder) 468 | fig.savefig("%s.eps" % save_path, bbox_inches="tight", dpi=100) 469 | if save_png: 470 | if not os.path.exists(folder): 471 | os.makedirs(folder) 472 | fig.savefig("%s.png" % save_path, bbox_inches="tight", dpi=100) 473 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ### Dependencies 2 | ### To install, run: 3 | ### $ pip install -r requirements.txt 4 | 5 | ## data processing ## 6 | numpy>=1.15.2 7 | pandas>=0.19.2 8 | 9 | ## visualization ## 10 | matplotlib>=3.1.3 11 | 12 | ## network platform 13 | tensorflow>=2.0.0 14 | 15 | ## external tools 16 | scikit-learn>=0.23.0 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | package_data = { 4 | "gaminet": [ 5 | "lib/lib_ebmcore_win_x64.dll", 6 | "lib/lib_ebmcore_linux_x64.so", 7 | "lib/lib_ebmcore_mac_x64.dylib", 8 | "lib/lib_ebmcore_win_x64.pdb" 9 | ] 10 | } 11 | 12 | setup(name='gaminet', 13 | version='0.5.8', 14 | description='Explainable Neural Networks based on Generalized Additive Models with Structured Interactions', 15 | url='https://github.com/ZebinYang/GAMINet', 16 | author='Zebin Yang', 17 | author_email='yangzb2010@connect.hku.hk', 18 | license='GPL', 19 | packages=['gaminet'], 20 | package_data=package_data, 21 | install_requires=['matplotlib>=3.1.3', 'tensorflow>=2.0.0', 'numpy>=1.15.2', 'pandas>=0.19.2', 'scikit-learn>=0.23.0', 'tensorflow_lattice>=2.0.8'], 22 | zip_safe=False) 23 | --------------------------------------------------------------------------------