├── .gitignore ├── LICENSE ├── README.md ├── SimCLR_MotionSense.ipynb ├── data_pre_processing.py ├── img ├── SimCLR_HAR.png ├── motion_sense_transform_results.png └── transformations.png ├── raw_data_processing.py ├── simclr_models.py ├── simclr_utitlities.py └── transformations.py /.gitignore: -------------------------------------------------------------------------------- 1 | test_run/ 2 | __pycache__/ -------------------------------------------------------------------------------- /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 | # Contrastive Learning for Human Activity Recognition 2 | 3 | ![Contrastive Learning for Human Activity Recognition](./img/SimCLR_HAR.png "Contrastive Learning for Human Activity Recognition") 4 | 5 | Motivated by the limitations of labeled datasets in HAR, particularly when employed in healthcare-related applications, this work explores the adoption and adaptation of SimCLR, a contrastive learning technique for visual representations, to HAR. We have found significant differences in performance when different transformations were applied to sensor signals, and a slight improvement upon previous state-of-the-art self-supervised learning method was shown using contrastive learning. 6 | 7 | More details can be found in our full paper: https://arxiv.org/abs/2011.11542. 8 | 9 | A poster for this study can be found [here](https://iantangc.github.io/files/ML4MH_NeurIPS_2020_Tang_Poster.pdf). 10 | 11 | This repository complements our paper, providing a reference implementation of the method as described in the paper. Please contact the authors for enquiries regarding the code. 12 | 13 | # Citation 14 | 15 | If you find our paper useful or use the code available in this repository in your research, please consider citing our work: 16 | 17 | ``` 18 | @article{tang2020exploring, 19 | title={Exploring Contrastive Learning in Human Activity Recognition for Healthcare}, 20 | author={Tang, Chi Ian and Perez-Pozuelo, Ignacio and Spathis, Dimitris and Mascolo, Cecilia}, 21 | journal={arXiv preprint arXiv:2011.11542}, 22 | year={2020} 23 | } 24 | ``` 25 | 26 | # Requirements 27 | The code uses several external Python libraries for data analysis, machine learning and generating plots, listed as follows: 28 | 29 | - scipy 30 | - numpy 31 | - sklearn 32 | - pandas 33 | - tensorflow 34 | - matplotlib 35 | - seaborn 36 | 37 | Other Python standard libraries are also used. 38 | 39 | # Running the Code 40 | 41 | A demo implementation is provided in [`SimCLR_MotionSense.ipynb`](https://github.com/iantangc/ContrastiveLearning/blob/main/SimCLR_MotionSense.ipynb). In the demo, a HAR model is trained and evaluated on the MotionSense dataset following the settings outlined in our paper. 42 | 43 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/iantangc/ContrastiveLearning/blob/main/SimCLR_MotionSense.ipynb) 44 | 45 | 46 | # Results 47 | In our evaluation, we used eight different transformations designed for sensor time-series. 48 | 49 | ![Transformations](./img/transformations.png "Transformations") 50 | 51 | We observed that the SimCLR framework displays promising results, slightly outperforming other fully-supervised and semi-supervised methods, which is indicative of the potential of transferring SimCLR to mobile sensing settings and other health data, especially due to the modality-agnostic nature of the method. We also observed that the use of different transformation functions can affect the performance of the models, and in some cases, to a significant degree. 52 | 53 | ![MotionSense Results](./img/motion_sense_transform_results.png "MotionSense Results") 54 | 55 | # Code Organisation 56 | 57 | Every Python script comes with full comments, detailing what the functions do. A brief description of each file is provided below: 58 | 59 | - `SimCLR_MotionSense.ipynb`: The demo file which trains a HAR model using the MotionSense dataset following the settings outlined in our paper. 60 | - `data_pre_processing.py`: This file contains various functions for pre-processing data and preparing it for training and evaluation. 61 | - `raw_data_processing.py`: This file contains functionalities for parsing datasets from the original source into a Python object for easy working. 62 | - `simclr_models.py`: This file contains the specifications of different models used for SimCLR training for HAR. 63 | - `transformations.py`: THis file contains different functions for generating alternative views of sensor signals. 64 | 65 | # License 66 | The current version of this repository is released under the GNU General Public License v3.0 unless otherwise stated. The author of the repository retains their respective rights. The published paper is governed by a separate license and the authors retain their respective rights. 67 | 68 | # Disclaimers 69 | Disclaimer of Warranty. 70 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 71 | 72 | Limitation of Liability. 73 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 74 | 75 | # Other works used in this project 76 | This work made use of the MotionSense dataset available at https://github.com/mmalekzadeh/motion-sense. 77 | 78 | The transformation functions for the time-series in this repository is based on Um et al.'s work at https://github.com/terryum/Data-Augmentation-For-Wearable-Sensor-Data. 79 | 80 | The NT-Xent Loss function is based on a implemention by The SimCLR Authors, at https://github.com/google-research/simclr. 81 | 82 | # Copyright 83 | 84 | Copyright (c) 2020 Chi Ian Tang 85 | -------------------------------------------------------------------------------- /data_pre_processing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.stats 3 | import sklearn.model_selection 4 | import tensorflow as tf 5 | 6 | __author__ = "C. I. Tang" 7 | __copyright__ = "Copyright (C) 2020 C. I. Tang" 8 | 9 | """ 10 | Based on work of Tang et al.: https://arxiv.org/abs/2011.11542 11 | Contact: cit27@cl.cam.ac.uk 12 | License: GNU General Public License v3.0 13 | 14 | This program is free software: you can redistribute it and/or modify 15 | it under the terms of the GNU General Public License as published by 16 | the Free Software Foundation, either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License 25 | along with this program. If not, see . 26 | """ 27 | 28 | 29 | def get_mode(np_array): 30 | """ 31 | Get the mode (majority/most frequent value) from a 1D array 32 | """ 33 | return scipy.stats.mode(np_array)[0] 34 | 35 | def sliding_window_np(X, window_size, shift, stride, offset=0, flatten=None): 36 | """ 37 | Create sliding windows from an ndarray 38 | 39 | Parameters: 40 | 41 | X (numpy-array) 42 | The numpy array to be windowed 43 | 44 | shift (int) 45 | number of timestamps to shift for each window 46 | (200 here refers to 50% overlap, no overlap if =400) 47 | 48 | stride (int) 49 | stride of the window (dilation) 50 | 51 | offset (int) 52 | starting index of the first window 53 | 54 | flatten (function (array) -> (value or array) ) 55 | the function to be applied to a window after it is extracted 56 | can be used with get_mode (see above) for extracting the label by majority voting 57 | ignored if is None 58 | 59 | Return: 60 | 61 | Windowed ndarray 62 | shape[0] is the number of windows 63 | """ 64 | 65 | overall_window_size = (window_size - 1) * stride + 1 66 | num_windows = (X.shape[0] - offset - (overall_window_size)) // shift + 1 67 | windows = [] 68 | for i in range(num_windows): 69 | start_index = i * shift + offset 70 | this_window = X[start_index : start_index + overall_window_size : stride] 71 | if flatten is not None: 72 | this_window = flatten(this_window) 73 | windows.append(this_window) 74 | return np.array(windows) 75 | 76 | def get_windows_dataset_from_user_list_format(user_datasets, window_size=400, shift=200, stride=1, verbose=0): 77 | """ 78 | Create windows dataset in 'user-list' format using sliding windows 79 | 80 | Parameters: 81 | 82 | user_datasets 83 | dataset in the 'user-list' format {user_id: [(sensor_values, activity_labels)]} 84 | 85 | window_size = 400 86 | size of the window (output) 87 | 88 | shift = 200 89 | number of timestamps to shift for each window 90 | (200 here refers to 50% overlap, no overlap if =400) 91 | 92 | stride = 1 93 | stride of the window (dilation) 94 | 95 | verbose = 0 96 | debug messages are printed if > 0 97 | 98 | 99 | Return: 100 | 101 | user_dataset_windowed 102 | Windowed version of the user_datasets 103 | Windows from different trials are combined into one array 104 | type: {user_id: ( windowed_sensor_values, windowed_activity_labels)} 105 | windowed_sensor_values have shape (num_window, window_size, channels) 106 | windowed_activity_labels have shape (num_window) 107 | 108 | Labels are decided by majority vote 109 | """ 110 | 111 | user_dataset_windowed = {} 112 | 113 | for user_id in user_datasets: 114 | if verbose > 0: 115 | print(f"Processing {user_id}") 116 | x = [] 117 | y = [] 118 | 119 | # Loop through each trail of each user 120 | for v,l in user_datasets[user_id]: 121 | v_windowed = sliding_window_np(v, window_size, shift, stride) 122 | 123 | # flatten the window by majority vote (1 value for each window) 124 | l_flattened = sliding_window_np(l, window_size, shift, stride, flatten=get_mode) 125 | if len(v_windowed) > 0: 126 | x.append(v_windowed) 127 | y.append(l_flattened) 128 | if verbose > 0: 129 | print(f"Data: {v_windowed.shape}, Labels: {l_flattened.shape}") 130 | 131 | # combine all trials 132 | user_dataset_windowed[user_id] = (np.concatenate(x), np.concatenate(y).squeeze()) 133 | return user_dataset_windowed 134 | 135 | def combine_windowed_dataset(user_datasets_windowed, train_users, test_users=None, verbose=0): 136 | """ 137 | Combine a windowed 'user-list' dataset into training and test sets 138 | 139 | Parameters: 140 | 141 | user_dataset_windowed 142 | dataset in the windowed 'user-list' format {user_id: ( windowed_sensor_values, windowed_activity_labels)} 143 | 144 | train_users 145 | list or set of users (corresponding to the user_id) to be used as training data 146 | 147 | test_users = None 148 | list or set of users (corresponding to the user_id) to be used as testing data 149 | if is None, then all users not in train_users will be treated as test users 150 | 151 | verbose = 0 152 | debug messages are printed if > 0 153 | 154 | Return: 155 | (train_x, train_y, test_x, test_y) 156 | train_x, train_y 157 | the resulting training/test input values as a single numpy array 158 | test_x, test_y 159 | the resulting training/test labels as a single (1D) numpy array 160 | """ 161 | 162 | train_x = [] 163 | train_y = [] 164 | test_x = [] 165 | test_y = [] 166 | for user_id in user_datasets_windowed: 167 | 168 | v,l = user_datasets_windowed[user_id] 169 | if user_id in train_users: 170 | if verbose > 0: 171 | print(f"{user_id} Train") 172 | train_x.append(v) 173 | train_y.append(l) 174 | elif test_users is None or user_id in test_users: 175 | if verbose > 0: 176 | print(f"{user_id} Test") 177 | test_x.append(v) 178 | test_y.append(l) 179 | 180 | 181 | if len(train_x) == 0: 182 | train_x = np.array([]) 183 | train_y = np.array([]) 184 | else: 185 | train_x = np.concatenate(train_x) 186 | train_y = np.concatenate(train_y).squeeze() 187 | 188 | if len(test_x) == 0: 189 | test_x = np.array([]) 190 | test_y = np.array([]) 191 | else: 192 | test_x = np.concatenate(test_x) 193 | test_y = np.concatenate(test_y).squeeze() 194 | 195 | return train_x, train_y, test_x, test_y 196 | 197 | def get_mean_std_from_user_list_format(user_datasets, train_users): 198 | """ 199 | Obtain and means and standard deviations from a 'user-list' dataset (channel-wise) 200 | from training users only 201 | 202 | Parameters: 203 | 204 | user_datasets 205 | dataset in the 'user-list' format {user_id: [(sensor_values, activity_labels)]} 206 | 207 | train_users 208 | list or set of users (corresponding to the user_ids) from which the mean and std are extracted 209 | 210 | Return: 211 | (means, stds) 212 | means and stds of the particular users (channel-wise) 213 | shape: (num_channels) 214 | 215 | """ 216 | 217 | mean_std_data = [] 218 | for u in train_users: 219 | for data, _ in user_datasets[u]: 220 | mean_std_data.append(data) 221 | mean_std_data_combined = np.concatenate(mean_std_data) 222 | means = np.mean(mean_std_data_combined, axis=0) 223 | stds = np.std(mean_std_data_combined, axis=0) 224 | return (means, stds) 225 | 226 | def normalise(data, mean, std): 227 | """ 228 | Normalise data (Z-normalisation) 229 | """ 230 | 231 | return ((data - mean) / std) 232 | 233 | def apply_label_map(y, label_map): 234 | """ 235 | Apply a dictionary mapping to an array of labels 236 | Can be used to convert str labels to int labels 237 | 238 | Parameters: 239 | y 240 | 1D array of labels 241 | label_map 242 | a label dictionary of (label_original -> label_new) 243 | 244 | Return: 245 | y_mapped 246 | 1D array of mapped labels 247 | None values are present if there is no entry in the dictionary 248 | """ 249 | 250 | y_mapped = [] 251 | for l in y: 252 | y_mapped.append(label_map.get(l)) 253 | return np.array(y_mapped) 254 | 255 | 256 | def filter_none_label(X, y): 257 | """ 258 | Filter samples of the value None 259 | Can be used to exclude non-mapped values from apply_label_map 260 | 261 | Parameters: 262 | X 263 | data values 264 | 265 | y 266 | labels (1D) 267 | 268 | Return: 269 | (X_filtered, y_filtered) 270 | X_filtered 271 | filtered data values 272 | 273 | y_filtered 274 | filtered labels (of type int) 275 | """ 276 | 277 | valid_mask = np.where(y != None) 278 | return (np.array(X[valid_mask]), np.array(y[valid_mask], dtype=int)) 279 | 280 | def pre_process_dataset_composite(user_datasets, label_map, output_shape, train_users, test_users, window_size, shift, normalise_dataset=True, validation_split_proportion=0.2, verbose=0): 281 | """ 282 | A composite function to process a dataset 283 | Steps 284 | 1: Use sliding window to make a windowed dataset (see get_windows_dataset_from_user_list_format) 285 | 2: Split the dataset into training and test set (see combine_windowed_dataset) 286 | 3: Normalise the datasets (see get_mean_std_from_user_list_format) 287 | 4: Apply the label map and filter labels (see apply_label_map, filter_none_label) 288 | 5: One-hot encode the labels (see tf.keras.utils.to_categorical) 289 | 6: Split the training set into training and validation sets (see sklearn.model_selection.train_test_split) 290 | 291 | Parameters: 292 | user_datasets 293 | dataset in the 'user-list' format {user_id: [(sensor_values, activity_labels)]} 294 | 295 | label_map 296 | a mapping of the labels 297 | can be used to filter labels 298 | (see apply_label_map and filter_none_label) 299 | 300 | output_shape 301 | number of output classifiction categories 302 | used in one hot encoding of the labels 303 | (see tf.keras.utils.to_categorical) 304 | 305 | train_users 306 | list or set of users (corresponding to the user_id) to be used as training data 307 | 308 | test_users 309 | list or set of users (corresponding to the user_id) to be used as testing data 310 | 311 | window_size 312 | size of the data windows 313 | (see get_windows_dataset_from_user_list_format) 314 | 315 | shift 316 | number of timestamps to shift for each window 317 | (see get_windows_dataset_from_user_list_format) 318 | 319 | normalise_dataset = True 320 | applies Z-normalisation if True 321 | 322 | validation_split_proportion = 0.2 323 | if not None, the proportion for splitting the full training set further into training and validation set using random sampling 324 | (see sklearn.model_selection.train_test_split) 325 | if is None, the training set will not be split - the return value np_val will also be none 326 | 327 | verbose = 0 328 | debug messages are printed if > 0 329 | 330 | 331 | Return: 332 | (np_train, np_val, np_test) 333 | three pairs of (X, y) 334 | X is a windowed set of data points 335 | y is an array of one-hot encoded labels 336 | 337 | if validation_split_proportion is None, np_val is None 338 | """ 339 | 340 | # Step 1 341 | user_datasets_windowed = get_windows_dataset_from_user_list_format(user_datasets, window_size=window_size, shift=shift) 342 | 343 | # Step 2 344 | train_x, train_y, test_x, test_y = combine_windowed_dataset(user_datasets_windowed, train_users) 345 | 346 | # Step 3 347 | if normalise_dataset: 348 | means, stds = get_mean_std_from_user_list_format(user_datasets, train_users) 349 | train_x = normalise(train_x, means, stds) 350 | test_x = normalise(test_x, means, stds) 351 | 352 | # Step 4 353 | train_y_mapped = apply_label_map(train_y, label_map) 354 | test_y_mapped = apply_label_map(test_y, label_map) 355 | 356 | train_x, train_y_mapped = filter_none_label(train_x, train_y_mapped) 357 | test_x, test_y_mapped = filter_none_label(test_x, test_y_mapped) 358 | 359 | if verbose > 0: 360 | print("Test") 361 | print(np.unique(test_y, return_counts=True)) 362 | print(np.unique(test_y_mapped, return_counts=True)) 363 | print("-----------------") 364 | 365 | print("Train") 366 | print(np.unique(train_y, return_counts=True)) 367 | print(np.unique(train_y_mapped, return_counts=True)) 368 | print("-----------------") 369 | 370 | # Step 5 371 | train_y_one_hot = tf.keras.utils.to_categorical(train_y_mapped, num_classes=output_shape) 372 | test_y_one_hot = tf.keras.utils.to_categorical(test_y_mapped, num_classes=output_shape) 373 | 374 | r = np.random.randint(len(train_y_mapped)) 375 | assert train_y_one_hot[r].argmax() == train_y_mapped[r] 376 | r = np.random.randint(len(test_y_mapped)) 377 | assert test_y_one_hot[r].argmax() == test_y_mapped[r] 378 | 379 | # Step 6 380 | if validation_split_proportion is not None and validation_split_proportion > 0: 381 | train_x_split, val_x_split, train_y_split, val_y_split = sklearn.model_selection.train_test_split(train_x, train_y_one_hot, test_size=validation_split_proportion, random_state=42) 382 | else: 383 | train_x_split = train_x 384 | train_y_split = train_y_one_hot 385 | val_x_split = None 386 | val_y_split = None 387 | 388 | 389 | if verbose > 0: 390 | print("Training data shape:", train_x_split.shape) 391 | print("Validation data shape:", val_x_split.shape if val_x_split is not None else "None") 392 | print("Testing data shape:", test_x.shape) 393 | 394 | np_train = (train_x_split, train_y_split) 395 | np_val = (val_x_split, val_y_split) if val_x_split is not None else None 396 | np_test = (test_x, test_y_one_hot) 397 | 398 | # original_np_train = np_train 399 | # original_np_val = np_val 400 | # original_np_test = np_test 401 | 402 | return (np_train, np_val, np_test) 403 | 404 | def pre_process_dataset_composite_in_user_format(user_datasets, label_map, output_shape, train_users, window_size, shift, normalise_dataset=True, verbose=0): 405 | """ 406 | A composite function to process a dataset which outputs processed datasets separately for each user (of type: {user_id: ( windowed_sensor_values, windowed_activity_labels)}). 407 | This is different from pre_process_dataset_composite where the data from the training and testing users are not combined into one object. 408 | 409 | Steps 410 | 1: Use sliding window to make a windowed dataset (see get_windows_dataset_from_user_list_format) 411 | For each user: 412 | 2: Apply the label map and filter labels (see apply_label_map, filter_none_label) 413 | 3: One-hot encode the labels (see tf.keras.utils.to_categorical) 414 | 4: Normalise the data (see get_mean_std_from_user_list_format) 415 | 416 | Parameters: 417 | user_datasets 418 | dataset in the 'user-list' format {user_id: [(sensor_values, activity_labels)]} 419 | 420 | label_map 421 | a mapping of the labels 422 | can be used to filter labels 423 | (see apply_label_map and filter_none_label) 424 | 425 | output_shape 426 | number of output classifiction categories 427 | used in one hot encoding of the labels 428 | (see tf.keras.utils.to_categorical) 429 | 430 | train_users 431 | list or set of users (corresponding to the user_id) to be used for normalising the dataset 432 | 433 | window_size 434 | size of the data windows 435 | (see get_windows_dataset_from_user_list_format) 436 | 437 | shift 438 | number of timestamps to shift for each window 439 | (see get_windows_dataset_from_user_list_format) 440 | 441 | normalise_dataset = True 442 | applies Z-normalisation if True 443 | 444 | verbose = 0 445 | debug messages are printed if > 0 446 | 447 | 448 | Return: 449 | user_datasets_processed 450 | Processed version of the user_datasets in the windowed format 451 | type: {user_id: (windowed_sensor_values, windowed_activity_labels)} 452 | """ 453 | 454 | # Preparation for step 2 455 | if normalise_dataset: 456 | means, stds = get_mean_std_from_user_list_format(user_datasets, train_users) 457 | 458 | # Step 1 459 | user_datasets_windowed = get_windows_dataset_from_user_list_format(user_datasets, window_size=window_size, shift=shift) 460 | 461 | 462 | user_datasets_processed = {} 463 | for user, user_dataset in user_datasets_windowed.items(): 464 | data, labels = user_dataset 465 | 466 | # Step 2 467 | labels_mapped = apply_label_map(labels, label_map) 468 | data_filtered, labels_filtered = filter_none_label(data, labels_mapped) 469 | 470 | # Step 3 471 | labels_one_hot = tf.keras.utils.to_categorical(labels_filtered, num_classes=output_shape) 472 | 473 | # random check 474 | r = np.random.randint(len(labels_filtered)) 475 | assert labels_one_hot[r].argmax() == labels_filtered[r] 476 | 477 | # Step 4 478 | if normalise_dataset: 479 | data_filtered = normalise(data_filtered, means, stds) 480 | 481 | user_datasets_processed[user] = (data_filtered, labels_one_hot) 482 | 483 | if verbose > 0: 484 | print("Data shape of user", user, ":", data_filtered.shape) 485 | 486 | return user_datasets_processed 487 | 488 | def add_user_id_to_windowed_dataset(user_datasets_windowed, encode_user_id=True, as_feature=False, as_label=True, verbose=0): 489 | """ 490 | Add user ids as features or labels to a windowed dataset 491 | The user ids are appended to the last dimension of the arrays 492 | E.g. sensor values of shape (100, 400, 3) will become (100, 400, 4), and data[:, :, -1] will contain the user id 493 | Similarly labels of shape (100, 5) will become (100, 6), and labels[:, -1] will contain the user id 494 | 495 | Parameters: 496 | user_datasets_windowed 497 | dataset in the 'windowed-user' format type: {user_id: (windowed_sensor_values, windowed_activity_labels)} 498 | 499 | encode_user_id = True 500 | whether to encode the user ids as integers 501 | if True: 502 | encode all user ids as integers when being appended to the np arrays 503 | return the map from user id to integer as an output 504 | note that the dtype of the output np arrays will be kept as float if they are originally of type float 505 | if False: 506 | user ids will be kept as is when being appended to the np arrays 507 | WARNING: if the user id is of type string, the output arrays will also be converted to type string, which might be difficult to work with 508 | 509 | as_feature = False 510 | user ids will be added to the windowed_sensor_values arrays as extra features if True 511 | 512 | as_label = False 513 | user ids will be added to the windowed_activity_labels arrays as extra labels if True 514 | 515 | verbose = 0 516 | debug messages are printed if > 0 517 | 518 | Return: 519 | user_datasets_modified, user_id_encoder 520 | 521 | user_datasets_modified 522 | the modified version of the input (user_datasets_windowed) 523 | with the same type {user_id: ( windowed_sensor_values, windowed_activity_labels)} 524 | user_id_encoder 525 | the encoder which maps user ids to integers 526 | type: {user_id: encoded_user_id} 527 | None if encode_user_id is False 528 | """ 529 | 530 | # Create the mapping from user_id to integers 531 | if encode_user_id: 532 | all_users = sorted(list(user_datasets_windowed.keys())) 533 | user_id_encoder = dict([(u, i) for i, u in enumerate(all_users)]) 534 | else: 535 | user_id_encoder = None 536 | 537 | # if none of the options are enabled, return the input 538 | if not as_feature and not as_label: 539 | return user_datasets_windowed, user_id_encoder 540 | 541 | user_datasets_modified = {} 542 | for user, user_dataset in user_datasets_windowed.items(): 543 | data, labels = user_dataset 544 | 545 | # Get the encoded user_id 546 | if encode_user_id: 547 | user_id = user_id_encoder[user] 548 | else: 549 | user_id = user 550 | 551 | # Add user_id as an extra feature 552 | if as_feature: 553 | user_feature = np.expand_dims(np.full(data.shape[:-1], user_id), axis=-1) 554 | data_modified = np.append(data, user_feature, axis=-1) 555 | else: 556 | data_modified = data 557 | 558 | # Add user_id as an extra label 559 | if as_label: 560 | user_labels = np.expand_dims(np.full(labels.shape[:-1], user_id), axis=-1) 561 | labels_modified = np.append(labels, user_labels, axis=-1) 562 | else: 563 | labels_modified = labels 564 | 565 | if verbose > 0: 566 | print(f"User {user}: id {repr(user)} -> {repr(user_id)}, data shape {data.shape} -> {data_modified.shape}, labels shape {labels.shape} -> {labels_modified.shape}") 567 | 568 | user_datasets_modified[user] = (data_modified, labels_modified) 569 | 570 | return user_datasets_modified, user_id_encoder 571 | 572 | def make_batches_reshape(data, batch_size): 573 | """ 574 | Make a batched dataset from a windowed time-series by simple reshaping 575 | Note that the last batch is dropped if incomplete 576 | 577 | Parameters: 578 | data 579 | A 3D numpy array in the shape (num_windows, window_size, num_channels) 580 | 581 | batch_size 582 | the (maximum) size of the batches 583 | 584 | Returns: 585 | batched_data 586 | A 4D numpy array in the shape (num_batches, batch_size, window_size, num_channels) 587 | """ 588 | 589 | max_len = (data.shape[0]) // batch_size * batch_size 590 | return data[:max_len].reshape((-1, batch_size, data.shape[-2], data.shape[-1])) 591 | 592 | def np_random_shuffle_index(length): 593 | """ 594 | Get a list of randomly shuffled indices 595 | """ 596 | indices = np.arange(length) 597 | np.random.shuffle(indices) 598 | return indices 599 | 600 | def ceiling_division(n, d): 601 | """ 602 | Ceiling integer division 603 | """ 604 | return -(n // -d) 605 | 606 | def get_batched_dataset_generator(data, batch_size): 607 | """ 608 | Create a data batch generator 609 | Note that the last batch might not be full 610 | 611 | Parameters: 612 | data 613 | A numpy array of data 614 | 615 | batch_size 616 | the (maximum) size of the batches 617 | 618 | Returns: 619 | generator 620 | a batch of the data with the same shape except the first dimension, which is now the batch size 621 | """ 622 | 623 | num_bathes = ceiling_division(data.shape[0], batch_size) 624 | for i in range(num_bathes): 625 | yield data[i * batch_size : (i + 1) * batch_size] 626 | 627 | # return data[:max_len].reshape((-1, batch_size, data.shape[-2], data.shape[-1])) 628 | 629 | -------------------------------------------------------------------------------- /img/SimCLR_HAR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iantangc/ContrastiveLearningHAR/b3887b41e4c89e975ee989c414c0a564fd997c4e/img/SimCLR_HAR.png -------------------------------------------------------------------------------- /img/motion_sense_transform_results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iantangc/ContrastiveLearningHAR/b3887b41e4c89e975ee989c414c0a564fd997c4e/img/motion_sense_transform_results.png -------------------------------------------------------------------------------- /img/transformations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iantangc/ContrastiveLearningHAR/b3887b41e4c89e975ee989c414c0a564fd997c4e/img/transformations.png -------------------------------------------------------------------------------- /raw_data_processing.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import re 3 | import os 4 | import pandas as pd 5 | import numpy as np 6 | 7 | __author__ = "C. I. Tang" 8 | __copyright__ = "Copyright (C) 2020 C. I. Tang" 9 | 10 | """ 11 | Based on work of Tang et al.: https://arxiv.org/abs/2011.11542 12 | Contact: cit27@cl.cam.ac.uk 13 | License: GNU General Public License v3.0 14 | 15 | This program is free software: you can redistribute it and/or modify 16 | it under the terms of the GNU General Public License as published by 17 | the Free Software Foundation, either version 3 of the License, or 18 | (at your option) any later version. 19 | 20 | This program is distributed in the hope that it will be useful, 21 | but WITHOUT ANY WARRANTY; without even the implied warranty of 22 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 | GNU General Public License for more details. 24 | 25 | You should have received a copy of the GNU General Public License 26 | along with this program. If not, see . 27 | """ 28 | 29 | def process_motion_sense_accelerometer_files(accelerometer_data_folder_path): 30 | """ 31 | Preprocess the accelerometer files of the MotionSense dataset into the 'user-list' format 32 | Data files can be found at https://github.com/mmalekzadeh/motion-sense/tree/master/data 33 | 34 | Parameters: 35 | 36 | accelerometer_data_folder_path (str): 37 | the path to the folder containing the data files (unzipped) 38 | e.g. motionSense/B_Accelerometer_data/ 39 | the trial folders should be directly inside it (e.g. motionSense/B_Accelerometer_data/dws_1/) 40 | 41 | Return: 42 | 43 | user_datsets (dict of {user_id: [(sensor_values, activity_labels)]}) 44 | the processed dataset in a dictionary, of type {user_id: [(sensor_values, activity_labels)]} 45 | the keys of the dictionary is the user_id (participant id) 46 | the values of the dictionary are lists of (sensor_values, activity_labels) pairs 47 | sensor_values are 2D numpy array of shape (length, channels=3) 48 | activity_labels are 1D numpy array of shape (length) 49 | each pair corresponds to a separate trial 50 | (i.e. time is not contiguous between pairs, which is useful for making sliding windows, where it is easy to separate trials) 51 | """ 52 | 53 | # label_set = {} 54 | user_datasets = {} 55 | all_trials_folders = sorted(glob.glob(accelerometer_data_folder_path + "/*")) 56 | 57 | # Loop through every trial folder 58 | for trial_folder in all_trials_folders: 59 | trial_name = os.path.split(trial_folder)[-1] 60 | 61 | # label of the trial is given in the folder name, separated by underscore 62 | label = trial_name.split("_")[0] 63 | # label_set[label] = True 64 | print(trial_folder) 65 | 66 | # Loop through files for every user of the trail 67 | for trial_user_file in sorted(glob.glob(trial_folder + "/*.csv")): 68 | 69 | # use regex to match the user id 70 | user_id_match = re.search(r'(?P[0-9]+)\.csv', os.path.split(trial_user_file)[-1]) 71 | if user_id_match is not None: 72 | user_id = int(user_id_match.group('user_id')) 73 | 74 | # Read file 75 | user_trial_dataset = pd.read_csv(trial_user_file) 76 | user_trial_dataset.dropna(how = "any", inplace = True) 77 | 78 | # Extract the x, y, z channels 79 | values = user_trial_dataset[["x", "y", "z"]].values 80 | 81 | # the label is the same during the entire trial, so it is repeated here to pad to the same length as the values 82 | labels = np.repeat(label, values.shape[0]) 83 | 84 | if user_id not in user_datasets: 85 | user_datasets[user_id] = [] 86 | user_datasets[user_id].append((values, labels)) 87 | else: 88 | print("[ERR] User id not found", trial_user_file) 89 | 90 | return user_datasets 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /simclr_models.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | __author__ = "C. I. Tang" 4 | __copyright__ = "Copyright (C) 2020 C. I. Tang" 5 | 6 | """ 7 | Based on work of Tang et al.: https://arxiv.org/abs/2011.11542 8 | Contact: cit27@cl.cam.ac.uk 9 | License: GNU General Public License v3.0 10 | 11 | This program is free software: you can redistribute it and/or modify 12 | it under the terms of the GNU General Public License as published by 13 | the Free Software Foundation, either version 3 of the License, or 14 | (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License 22 | along with this program. If not, see . 23 | """ 24 | 25 | def create_base_model(input_shape, model_name="base_model"): 26 | """ 27 | Create the base model for activity recognition 28 | Reference (TPN model): 29 | Saeed, A., Ozcelebi, T., & Lukkien, J. (2019). Multi-task self-supervised learning for human activity detection. Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies, 3(2), 1-30. 30 | 31 | Architecture: 32 | Input 33 | -> Conv 1D: 32 filters, 24 kernel_size, relu, L2 regularizer 34 | -> Dropout: 10% 35 | -> Conv 1D: 64 filters, 16 kernel_size, relu, L2 regularizer 36 | -> Dropout: 10% 37 | -> Conv 1D: 96 filters, 8 kernel_size, relu, L2 regularizer 38 | -> Dropout: 10% 39 | -> Global Maximum Pooling 1D 40 | 41 | Parameters: 42 | input_shape 43 | the input shape for the model, should be (window_size, num_channels) 44 | 45 | Returns: 46 | model (tf.keras.Model) 47 | """ 48 | 49 | inputs = tf.keras.Input(shape=input_shape, name='input') 50 | x = inputs 51 | x = tf.keras.layers.Conv1D( 52 | 32, 24, 53 | activation='relu', 54 | kernel_regularizer=tf.keras.regularizers.l2(l=1e-4) 55 | )(x) 56 | x = tf.keras.layers.Dropout(0.1)(x) 57 | 58 | x = tf.keras.layers.Conv1D( 59 | 64, 16, 60 | activation='relu', 61 | kernel_regularizer=tf.keras.regularizers.l2(l=1e-4), 62 | )(x) 63 | x = tf.keras.layers.Dropout(0.1)(x) 64 | 65 | x = tf.keras.layers.Conv1D( 66 | 96, 8, 67 | activation='relu', 68 | kernel_regularizer=tf.keras.regularizers.l2(l=1e-4), 69 | )(x) 70 | x = tf.keras.layers.Dropout(0.1)(x) 71 | 72 | x = tf.keras.layers.GlobalMaxPool1D(data_format='channels_last', name='global_max_pooling1d')(x) 73 | 74 | return tf.keras.Model(inputs, x, name=model_name) 75 | 76 | def attach_simclr_head(base_model, hidden_1=256, hidden_2=128, hidden_3=50): 77 | """ 78 | Attach a 3-layer fully-connected encoding head 79 | 80 | Architecture: 81 | base_model 82 | -> Dense: hidden_1 units 83 | -> ReLU 84 | -> Dense: hidden_2 units 85 | -> ReLU 86 | -> Dense: hidden_3 units 87 | """ 88 | 89 | input = base_model.input 90 | x = base_model.output 91 | 92 | projection_1 = tf.keras.layers.Dense(hidden_1)(x) 93 | projection_1 = tf.keras.layers.Activation("relu")(projection_1) 94 | projection_2 = tf.keras.layers.Dense(hidden_2)(projection_1) 95 | projection_2 = tf.keras.layers.Activation("relu")(projection_2) 96 | projection_3 = tf.keras.layers.Dense(hidden_3)(projection_2) 97 | 98 | simclr_model = tf.keras.Model(input, projection_3, name= base_model.name + "_simclr") 99 | 100 | return simclr_model 101 | 102 | 103 | def create_linear_model_from_base_model(base_model, output_shape, intermediate_layer=7): 104 | 105 | """ 106 | Create a linear classification model from the base mode, using activitations from an intermediate layer 107 | 108 | Architecture: 109 | base_model-intermediate_layer 110 | -> Dense: output_shape units 111 | -> Softmax 112 | 113 | Optimizer: SGD 114 | Loss: CategoricalCrossentropy 115 | 116 | Parameters: 117 | base_model 118 | the base model from which the activations are extracted 119 | 120 | output_shape 121 | number of output classifiction categories 122 | 123 | intermediate_layer 124 | the index of the intermediate layer from which the activations are extracted 125 | 126 | Returns: 127 | trainable_model (tf.keras.Model) 128 | """ 129 | 130 | inputs = base_model.inputs 131 | x = base_model.layers[intermediate_layer].output 132 | x = tf.keras.layers.Dense(output_shape, kernel_initializer=tf.random_normal_initializer(stddev=.01))(x) 133 | outputs = tf.keras.layers.Softmax()(x) 134 | 135 | model = tf.keras.Model(inputs=inputs, outputs=outputs, name=base_model.name + "linear") 136 | 137 | for layer in model.layers[:intermediate_layer+1]: 138 | layer.trainable = False 139 | 140 | model.compile( 141 | optimizer=tf.keras.optimizers.SGD(learning_rate=0.03), 142 | loss=tf.keras.losses.CategoricalCrossentropy(), 143 | metrics=[tf.keras.metrics.CategoricalAccuracy(name="categorical_accuracy"), tf.keras.metrics.AUC(name="auc"), tf.keras.metrics.Precision(name="precision"), tf.keras.metrics.Recall(name="recall")] 144 | ) 145 | return model 146 | 147 | 148 | def create_full_classification_model_from_base_model(base_model, output_shape, model_name="TPN", intermediate_layer=7, last_freeze_layer=4): 149 | """ 150 | Create a full 2-layer classification model from the base mode, using activitations from an intermediate layer with partial freezing 151 | 152 | Architecture: 153 | base_model-intermediate_layer 154 | -> Dense: 1024 units 155 | -> ReLU 156 | -> Dense: output_shape units 157 | -> Softmax 158 | 159 | Optimizer: Adam 160 | Loss: CategoricalCrossentropy 161 | 162 | Parameters: 163 | base_model 164 | the base model from which the activations are extracted 165 | 166 | output_shape 167 | number of output classifiction categories 168 | 169 | model_name 170 | name of the output model 171 | 172 | intermediate_layer 173 | the index of the intermediate layer from which the activations are extracted 174 | 175 | last_freeze_layer 176 | the index of the last layer to be frozen for fine-tuning (including the layer with the index) 177 | 178 | Returns: 179 | trainable_model (tf.keras.Model) 180 | """ 181 | 182 | # inputs = base_model.inputs 183 | intermediate_x = base_model.layers[intermediate_layer].output 184 | 185 | x = tf.keras.layers.Dense(1024, activation='relu')(intermediate_x) 186 | x = tf.keras.layers.Dense(output_shape)(x) 187 | outputs = tf.keras.layers.Softmax()(x) 188 | 189 | model = tf.keras.Model(inputs=base_model.inputs, outputs=outputs, name=model_name) 190 | 191 | for layer in model.layers: 192 | layer.trainable = False 193 | 194 | for layer in model.layers[last_freeze_layer+1:]: 195 | layer.trainable = True 196 | 197 | model.compile( 198 | optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), 199 | loss=tf.keras.losses.CategoricalCrossentropy(), 200 | metrics=[tf.keras.metrics.CategoricalAccuracy(name="categorical_accuracy"), tf.keras.metrics.AUC(name="auc"), tf.keras.metrics.Precision(name="precision"), tf.keras.metrics.Recall(name="recall")] 201 | ) 202 | 203 | return model 204 | 205 | 206 | def extract_intermediate_model_from_base_model(base_model, intermediate_layer=7): 207 | """ 208 | Create an intermediate model from base mode, which outputs embeddings of the intermediate layer 209 | 210 | Parameters: 211 | base_model 212 | the base model from which the intermediate model is built 213 | 214 | intermediate_layer 215 | the index of the intermediate layer from which the activations are extracted 216 | 217 | Returns: 218 | model (tf.keras.Model) 219 | """ 220 | 221 | model = tf.keras.Model(inputs=base_model.inputs, outputs=base_model.layers[intermediate_layer].output, name=base_model.name + "_layer_" + str(intermediate_layer)) 222 | return model 223 | 224 | -------------------------------------------------------------------------------- /simclr_utitlities.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | import sklearn.metrics 4 | 5 | import data_pre_processing 6 | 7 | __author__ = "C. I. Tang" 8 | __copyright__ = """Copyright (C) 2020 C. I. Tang""" 9 | 10 | """ 11 | This file includes software licensed under the Apache License 2.0, modified by C. I. Tang. 12 | 13 | Based on work of Tang et al.: https://arxiv.org/abs/2011.11542 14 | Contact: cit27@cl.cam.ac.uk 15 | License: GNU General Public License v3.0 16 | 17 | This program is free software: you can redistribute it and/or modify 18 | it under the terms of the GNU General Public License as published by 19 | the Free Software Foundation, either version 3 of the License, or 20 | (at your option) any later version. 21 | 22 | This program is distributed in the hope that it will be useful, 23 | but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | GNU General Public License for more details. 26 | 27 | You should have received a copy of the GNU General Public License 28 | along with this program. If not, see . 29 | """ 30 | 31 | def generate_composite_transform_function_simple(transform_funcs): 32 | """ 33 | Create a composite transformation function by composing transformation functions 34 | 35 | Parameters: 36 | transform_funcs 37 | list of transformation functions 38 | the function is composed by applying 39 | transform_funcs[0] -> transform_funcs[1] -> ... 40 | i.e. f(x) = f3(f2(f1(x))) 41 | 42 | Returns: 43 | combined_transform_func 44 | a composite transformation function 45 | """ 46 | for i, func in enumerate(transform_funcs): 47 | print(i, func) 48 | def combined_transform_func(sample): 49 | for func in transform_funcs: 50 | sample = func(sample) 51 | return sample 52 | return combined_transform_func 53 | 54 | def generate_combined_transform_function(transform_funcs, indices=[0]): 55 | """ 56 | Create a composite transformation function by composing transformation functions 57 | 58 | Parameters: 59 | transform_funcs 60 | list of transformation functions 61 | 62 | indices 63 | list of indices corresponding to the transform_funcs 64 | the function is composed by applying 65 | function indices[0] -> function indices[1] -> ... 66 | i.e. f(x) = f3(f2(f1(x))) 67 | 68 | Returns: 69 | combined_transform_func 70 | a composite transformation function 71 | """ 72 | 73 | for index in indices: 74 | print(transform_funcs[index]) 75 | def combined_transform_func(sample): 76 | for index in indices: 77 | sample = transform_funcs[index](sample) 78 | return sample 79 | return combined_transform_func 80 | 81 | def generate_slicing_transform_function(transform_func_structs, slicing_axis=2, concatenate_axis=2): 82 | """ 83 | Create a transformation function with slicing by applying different transformation functions to different slices. 84 | The output arrays are then concatenated at the specified axis. 85 | 86 | Parameters: 87 | transform_func_structs 88 | list of transformation function structs 89 | each transformation functions struct is a 2-tuple of (indices, transform_func) 90 | 91 | each transformation function is applied by 92 | transform_func(np.take(data, indices, slicing_axis)) 93 | 94 | all outputs are concatenated in the output axis (concatenate_axis) 95 | 96 | Example: 97 | transform_func_structs = [ 98 | ([0,1,2], transformations.rotation_transform_vectorized), 99 | ([3,4,5], transformations.time_flip_transform_vectorized) 100 | ] 101 | 102 | slicing_axis = 2 103 | the axis from which the slicing is applied 104 | (see numpy.take) 105 | 106 | concatenate_axis = 2 107 | the axis which the transformed array (tensors) are concatenated 108 | if it is None, a list will be returned 109 | 110 | Returns: 111 | slicing_transform_func 112 | a slicing transformation function 113 | """ 114 | def slicing_transform_func(sample): 115 | all_slices = [] 116 | for indices, transform_func in transform_func_structs: 117 | trasnformed_slice = transform_func(np.take(sample, indices, slicing_axis)) 118 | all_slices.append(trasnformed_slice) 119 | if concatenate_axis is None: 120 | return all_slices 121 | else: 122 | return np.concatenate(all_slices, axis=concatenate_axis) 123 | return slicing_transform_func 124 | 125 | 126 | def get_NT_Xent_loss_gradients(model, samples_transform_1, samples_transform_2, normalize=True, temperature=1.0, weights=1.0): 127 | """ 128 | A wrapper function for the NT_Xent_loss function which facilitates back propagation 129 | 130 | Parameters: 131 | model 132 | the deep learning model for feature learning 133 | 134 | samples_transform_1 135 | inputs samples subject to transformation 1 136 | 137 | samples_transform_2 138 | inputs samples subject to transformation 2 139 | 140 | normalize = True 141 | normalise the activations if true 142 | 143 | temperature = 1.0 144 | hyperparameter, the scaling factor of the logits 145 | (see NT_Xent_loss) 146 | 147 | weights = 1.0 148 | weights of different samples 149 | (see NT_Xent_loss) 150 | 151 | Return: 152 | loss 153 | the value of the NT_Xent_loss 154 | 155 | gradients 156 | the gradients for backpropagation 157 | """ 158 | with tf.GradientTape() as tape: 159 | hidden_features_transform_1 = model(samples_transform_1) 160 | hidden_features_transform_2 = model(samples_transform_2) 161 | loss = NT_Xent_loss(hidden_features_transform_1, hidden_features_transform_2, normalize=normalize, temperature=temperature, weights=weights) 162 | 163 | gradients = tape.gradient(loss, model.trainable_variables) 164 | return loss, gradients 165 | 166 | 167 | 168 | def simclr_train_model(model, dataset, optimizer, batch_size, transformation_function, temperature=1.0, epochs=100, is_trasnform_function_vectorized=False, verbose=0): 169 | """ 170 | Train a deep learning model using the SimCLR algorithm 171 | 172 | Parameters: 173 | model 174 | the deep learning model for feature learning 175 | 176 | dataset 177 | the numpy array for training (no labels) 178 | the first dimension should be the number of samples 179 | 180 | optimizer 181 | the optimizer for training 182 | e.g. tf.keras.optimizers.SGD() 183 | 184 | batch_size 185 | the batch size for mini-batch training 186 | 187 | transformation_function 188 | the stochastic (probabilistic) function for transforming data samples 189 | two different views of the sample is generated by applying transformation_function twice 190 | 191 | temperature = 1.0 192 | hyperparameter of the NT_Xent_loss, the scaling factor of the logits 193 | (see NT_Xent_loss) 194 | 195 | epochs = 100 196 | number of epochs of training 197 | 198 | is_trasnform_function_vectorized = False 199 | whether the transformation_function is vectorized 200 | i.e. whether the function accepts data in the batched form, or single-sample only 201 | vectorized functions reduce the need for an internal for loop on each sample 202 | 203 | verbose = 0 204 | debug messages are printed if > 0 205 | 206 | Return: 207 | (model, epoch_wise_loss) 208 | model 209 | the trained model 210 | epoch_wise_loss 211 | list of epoch losses during training 212 | """ 213 | 214 | epoch_wise_loss = [] 215 | 216 | for epoch in range(epochs): 217 | step_wise_loss = [] 218 | 219 | # Randomly shuffle the dataset 220 | shuffle_indices = data_pre_processing.np_random_shuffle_index(len(dataset)) 221 | shuffled_dataset = dataset[shuffle_indices] 222 | 223 | # Make a batched dataset 224 | batched_dataset = data_pre_processing.get_batched_dataset_generator(shuffled_dataset, batch_size) 225 | 226 | for data_batch in batched_dataset: 227 | 228 | # Apply transformation 229 | if is_trasnform_function_vectorized: 230 | transform_1 = transformation_function(data_batch) 231 | transform_2 = transformation_function(data_batch) 232 | else: 233 | transform_1 = np.array([transformation_function(data) for data in data_batch]) 234 | transform_2 = np.array([transformation_function(data) for data in data_batch]) 235 | 236 | # Forward propagation 237 | loss, gradients = get_NT_Xent_loss_gradients(model, transform_1, transform_2, normalize=True, temperature=temperature, weights=1.0) 238 | 239 | optimizer.apply_gradients(zip(gradients, model.trainable_variables)) 240 | step_wise_loss.append(loss) 241 | 242 | epoch_wise_loss.append(np.mean(step_wise_loss)) 243 | 244 | if verbose > 0: 245 | print("epoch: {} loss: {:.3f}".format(epoch + 1, np.mean(step_wise_loss))) 246 | 247 | return model, epoch_wise_loss 248 | 249 | 250 | def evaluate_model_simple(pred, truth, is_one_hot=True, return_dict=True): 251 | """ 252 | Evaluate the prediction results of a model with 7 different metrics 253 | Metrics: 254 | Confusion Matrix 255 | F1 Macro 256 | F1 Micro 257 | F1 Weighted 258 | Precision 259 | Recall 260 | Kappa (sklearn.metrics.cohen_kappa_score) 261 | 262 | Parameters: 263 | pred 264 | predictions made by the model 265 | 266 | truth 267 | the ground-truth labels 268 | 269 | is_one_hot=True 270 | whether the predictions and ground-truth labels are one-hot encoded or not 271 | 272 | return_dict=True 273 | whether to return the results in dictionary form (return a tuple if False) 274 | 275 | Return: 276 | results 277 | dictionary with 7 entries if return_dict=True 278 | tuple of size 7 if return_dict=False 279 | """ 280 | 281 | if is_one_hot: 282 | truth_argmax = np.argmax(truth, axis=1) 283 | pred_argmax = np.argmax(pred, axis=1) 284 | else: 285 | truth_argmax = truth 286 | pred_argmax = pred 287 | 288 | test_cm = sklearn.metrics.confusion_matrix(truth_argmax, pred_argmax) 289 | test_f1 = sklearn.metrics.f1_score(truth_argmax, pred_argmax, average='macro') 290 | test_precision = sklearn.metrics.precision_score(truth_argmax, pred_argmax, average='macro') 291 | test_recall = sklearn.metrics.recall_score(truth_argmax, pred_argmax, average='macro') 292 | test_kappa = sklearn.metrics.cohen_kappa_score(truth_argmax, pred_argmax) 293 | 294 | test_f1_micro = sklearn.metrics.f1_score(truth_argmax, pred_argmax, average='micro') 295 | test_f1_weighted = sklearn.metrics.f1_score(truth_argmax, pred_argmax, average='weighted') 296 | 297 | if return_dict: 298 | return { 299 | 'Confusion Matrix': test_cm, 300 | 'F1 Macro': test_f1, 301 | 'F1 Micro': test_f1_micro, 302 | 'F1 Weighted': test_f1_weighted, 303 | 'Precision': test_precision, 304 | 'Recall': test_recall, 305 | 'Kappa': test_kappa 306 | } 307 | else: 308 | return (test_cm, test_f1, test_f1_micro, test_f1_weighted, test_precision, test_recall, test_kappa) 309 | 310 | """ 311 | The following section of this file includes software licensed under the Apache License 2.0, by The SimCLR Authors 2020, modified by C. I. Tang. 312 | You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 313 | """ 314 | 315 | @tf.function 316 | def NT_Xent_loss(hidden_features_transform_1, hidden_features_transform_2, normalize=True, temperature=1.0, weights=1.0): 317 | """ 318 | The normalised temperature-scaled cross entropy loss function of SimCLR Contrastive training 319 | Reference: Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A simple framework for contrastive learning of visual representations. arXiv preprint arXiv:2002.05709. 320 | https://github.com/google-research/simclr/blob/master/objective.py 321 | 322 | Parameters: 323 | hidden_features_transform_1 324 | the features (activations) extracted from the inputs after applying transformation 1 325 | e.g. model(transform_1(X)) 326 | 327 | hidden_features_transform_2 328 | the features (activations) extracted from the inputs after applying transformation 2 329 | e.g. model(transform_2(X)) 330 | 331 | normalize = True 332 | normalise the activations if true 333 | 334 | temperature 335 | hyperparameter, the scaling factor of the logits 336 | 337 | weights 338 | weights of different samples 339 | 340 | Return: 341 | loss 342 | the value of the NT_Xent_loss 343 | """ 344 | LARGE_NUM = 1e9 345 | entropy_function = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) 346 | batch_size = tf.shape(hidden_features_transform_1)[0] 347 | 348 | h1 = hidden_features_transform_1 349 | h2 = hidden_features_transform_2 350 | if normalize: 351 | h1 = tf.math.l2_normalize(h1, axis=1) 352 | h2 = tf.math.l2_normalize(h2, axis=1) 353 | 354 | labels = tf.range(batch_size) 355 | masks = tf.one_hot(tf.range(batch_size), batch_size) 356 | 357 | logits_aa = tf.matmul(h1, h1, transpose_b=True) / temperature 358 | # Suppresses the logit of the repeated sample, which is in the diagonal of logit_aa 359 | # i.e. the product of h1[x] . h1[x] 360 | logits_aa = logits_aa - masks * LARGE_NUM 361 | logits_bb = tf.matmul(h2, h2, transpose_b=True) / temperature 362 | logits_bb = logits_bb - masks * LARGE_NUM 363 | logits_ab = tf.matmul(h1, h2, transpose_b=True) / temperature 364 | logits_ba = tf.matmul(h2, h1, transpose_b=True) / temperature 365 | 366 | 367 | loss_a = entropy_function(labels, tf.concat([logits_ab, logits_aa], 1), sample_weight=weights) 368 | loss_b = entropy_function(labels, tf.concat([logits_ba, logits_bb], 1), sample_weight=weights) 369 | loss = loss_a + loss_b 370 | 371 | return loss 372 | -------------------------------------------------------------------------------- /transformations.py: -------------------------------------------------------------------------------- 1 | "Vectorized transformation functions for mobile sensor time series" 2 | import itertools 3 | import numpy as np 4 | import scipy.interpolate 5 | 6 | __author__ = "C. I. Tang" 7 | __copyright__ = "Copyright (C) 2020 C. I. Tang" 8 | 9 | """ 10 | Based on work of Tang et al.: https://arxiv.org/abs/2011.11542 11 | Contact: cit27@cl.cam.ac.uk 12 | License: GNU General Public License v3.0 13 | 14 | This program is free software: you can redistribute it and/or modify 15 | it under the terms of the GNU General Public License as published by 16 | the Free Software Foundation, either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License 25 | along with this program. If not, see . 26 | 27 | An re-implemention of 28 | T. T. Um et al., “Data augmentation of wearable sensor data for parkinson’s disease monitoring using convolutional neural networks,” in Proceedings of the 19th ACM International Conference on Multimodal Interaction, ser. ICMI 2017. New York, NY, USA: ACM, 2017, pp. 216–220. 29 | 30 | https://dl.acm.org/citation.cfm?id=3136817 31 | 32 | https://arxiv.org/abs/1706.00527 33 | 34 | @inproceedings{TerryUm_ICMI2017, author = {Um, Terry T. and Pfister, Franz M. J. and Pichler, Daniel and Endo, Satoshi and Lang, Muriel and Hirche, Sandra and Fietzek, Urban and Kuli\'{c}, Dana}, title = {Data Augmentation of Wearable Sensor Data for Parkinson's Disease Monitoring Using Convolutional Neural Networks}, booktitle = {Proceedings of the 19th ACM International Conference on Multimodal Interaction}, series = {ICMI 2017}, year = {2017}, isbn = {978-1-4503-5543-8}, location = {Glasgow, UK}, pages = {216--220}, numpages = {5}, doi = {10.1145/3136755.3136817}, acmid = {3136817}, publisher = {ACM}, address = {New York, NY, USA}, keywords = {Parkinson\'s disease, convolutional neural networks, data augmentation, health monitoring, motor state detection, wearable sensor}, } 35 | 36 | """ 37 | 38 | def noise_transform_vectorized(X, sigma=0.05): 39 | """ 40 | Adding random Gaussian noise with mean 0 41 | """ 42 | noise = np.random.normal(loc=0, scale=sigma, size=X.shape) 43 | return X + noise 44 | 45 | def scaling_transform_vectorized(X, sigma=0.1): 46 | """ 47 | Scaling by a random factor 48 | """ 49 | scaling_factor = np.random.normal(loc=1.0, scale=sigma, size=(X.shape[0], 1, X.shape[2])) 50 | return X * scaling_factor 51 | 52 | def rotation_transform_vectorized(X): 53 | """ 54 | Applying a random 3D rotation 55 | """ 56 | axes = np.random.uniform(low=-1, high=1, size=(X.shape[0], X.shape[2])) 57 | angles = np.random.uniform(low=-np.pi, high=np.pi, size=(X.shape[0])) 58 | matrices = axis_angle_to_rotation_matrix_3d_vectorized(axes, angles) 59 | 60 | return np.matmul(X, matrices) 61 | 62 | def axis_angle_to_rotation_matrix_3d_vectorized(axes, angles): 63 | """ 64 | Get the rotational matrix corresponding to a rotation of (angle) radian around the axes 65 | 66 | Reference: the Transforms3d package - transforms3d.axangles.axangle2mat 67 | Formula: http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle 68 | """ 69 | axes = axes / np.linalg.norm(axes, ord=2, axis=1, keepdims=True) 70 | x = axes[:, 0]; y = axes[:, 1]; z = axes[:, 2] 71 | c = np.cos(angles) 72 | s = np.sin(angles) 73 | C = 1 - c 74 | 75 | xs = x*s; ys = y*s; zs = z*s 76 | xC = x*C; yC = y*C; zC = z*C 77 | xyC = x*yC; yzC = y*zC; zxC = z*xC 78 | 79 | m = np.array([ 80 | [ x*xC+c, xyC-zs, zxC+ys ], 81 | [ xyC+zs, y*yC+c, yzC-xs ], 82 | [ zxC-ys, yzC+xs, z*zC+c ]]) 83 | matrix_transposed = np.transpose(m, axes=(2,0,1)) 84 | return matrix_transposed 85 | 86 | def negate_transform_vectorized(X): 87 | """ 88 | Inverting the signals 89 | """ 90 | return X * -1 91 | 92 | def time_flip_transform_vectorized(X): 93 | """ 94 | Reversing the direction of time 95 | """ 96 | return X[:, ::-1, :] 97 | 98 | 99 | def channel_shuffle_transform_vectorized(X): 100 | """ 101 | Shuffling the different channels 102 | 103 | Note: it might consume a lot of memory if the number of channels is high 104 | """ 105 | channels = range(X.shape[2]) 106 | all_channel_permutations = np.array(list(itertools.permutations(channels))[1:]) 107 | 108 | random_permutation_indices = np.random.randint(len(all_channel_permutations), size=(X.shape[0])) 109 | permuted_channels = all_channel_permutations[random_permutation_indices] 110 | X_transformed = X[np.arange(X.shape[0])[:, np.newaxis, np.newaxis], np.arange(X.shape[1])[np.newaxis, :, np.newaxis], permuted_channels[:, np.newaxis, :]] 111 | return X_transformed 112 | 113 | def time_segment_permutation_transform_improved(X, num_segments=4): 114 | """ 115 | Randomly scrambling sections of the signal 116 | """ 117 | segment_points_permuted = np.random.choice(X.shape[1], size=(X.shape[0], num_segments)) 118 | segment_points = np.sort(segment_points_permuted, axis=1) 119 | 120 | X_transformed = np.empty(shape=X.shape) 121 | for i, (sample, segments) in enumerate(zip(X, segment_points)): 122 | # print(sample.shape) 123 | splitted = np.array(np.split(sample, np.append(segments, X.shape[1]))) 124 | np.random.shuffle(splitted) 125 | concat = np.concatenate(splitted, axis=0) 126 | X_transformed[i] = concat 127 | return X_transformed 128 | 129 | def get_cubic_spline_interpolation(x_eval, x_data, y_data): 130 | """ 131 | Get values for the cubic spline interpolation 132 | """ 133 | cubic_spline = scipy.interpolate.CubicSpline(x_data, y_data) 134 | return cubic_spline(x_eval) 135 | 136 | 137 | def time_warp_transform_improved(X, sigma=0.2, num_knots=4): 138 | """ 139 | Stretching and warping the time-series 140 | """ 141 | time_stamps = np.arange(X.shape[1]) 142 | knot_xs = np.arange(0, num_knots + 2, dtype=float) * (X.shape[1] - 1) / (num_knots + 1) 143 | spline_ys = np.random.normal(loc=1.0, scale=sigma, size=(X.shape[0] * X.shape[2], num_knots + 2)) 144 | 145 | spline_values = np.array([get_cubic_spline_interpolation(time_stamps, knot_xs, spline_ys_individual) for spline_ys_individual in spline_ys]) 146 | 147 | cumulative_sum = np.cumsum(spline_values, axis=1) 148 | distorted_time_stamps_all = cumulative_sum / cumulative_sum[:, -1][:, np.newaxis] * (X.shape[1] - 1) 149 | 150 | X_transformed = np.empty(shape=X.shape) 151 | for i, distorted_time_stamps in enumerate(distorted_time_stamps_all): 152 | X_transformed[i // X.shape[2], :, i % X.shape[2]] = np.interp(time_stamps, distorted_time_stamps, X[i // X.shape[2], :, i % X.shape[2]]) 153 | return X_transformed 154 | 155 | def time_warp_transform_low_cost(X, sigma=0.2, num_knots=4, num_splines=150): 156 | """ 157 | Stretching and warping the time-series (low cost) 158 | """ 159 | time_stamps = np.arange(X.shape[1]) 160 | knot_xs = np.arange(0, num_knots + 2, dtype=float) * (X.shape[1] - 1) / (num_knots + 1) 161 | spline_ys = np.random.normal(loc=1.0, scale=sigma, size=(num_splines, num_knots + 2)) 162 | 163 | spline_values = np.array([get_cubic_spline_interpolation(time_stamps, knot_xs, spline_ys_individual) for spline_ys_individual in spline_ys]) 164 | 165 | cumulative_sum = np.cumsum(spline_values, axis=1) 166 | distorted_time_stamps_all = cumulative_sum / cumulative_sum[:, -1][:, np.newaxis] * (X.shape[1] - 1) 167 | 168 | random_indices = np.random.randint(num_splines, size=(X.shape[0] * X.shape[2])) 169 | 170 | X_transformed = np.empty(shape=X.shape) 171 | for i, random_index in enumerate(random_indices): 172 | X_transformed[i // X.shape[2], :, i % X.shape[2]] = np.interp(time_stamps, distorted_time_stamps_all[random_index], X[i // X.shape[2], :, i % X.shape[2]]) 173 | return X_transformed --------------------------------------------------------------------------------