├── .DS_Store ├── .idea ├── .gitignore ├── .name ├── TorchProjects.iml ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── jupyter-settings.xml ├── misc.xml ├── modules.xml └── vcs.xml ├── LICENSE ├── Model ├── model01.pth └── module.py ├── PaperReplicate ├── .DS_Store ├── Self_Attention_from_Scratch │ ├── .DS_Store │ ├── Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38.md │ ├── Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38 │ │ ├── Untitled 1.png │ │ ├── Untitled 2.png │ │ ├── Untitled 3.png │ │ ├── Untitled 4.png │ │ ├── Untitled 5.png │ │ ├── Untitled 6.png │ │ └── Untitled.png │ ├── self_attention.py │ └── self_attention_mechanism.ipynb ├── VisionTransformer │ └── replicate_vit.ipynb ├── data_setup.py ├── helper_functions.py ├── predictions.py └── utils.py ├── PracticePytorch ├── .DS_Store ├── 02.Classification.ipynb ├── 03CV.ipynb ├── 04.CustomData.ipynb ├── 06.TransferLearning.ipynb ├── 07.ExperimentsTracking.ipynb ├── Custom_dataset_dataloader_transform.ipynb ├── backbone.py ├── c2.ipynb ├── faces │ ├── 0805personali01.jpg │ ├── 1084239450_e76e00b7e7.jpg │ ├── 10comm-decarlo.jpg │ ├── 110276240_bec305da91.jpg │ ├── 1198_0_861.jpg │ ├── 137341995_e7c48e9a75.jpg │ ├── 1383023626_8a49e4879a.jpg │ ├── 144044282_87cf3ff76e.jpg │ ├── 152601997_ec6429a43c.jpg │ ├── 1549040388_b99e9fa295.jpg │ ├── 1878519279_f905d4f34e.jpg │ ├── 2046713398_91aaa6fe1c.jpg │ ├── 2173711035_dbd53b4f9f.jpg │ ├── 2210514040_6b03ff2629.jpg │ ├── 2322901504_08122b01ba.jpg │ ├── 2327253037_66a61ea6fe.jpg │ ├── 2328398005_d328a70b4c.jpg │ ├── 2370961440_6bc8ce346c.jpg │ ├── 2382SJ8.jpg │ ├── 252418361_440b75751b.jpg │ ├── 262007783_943bbcf613.jpg │ ├── 2633371780_45b740b670.jpg │ ├── 2647088981_60e9fe40cd.jpg │ ├── 2711409561_a0786a3d3d.jpg │ ├── 2722779845_7fcb64a096.jpg │ ├── 2795838930_0cc5aa5f41.jpg │ ├── 2902323565_100017b63c.jpg │ ├── 2902760364_89c50bde40.jpg │ ├── 2956581526_cd803f2daa.jpg │ ├── 297448785_b2dda4b2c0.jpg │ ├── 299733036_fff5ea6f8e.jpg │ ├── 303808204_1f744bc407.jpg │ ├── 3074791551_baee7fa0c1.jpg │ ├── 3152653555_68322314f3.jpg │ ├── 3264867945_fe18d442c1.jpg │ ├── 3273658251_b95f65c244.jpg │ ├── 3298715079_5af7c78fcb.jpg │ ├── 3325611505_ddc7beffa1.jpg │ ├── 3362762930_24f76cb89c.jpg │ ├── 343583208_e986824d77.jpg │ ├── 3461016494_56cce9c984.jpg │ ├── 348272697_832ce65324.jpg │ ├── 3534188114_2108895291.jpg │ ├── 3534189272_8ef88ba368.jpg │ ├── 3555944509_7b477069c6.jpg │ ├── 3574737496_6ee8207045.jpg │ ├── 362167809_d5a5dcbfdb.jpg │ ├── 363149951_8be04dc6c0.jpg │ ├── 3638950581_3387685d3a.jpg │ ├── 3646828311_bfeb429ef7.jpg │ ├── 3689162471_5f9ffb5aa0.jpg │ ├── 3718903026_c1bf5dfcf8.jpg │ ├── 3790616528_297c0ac935.jpg │ ├── 3855944735_e252959937.jpg │ ├── 3856149136_d4595ffdd4.jpg │ ├── 3872768751_e60d7fdbd5.jpg │ ├── 529447797_0f9d2fb756.jpg │ ├── 57635685_d41c98f8ca.jpg │ ├── 809285949_6889026b53.jpg │ ├── 92053278_be61a225d2.jpg │ ├── 96063776_bdb3617b64.jpg │ ├── 97308305_4b737d0873.jpg │ ├── britney-bald.jpg │ ├── create_landmark_dataset.py │ ├── deeny.peggy.jpg │ ├── face_landmarks.csv │ ├── matt-mathes.jpg │ ├── person-7.jpg │ ├── person.jpg │ ├── person_TjahjonoDGondhowiardjo.jpg │ └── personalpic.jpg └── runs │ ├── Jun18_14-46-04_Sherlocks-MacBook-Pro.local │ └── events.out.tfevents.1687117564.Sherlocks-MacBook-Pro.local.51259.0 │ ├── Jun18_15-03-00_Sherlocks-MacBook-Pro.local │ ├── events.out.tfevents.1687118580.Sherlocks-MacBook-Pro.local.51259.1 │ └── events.out.tfevents.1687119446.Sherlocks-MacBook-Pro.local.51259.2 │ └── efficientnet_b0_pizza_steak_sushi │ ├── events.out.tfevents.1686965428.Sherlocks-MacBook-Pro.local.31548.0 │ ├── events.out.tfevents.1686965887.Sherlocks-MacBook-Pro.local.32194.0 │ └── events.out.tfevents.1686966251.Sherlocks-MacBook-Pro.local.32194.1 ├── Python&Probability&Statistics └── BasicPython │ └── Numpy_Exercise.ipynb ├── README.md ├── Signal_Processing ├── .DS_Store ├── Intro │ ├── .DS_Store │ ├── glassDance.mat │ ├── sigprocMXC_filterGlass.ipynb │ └── sigprocMXC_filterGlass.m ├── SelectiveSearch │ ├── Part 3 Object Detection with Pascal VOC2012 - Selective Search.ipynb │ ├── __pycache__ │ │ └── slective_search.cpython-310.pyc │ ├── image │ │ ├── 2012_001297.jpg │ │ ├── cats.png │ │ ├── example_id1.JPG │ │ ├── example_id2.JPG │ │ ├── example_id3.JPG │ │ ├── example_id4.JPG │ │ └── example_image_easy.JPG │ └── slective_search.py └── TimeSeriesDenoising │ ├── .DS_Store │ ├── denoising_codeChallenge.mat │ ├── emg4TKEO.mat │ ├── eyedat.mat │ ├── read_data.py │ ├── sigprocMXC_timeSeriesDenoising.ipynb │ └── templateProjection.mat ├── __pycache__ ├── data_setup.cpython-310.pyc ├── data_setup.cpython-38.pyc ├── helper_functions.cpython-38.pyc ├── helper_functions.cpython-39.pyc ├── module.cpython-38.pyc ├── utils.cpython-310.pyc └── utils.cpython-38.pyc └── test.ipynb /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/.DS_Store -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | sigprocMXC_filterGlass.ipynb -------------------------------------------------------------------------------- /.idea/TorchProjects.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 31 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/jupyter-settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 33 | 34 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Model/model01.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Model/model01.pth -------------------------------------------------------------------------------- /Model/module.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | class PatchEmbedding(nn.Module): 5 | def __init__( 6 | self, 7 | in_channels: int = 3, 8 | patch_size: int = 16, 9 | embedding_dim: int = 768 10 | ): 11 | super().__init__() 12 | self.patch_size = patch_size 13 | self.patcher = nn.Conv2d( 14 | in_channels = in_channels, 15 | out_channels = embedding_dim, 16 | kernel_size = patch_size, 17 | stride = patch_size, 18 | padding = 0 19 | ) 20 | self.flattener = nn.Flatten(start_dim = 2, end_dim = 3) 21 | 22 | def forward(self, x): 23 | image_size = x.shape[-1] 24 | assert image_size % self.patch_size == 0, f"Input image size must be divisible by patch " \ 25 | f"size, please re-check the patch size:" \ 26 | f"{self.patch_size} and the image size: " \ 27 | f"{image_size}." 28 | 29 | return self.flattener(self.patcher(x)).permute(0, 2, 1) 30 | 31 | 32 | class MSA(nn.Module): 33 | def __init__( 34 | self, 35 | embedding_dim: int = 768, 36 | h = 12, 37 | dropout: float = .0 38 | ): 39 | super().__init__() 40 | self.norm_layer = nn.LayerNorm(normalized_shape = embedding_dim) 41 | self.multi_head_attention = nn.MultiheadAttention( 42 | embed_dim = embedding_dim, 43 | num_heads = h, 44 | dropout = dropout, 45 | batch_first = True 46 | ) 47 | 48 | def forward(self, x): 49 | x = self.norm_layer(x) 50 | # we don't need the attention weights but just the layer output, so need_weights = Flase 51 | x, _ = self.multi_head_attention(query = x, key = x, value = x, need_weights = False) 52 | return x 53 | 54 | 55 | class MLP(nn.Module): 56 | def __init__(self, embedding_dim: int = 768, mlp_size: int = 3072, dropout: float = .1): 57 | super().__init__() 58 | self.norm = nn.LayerNorm(normalized_shape = embedding_dim) 59 | self.mlp_body = nn.Sequential( 60 | nn.Linear(in_features = embedding_dim, out_features = mlp_size), 61 | nn.GELU(), 62 | nn.Dropout(p = dropout), 63 | nn.Linear(in_features = mlp_size, out_features = embedding_dim), 64 | nn.Dropout(p = dropout) 65 | ) 66 | 67 | def forward(self, x): 68 | x = self.norm(x) 69 | x = self.mlp_body(x) 70 | return x 71 | 72 | 73 | class Encoder(nn.Module): 74 | def __init__( 75 | self, embedding_dim: int = 768, h: int = 12, mlp_size: int = 3072, mlp_dropout: 76 | float = .1, msa_dropout: float = .0 77 | ): 78 | super().__init__() 79 | self.msa = MSA(embedding_dim = embedding_dim, h = h, dropout = msa_dropout) 80 | self.mlp = MLP(embedding_dim = embedding_dim, mlp_size = mlp_size, dropout = mlp_dropout) 81 | 82 | def forward(self, x): 83 | x = self.msa(x) + x 84 | x = self.mlp(x) + x 85 | return x 86 | 87 | class StandardVit(nn.Module): 88 | def __init__(self, 89 | img_size: int = 224, 90 | in_channels: int = 3, 91 | patch_size: int = 16, 92 | transformer_layers_num: int = 12, 93 | embedding_dim: int = 768, 94 | mlp_size: int = 3072, 95 | h: int = 12, 96 | msa_dropout: float = .0, 97 | mlp_dropout: float = .1, 98 | embedding_dropout: float = .1, 99 | num_classes: int = 1000): 100 | super().__init__() 101 | assert img_size % patch_size == 0, f"Image size must be divisible by patch size, " \ 102 | f"image size: {img_size}, patch size: {patch_size}." 103 | 104 | self.patch_num = (img_size * img_size) // (patch_size ** 2) 105 | 106 | self.class_embedding = nn.Parameter(data = torch.randn(1, 1, embedding_dim), 107 | requires_grad = True) 108 | 109 | self.position_embedding = nn.Parameter( 110 | data = torch.randn(1, self.patch_num + 1, embedding_dim), requires_grad = True) 111 | 112 | self.embedding_dropout = nn.Dropout(p = embedding_dropout) 113 | 114 | self.patch_embedding = PatchEmbedding(in_channels = in_channels, patch_size = patch_size, 115 | embedding_dim = embedding_dim) 116 | 117 | self.transformer_encoder = nn.Sequential(*[Encoder(embedding_dim = embedding_dim, h = h, 118 | mlp_size = mlp_size, mlp_dropout = 119 | mlp_dropout, msa_dropout = 120 | msa_dropout) for _ in range(transformer_layers_num)]) 121 | 122 | self.classifier = nn.Sequential(nn.LayerNorm(normalized_shape = embedding_dim), 123 | nn.Linear(in_features = embedding_dim, out_features = num_classes)) 124 | 125 | 126 | def forward(self, x): 127 | batch_size = x.shape[0] 128 | 129 | class_token = self.class_embedding.expand(batch_size, -1, -1) 130 | 131 | x = self.patch_embedding(x) 132 | 133 | x = torch.cat((class_token, x), dim = 1) 134 | 135 | x = self.position_embedding + x 136 | 137 | x = self.embedding_dropout(x) 138 | 139 | x = self.transformer_encoder(x) 140 | 141 | x = self.classifier(x[:, 0]) 142 | 143 | return x 144 | 145 | 146 | class TinyVGG(nn.Module): 147 | def __init__(self, in_channel: int, hidden_unit: int, classes_num:int) -> None: 148 | self.block1 = nn.Sequential( 149 | nn.Conv2d(in_channels = in_channel, out_channels = hidden_unit, kernel_size = 3, 150 | stride = 1, padding = 0), 151 | nn.ReLU, 152 | nn.Conv2d(in_channels = hidden_unit, out_channels = hidden_unit, kernel_size = 3, 153 | stride = 1, padding = 0), 154 | nn.ReLU, 155 | nn.MaxPool2d(kernel_size = 2, stride = 2) 156 | ) 157 | 158 | self.block2 = nn.Sequential( 159 | nn.nn.Conv2d(in_channels = hidden_unit, out_channels = hidden_unit, kernel_size = 3, 160 | stride = 1, padding = 0), 161 | nn.ReLU, 162 | nn.Conv2d(in_channels = hidden_unit, out_channels = hidden_unit, kernel_size = 3, 163 | stride = 1, padding = 0), 164 | nn.ReLU, 165 | nn.MaxPool2d(kernel_size = 2, stride = 2) 166 | ) 167 | 168 | self.block3 = nn.Sequential( 169 | nn.Flatten(), 170 | nn.Linear(in_features = hidden_unit * 13 ** 2, out_features = classes_num) 171 | ) 172 | 173 | def forward(self, x): 174 | return self.block3(self.block2(self.block1(x))) 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | -------------------------------------------------------------------------------- /PaperReplicate/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/.DS_Store -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/.DS_Store -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38.md: -------------------------------------------------------------------------------- 1 | # Self-Attention and Multi-head Attention Mechanism 2 | 3 | Tags: Recap 4 | 5 | # Why Self-Attention? 6 | 7 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled.png) 8 | 9 | - The concept of “attention” in deep learning [has its roots in the effort to improve Recurrent Neural Networks (RNNs)](https://arxiv.org/abs/1409.0473) for handling longer sequences or sentences. 10 | - Translating a sentence word-by-word does not work effectively. 11 | - To overcome this issue, attention mechanisms were introduced to give access to all sequence elements at each time step. **The key is to be selective and determine which words are most important in a specific context**. 12 | - In 2017, the transformer architecture introduced a standalone self-attention mechanism, eliminating the need for RNNs altogether. 13 | 14 | # What is Self-Attention? 15 | 16 | - We can think of self-attention as a mechanism that **enhances the information content of an input embedding by including information about the input’s context**. In other words, the self-attention mechanism **enables the model to weigh the importance of different elements in an input sequence and dynamically adjust their influence on the output**. 17 | - This is especially important for language processing tasks, where the meaning of a word can change based on its context within a sentence or document. 18 | 19 | # How to Define Self-Attention? 20 | 21 | ## Embedding Input Sentence 22 | 23 | - For simplicity, here our dictionary dc is restricted to the words that occur in the input sentence. In a real-world application, we would consider all words in the training dataset (typical vocabulary sizes range between 30k to 50k). 24 | 25 | ```python 26 | sentence = "Life is short, eat dessert first" 27 | 28 | # Create Dictionary 29 | dict = {s : i for i, s in enumerate(sorted(sentence.replace(",", "").split()))} 30 | # dict: {'Life': 0, 'dessert': 1, 'eat': 2, 'first': 3, 'is': 4, 'short': 5} 31 | 32 | import torch 33 | sentence_idx = torch.tensor([dict[s] for s in sentence.replace(',', '').split()]) 34 | # sentence_idx: tensor([0, 4, 5, 2, 1, 3]) 35 | ``` 36 | 37 | ### Word Embedding 38 | 39 | - Here, we will use a 16-dimensional embedding such that each input word is represented by a 16-dimensional vector. 40 | 41 | ```python 42 | torch.manual_seed(123) 43 | embeder = torch.nn.Embedding(6, 16) 44 | embedded_sentence = embeder(sentence_idx).detach() # [6, 16] 45 | ``` 46 | 47 | ## Define Unnormalized Attention Weights 48 | 49 | ### Define Weight Matrices 50 | 51 | - Self-Attention uses three weight matrices, referred to as $W_q, W_k, W_v$, which are adjusted as model parameters during training. 52 | - These matrics serve to project the inputs into query , key, and value components of the sequence. 53 | 54 | $$\text{Query Sequence: } \mathbf{q}^{(\mathrm{i})}=\mathbf{W}_{\mathrm{q}} \mathbf{x}^{(\mathrm{i})} \text { for } \mathrm{i} \in[1, \mathrm{~T}]$$ 55 | 56 | 57 | $$\text{Key Sequence: } \mathbf{k}^{(\mathrm{i})}=\mathbf{W}_{\mathrm{k}} \mathbf{x}^{(\mathrm{i})} \text { for } \mathrm{i} \in[1, \mathrm{~T}]$$ 58 | 59 | $$\text{Value Sequence: } \mathbf{v}^{(\mathrm{i})}=\mathbf{W}_{\mathrm{v}} \mathbf{x}^{(\mathrm{i})} \text { for } \mathrm{i} \in[1, \mathrm{~T}]$$ 60 | 61 | $$\text{i refers to the token index position in the input sequence}$$ 62 | 63 | 64 | - Here, both $q^{(i)}, k^{(i)}$ are vectors of dim $d_k$; $v^{(i)}$ is the vector of dim $d_v$. 65 | $W_q,\ W_k$ have shape $d_k \times d$, $W_v$ has shape $d_v \times d$, $d$ is the embedding dim of each word vector $x^{(i)}$ 66 | - Since we are computing the dot-product between the query and key vectors, these two vectors have to contain the same number of elements ($d_q=d_k$). However, the number of elements in the value vector $d_v$ which determines the size of the resulting context vector, is arbitrary. 67 | 68 | ```python 69 | torch.manual_seed(123) 70 | 71 | d = embedded_sentence.shape[1] 72 | 73 | d_q, d_k, d_v = 24, 24, 28 74 | 75 | W_query = torch.nn.Parameter(torch.randn(d_q, d)) # [24, 16] 76 | W_key = torch.nn.Parameter(torch.randn(d_k, d)) # [24, 16] 77 | W_value = torch.nn.Parameter(torch.randn(d_v, d)) # [28, 16] 78 | 79 | ``` 80 | 81 | ### Compute the unnormalized weights 82 | 83 | We pick the second words $x^{(2)}$ as example 84 | 85 | ```python 86 | x_2 = embedded_sentence[1] 87 | query_2 = W_query @ x_2 # [24] 88 | key_2 = W_key @ x_2 # [24] 89 | value_2 = W_value @ x_2 # [28] 90 | 91 | # compute the remaining key-value for all inputs 92 | keys = (W_key @ embedded_sentence.T).T # [6, 24] 93 | values = (W_value @ embedded_sentence.T).T #[6, 28] 94 | 95 | ``` 96 | 97 | Then compute $\omega_{\mathrm{ij}}=\mathbf{q}^{(\mathrm{i})^{\top}} \mathbf{k}^{(\mathrm{j})}$ 98 | 99 | ```python 100 | # compute unnormalized attention weight for the query and 5th input element 101 | omega_24 = query_2.dot(keys[4]) # tensor(-98.1709, grad_fn=) 102 | # then we can let the 2nd word asks every other words 103 | omega_2 = query_2 @ keys.T # (tensor([ 83.1533, 95.5014, -100.8583, 63.5880, -98.1709, 9.3997], grad_fn=) 104 | 105 | ``` 106 | 107 | ## Computing Attention Score 108 | 109 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%201.png) 110 | 111 | - Then we need the normalized attention weights $\alpha$ by applying the softmax function. 112 | - $1/\sqrt d_k$ is used to scale $w$ before normalization, so that we can ensure that the Euclidean length of the weight vectors will be approximately in the same magnitude. 113 | - This helps prevent the attention weights from becoming too small or too large, which could lead to numerical instability or affect the model’s ability to converge during training. 114 | 115 | ```python 116 | import torch.nn.functional as F 117 | 118 | attention_weights_2 = F.softmax(omega_2 / d_k**0.5, dim=0) 119 | # tensor([7.4329e-02, 9.2430e-01, 3.6185e-18, 1.3699e-03, 6.2628e-18, 2.1523e-08],grad_fn=) 120 | 121 | ``` 122 | 123 | ## Compute Context Vector 124 | 125 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%202.png) 126 | 127 | - $z^{(2)}$ is an attention-weighted version of our original query input $x^{(2)}$ 128 | - The context vector represents the second word in the context of the entire sentence and can be used as input to subsequent layers in a neural network or other models. 129 | 130 | ```python 131 | context_vector_2 = attention_weights_2 @ values # [28] 132 | ``` 133 | 134 | ## Dimension Graph 135 | 136 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%203.png) 137 | 138 | ## Functionalized Version 139 | 140 | ```python 141 | def calc_attn(embedded_sentence: torch.Tensor, 142 | dim_q: int, 143 | dim_k: int, 144 | dim_v: int, 145 | ): 146 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 147 | 148 | hid_dim = embedded_sentence.shape[-1] 149 | W_Q = nn.Parameter(torch.randn(dim_q, hid_dim)) 150 | W_K = nn.Parameter(torch.randn(dim_k, hid_dim)) 151 | W_V = nn.Parameter(torch.randn(dim_v, hid_dim)) 152 | 153 | Q = (W_K @ embedded_sentence.T).T # (T, d_q) 154 | K = (W_Q @ embedded_sentence.T).T # (T, d_k) 155 | V = (W_V @ embedded_sentence.T).T # (T, d_v) 156 | 157 | attn = torch.softmax(1 / dim_k ** .5 * Q @ K.T, dim = 1) @ V # (T, d_v) 158 | 159 | return attn 160 | ``` 161 | 162 | # Multi-Head Attention 163 | 164 | ## Single-Head Attention 165 | 166 | In the scaled dot-product attention, the input sequence was transformed using three matrices representing the query, key, and value. 167 | 168 | - These three matrices can be considered as a single attention head in the context of multi-head attention. 169 | 170 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%204.png) 171 | 172 | ## Multi-Head Attention 173 | 174 | As its name implies, multi-head attention involves multiple such heads, each consisting of query, key, and value matrices. 175 | 176 | - The final dimension of the context vector should be $(head, d_v)$ 177 | 178 | ![Untitled](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%205.png) 179 | 180 | ### Functionalized Version 181 | 182 | ```python 183 | def multi_head_attn(embedded_sentence: torch.Tensor, 184 | head: int, 185 | dim_q: int, 186 | dim_k: int, 187 | dim_v: int): 188 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 189 | hid_dim = embedded_sentence.shape[-1] # dim 190 | stacked_embedded_sentence = embedded_sentence.repeat(head, 1, 1) # (head, T, dim) 191 | 192 | W_Q = nn.Parameter(torch.randn(head, dim_q, hid_dim)) # (h, d_q, dim) 193 | W_K = nn.Parameter(torch.randn(head, dim_k, hid_dim)) # (h, d_k, dim) 194 | W_V = nn.Parameter(torch.randn(head, dim_v, hid_dim)) # (h, d_v, dim) 195 | 196 | Q = (W_Q @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_q) 197 | K = (W_K @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_k) 198 | V = (W_V @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_v) 199 | 200 | mha = torch.softmax(1 / d_k ** .5 * Q @ K.transpose(1, 2), dim = 2) @ V # (h, T, d_v) 201 | 202 | return mha 203 | ``` 204 | 205 | ### For Single Token 206 | 207 | ```python 208 | head = 3 209 | 210 | # (3, 24, 16) 211 | multihead_W_query = torch.nn.Parameter(torch.randn(head, d_q, d)) 212 | multihead_W_key = torch.nn.Parameter(torch.randn(head, d_k, d)) 213 | # (3, 28, 16) 214 | multihead_W_value = torch.nn.Parameter(torch.randn(head, d_v, d)) 215 | 216 | # q, k, v for x_2 217 | multihead_query_2 = multihead_W_query @ x_2 # (3, 24) 218 | multihead_key_2 = multihead_W_key @ x_2 # (3, 24) 219 | multihead_value_2 = multihead_W_value @ x_2 # (3, 24) 220 | 221 | # x_2 asks each other words, then we need to calculate the k, v for other tokens 222 | # first, we need to expand the input sequence embeddings to the number of heads 223 | stacked_inputs = embedded_sentence.T.repeat(head, 1, 1) # (3, 16, 6) 224 | 225 | multihead_keys = torch.bmm(multihead_W_key, stacked_inputs)# (3, 24, 6) 226 | multihead_values = torch.bmm(multihead_W_value, stacked_inputs) # (3, 28, 6) 227 | 228 | # let x_2 asks every token -> unnormalized attention score 229 | multihead_query_2.unsqueeze(1) 230 | multihead_attention_unnormalized_score_2 = torch.bmm(multihead_query_2.unsqueeze(dim = 1), 231 | multihead_keys).squeeze() # (3, 6) 232 | # normalized multihead attention score 233 | multihead_attention_normalized_score_2 = F.softmax(multihead_attention_unnormalized_score_2 / d_k 234 | ** 0.5, dim = 1) # (3, 6) 235 | # multihead attention context score 236 | multihead_context_score_2 = torch.bmm(multihead_attention_normalized_score_2.unsqueeze(1), 237 | multihead_values.permute(0, 2, 1)).squeeze() # (3, 28) 238 | 239 | ``` 240 | 241 | # Cross Attention 242 | 243 | - In self-attention, we work with the same input sequence. In cross-attention, we mix or combine two *different* input sequences. 244 | - Two input sequence $x_1$ and $x_2$ can have different numbers of elelments. However, their **embedding dimensions must match** 245 | 246 | ![If we set $x_1$ = $x_2$, it is equal to self-attention](Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38/Untitled%206.png) 247 | 248 | If we set $x_1$ = $x_2$, it is equal to self-attention 249 | 250 | - **Generated tokens** from Decoder (sen0) **query** the **tokens from Encoder** (sent1) 251 | - Queries usually come from the decoder, and keys and values usually come from the encoder. 252 | 253 | ## Functionalized Version 254 | 255 | ```python 256 | def cross_attn(embedded_sentence_0: torch.Tensor, 257 | embedded_sentence_1: torch.Tensor, 258 | dim_q: int, 259 | dim_k: int, 260 | dim_v: int): 261 | # Generated tokens from the decoder sentence 0 query the tokens from the encoder sentence 1 262 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 263 | assert embedded_sentence_0.shape[-1] == embedded_sentence_1.shape[-1], "Hid_dim must be same between two sentences" 264 | 265 | hid_dim = embedded_sentence_0.shape[-1] 266 | 267 | W_Q = nn.Parameter(torch.randn(dim_q, hid_dim)) 268 | W_K = nn.Parameter(torch.randn(dim_k, hid_dim)) 269 | W_V = nn.Parameter(torch.randn(dim_v, hid_dim)) 270 | 271 | Q = (W_K @ embedded_sentence_0.T).T # (T_0, d_q) 272 | K = (W_Q @ embedded_sentence_1.T).T # (T_1, d_k) 273 | V = (W_V @ embedded_sentence_1.T).T # (T_1, d_v) 274 | 275 | attn = torch.softmax(1 / dim_k ** .5 * Q @ K.T, dim = 1) @ V # (T_0, d_v) 276 | 277 | return attn 278 | ``` 279 | -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 1.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 2.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 3.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 4.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 5.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled 6.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PaperReplicate/Self_Attention_from_Scratch/Self-Attention and Multi-head Attention Mechanism 036331bdfc7649238f86306bb44bed38/Untitled.png -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/self_attention.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | 4 | def calc_attn(embedded_sentence: torch.Tensor, 5 | dim_q: int, 6 | dim_k: int, 7 | dim_v: int, 8 | ): 9 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 10 | 11 | hid_dim = embedded_sentence.shape[-1] 12 | W_Q = nn.Parameter(torch.randn(dim_q, hid_dim)) 13 | W_K = nn.Parameter(torch.randn(dim_k, hid_dim)) 14 | W_V = nn.Parameter(torch.randn(dim_v, hid_dim)) 15 | 16 | Q = (W_K @ embedded_sentence.T).T # (T, d_q) 17 | K = (W_Q @ embedded_sentence.T).T # (T, d_k) 18 | V = (W_V @ embedded_sentence.T).T # (T, d_v) 19 | 20 | attn = torch.softmax(1 / dim_k ** .5 * Q @ K.T, dim = 1) @ V # (T, d_v) 21 | 22 | return attn 23 | 24 | def cross_attn(embedded_sentence_0: torch.Tensor, 25 | embedded_sentence_1: torch.Tensor, 26 | dim_q: int, 27 | dim_k: int, 28 | dim_v: int): 29 | # Generated tokens from the decoder sentence 0 query the tokens from the encoder sentence 1 30 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 31 | assert embedded_sentence_0.shape[-1] == embedded_sentence_1.shape[-1], "Hid_dim must be same between two sentences" 32 | 33 | hid_dim = embedded_sentence_0.shape[-1] 34 | 35 | W_Q = nn.Parameter(torch.randn(dim_q, hid_dim)) 36 | W_K = nn.Parameter(torch.randn(dim_k, hid_dim)) 37 | W_V = nn.Parameter(torch.randn(dim_v, hid_dim)) 38 | 39 | Q = (W_K @ embedded_sentence_0.T).T # (T_0, d_q) 40 | K = (W_Q @ embedded_sentence_1.T).T # (T_1, d_k) 41 | V = (W_V @ embedded_sentence_1.T).T # (T_1, d_v) 42 | 43 | attn = torch.softmax(1 / dim_k ** .5 * Q @ K.T, dim = 1) @ V # (T_0, d_v) 44 | 45 | return attn 46 | 47 | 48 | def multi_head_attn(embedded_sentence: torch.Tensor, 49 | head: int, 50 | dim_q: int, 51 | dim_k: int, 52 | dim_v: int): 53 | assert dim_k == dim_q, "dim(K) == dim(Q) must be met!" 54 | hid_dim = embedded_sentence.shape[-1] # dim 55 | stacked_embedded_sentence = embedded_sentence.repeat(head, 1, 1) # (head, T, dim) 56 | 57 | W_Q = nn.Parameter(torch.randn(head, dim_q, hid_dim)) # (h, d_q, dim) 58 | W_K = nn.Parameter(torch.randn(head, dim_k, hid_dim)) # (h, d_k, dim) 59 | W_V = nn.Parameter(torch.randn(head, dim_v, hid_dim)) # (h, d_v, dim) 60 | 61 | Q = (W_Q @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_q) 62 | K = (W_K @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_k) 63 | V = (W_V @ stacked_embedded_sentence.transpose(1, 2)).transpose(1, 2) # (h, T, d_v) 64 | 65 | mha = torch.softmax(1 / d_k ** .5 * Q @ K.transpose(1, 2), dim = 2) @ V # (h, T, d_v) 66 | 67 | return mha 68 | 69 | 70 | if __name__ == '__main__': 71 | sentence = "Life is short, eat dessert first" 72 | # Create Dictionary 73 | dict = {s: i for i, s in enumerate(sorted(sentence.replace(",", "").split()))} 74 | # print(dict) 75 | 76 | sentence_index = torch.tensor([dict[s] for s in sentence.replace(",", "").split()]) 77 | # print(sentence_index) 78 | 79 | # word embedding 80 | embeder = torch.nn.Embedding(6, 16) 81 | embedded_sentence = embeder(sentence_index).detach() 82 | # print(embedded_sentence.shape) 83 | d_q, d_k, d_v = 24, 24, 30 84 | multi_head_attn(embedded_sentence, 3, d_q, d_k, d_v) 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /PaperReplicate/Self_Attention_from_Scratch/self_attention_mechanism.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "source": [ 6 | "# Embedding an Input Sentence\n", 7 | "\n", 8 | "For simplicity, here our dictionary dc is restricted to the words that occur in the input sentence. In a real-world application, we would consider all words in the training dataset (typical vocabulary sizes range between 30k to 50k).\n", 9 | "\n" 10 | ], 11 | "metadata": { 12 | "collapsed": false 13 | } 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 3, 18 | "outputs": [ 19 | { 20 | "data": { 21 | "text/plain": "{'Life': 0, 'dessert': 1, 'eat': 2, 'first': 3, 'is': 4, 'short': 5}" 22 | }, 23 | "execution_count": 3, 24 | "metadata": {}, 25 | "output_type": "execute_result" 26 | } 27 | ], 28 | "source": [ 29 | "sentence = \"Life is short, eat dessert first\"\n", 30 | "\n", 31 | "# Create Dictionary\n", 32 | "dict = {s : i for i, s in enumerate(sorted(sentence.replace(\",\", \"\").split()))}\n", 33 | "\n", 34 | "dict" 35 | ], 36 | "metadata": { 37 | "collapsed": false, 38 | "ExecuteTime": { 39 | "end_time": "2023-06-29T17:57:31.163972Z", 40 | "start_time": "2023-06-29T17:57:31.161212Z" 41 | } 42 | } 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": [ 47 | "### Assign the Index to Each Word" 48 | ], 49 | "metadata": { 50 | "collapsed": false 51 | } 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 4, 56 | "outputs": [ 57 | { 58 | "data": { 59 | "text/plain": "tensor([0, 4, 5, 2, 1, 3])" 60 | }, 61 | "execution_count": 4, 62 | "metadata": {}, 63 | "output_type": "execute_result" 64 | } 65 | ], 66 | "source": [ 67 | "import torch\n", 68 | "\n", 69 | "sentence_idx = torch.tensor([dict[s] for s in sentence.replace(',', '').split()])\n", 70 | "sentence_idx" 71 | ], 72 | "metadata": { 73 | "collapsed": false, 74 | "ExecuteTime": { 75 | "end_time": "2023-06-29T18:01:34.498889Z", 76 | "start_time": "2023-06-29T18:01:33.690016Z" 77 | } 78 | } 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "source": [ 83 | "### Word Embedding\n", 84 | "Here, we will use a 16-dimensional embedding such that each input word is represented by a 16-dimensional vector." 85 | ], 86 | "metadata": { 87 | "collapsed": false 88 | } 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 6, 93 | "outputs": [ 94 | { 95 | "name": "stdout", 96 | "output_type": "stream", 97 | "text": [ 98 | "torch.Size([6, 16])\n" 99 | ] 100 | } 101 | ], 102 | "source": [ 103 | "torch.manual_seed(123)\n", 104 | "embeder = torch.nn.Embedding(6, 16)\n", 105 | "embedded_sentence = embeder(sentence_idx).detach()\n", 106 | "\n", 107 | "\n", 108 | "print(embedded_sentence.shape)" 109 | ], 110 | "metadata": { 111 | "collapsed": false, 112 | "ExecuteTime": { 113 | "end_time": "2023-06-29T18:04:16.660623Z", 114 | "start_time": "2023-06-29T18:04:16.627372Z" 115 | } 116 | } 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "source": [ 121 | "### Define Weight Matrices" 122 | ], 123 | "metadata": { 124 | "collapsed": false 125 | } 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 12, 130 | "outputs": [ 131 | { 132 | "data": { 133 | "text/plain": "(torch.Size([24, 16]), torch.Size([24, 16]), torch.Size([28, 16]))" 134 | }, 135 | "execution_count": 12, 136 | "metadata": {}, 137 | "output_type": "execute_result" 138 | } 139 | ], 140 | "source": [ 141 | "torch.manual_seed(123)\n", 142 | "\n", 143 | "d = embedded_sentence.shape[1]\n", 144 | "\n", 145 | "d_q, d_k, d_v = 24, 24, 28\n", 146 | "\n", 147 | "W_query = torch.nn.Parameter(torch.randn(d_q, d))\n", 148 | "W_key = torch.nn.Parameter(torch.randn(d_k, d))\n", 149 | "W_value = torch.nn.Parameter(torch.randn(d_v, d))\n", 150 | "\n", 151 | "W_query.shape, W_key.shape, W_value.shape" 152 | ], 153 | "metadata": { 154 | "collapsed": false, 155 | "ExecuteTime": { 156 | "end_time": "2023-06-29T18:39:51.904276Z", 157 | "start_time": "2023-06-29T18:39:51.893251Z" 158 | } 159 | } 160 | }, 161 | { 162 | "cell_type": "markdown", 163 | "source": [ 164 | "### Computing the Unnormalized Attention Weights\n", 165 | "We pick the second words $x^{(2)}$ as example" 166 | ], 167 | "metadata": { 168 | "collapsed": false 169 | } 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 8, 174 | "outputs": [ 175 | { 176 | "data": { 177 | "text/plain": "(torch.Size([24]), torch.Size([24]), torch.Size([28]))" 178 | }, 179 | "execution_count": 8, 180 | "metadata": {}, 181 | "output_type": "execute_result" 182 | } 183 | ], 184 | "source": [ 185 | "x_2 = embedded_sentence[1]\n", 186 | "query_2 = W_query @ x_2\n", 187 | "key_2 = W_key @ x_2\n", 188 | "value_2 = W_value @ x_2\n", 189 | "\n", 190 | "query_2.shape, key_2.shape, value_2.shape" 191 | ], 192 | "metadata": { 193 | "collapsed": false, 194 | "ExecuteTime": { 195 | "end_time": "2023-06-29T18:32:34.857706Z", 196 | "start_time": "2023-06-29T18:32:34.853013Z" 197 | } 198 | } 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "source": [ 203 | "We can then generalize this to compute th remaining key, and value elements for all inputs as well, since we will need them in the next step when we compute the unnormalized attention weights ω:" 204 | ], 205 | "metadata": { 206 | "collapsed": false 207 | } 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 9, 212 | "outputs": [ 213 | { 214 | "data": { 215 | "text/plain": "(torch.Size([6, 24]), torch.Size([6, 28]))" 216 | }, 217 | "execution_count": 9, 218 | "metadata": {}, 219 | "output_type": "execute_result" 220 | } 221 | ], 222 | "source": [ 223 | "keys = (W_key @ embedded_sentence.T).T\n", 224 | "values = (W_value @ embedded_sentence.T).T\n", 225 | "\n", 226 | "keys.shape, values.shape" 227 | ], 228 | "metadata": { 229 | "collapsed": false, 230 | "ExecuteTime": { 231 | "end_time": "2023-06-29T18:34:23.237904Z", 232 | "start_time": "2023-06-29T18:34:23.232098Z" 233 | } 234 | } 235 | }, 236 | { 237 | "cell_type": "markdown", 238 | "source": [ 239 | "We can then generalize this to compute th remaining key, and value elements for all inputs as well, since we will need them in the next step when we compute the unnormalized attention weights ω\n", 240 | "\n", 241 | "As illustrated in the figure above, we compute $w_{ij}$\n", 242 | " as the dot product between the query and key sequences, $ω_{ij}=q^{(i)}^⊤k^{(j)}$\n", 243 | "\n" 244 | ], 245 | "metadata": { 246 | "collapsed": false 247 | } 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": 13, 252 | "outputs": [ 253 | { 254 | "data": { 255 | "text/plain": "tensor(-98.1709, grad_fn=)" 256 | }, 257 | "execution_count": 13, 258 | "metadata": {}, 259 | "output_type": "execute_result" 260 | } 261 | ], 262 | "source": [ 263 | "# Compute the unnormalized attention weights for the query and 5th input word\n", 264 | "omega_24 = query_2.dot(keys[4])\n", 265 | "omega_24" 266 | ], 267 | "metadata": { 268 | "collapsed": false, 269 | "ExecuteTime": { 270 | "end_time": "2023-06-29T18:44:07.066502Z", 271 | "start_time": "2023-06-29T18:44:07.049526Z" 272 | } 273 | } 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 17, 278 | "outputs": [ 279 | { 280 | "data": { 281 | "text/plain": "(tensor([ 83.1533, 95.5014, -100.8583, 63.5880, -98.1709, 9.3997],\n grad_fn=),\n torch.Size([6]))" 282 | }, 283 | "execution_count": 17, 284 | "metadata": {}, 285 | "output_type": "execute_result" 286 | } 287 | ], 288 | "source": [ 289 | "# For all tokens\n", 290 | "omega_2 = query_2 @ keys.T\n", 291 | "omega_2, omega_2.shape" 292 | ], 293 | "metadata": { 294 | "collapsed": false, 295 | "ExecuteTime": { 296 | "end_time": "2023-06-29T18:46:18.727666Z", 297 | "start_time": "2023-06-29T18:46:18.712331Z" 298 | } 299 | } 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 18, 304 | "outputs": [ 305 | { 306 | "data": { 307 | "text/plain": "tensor([7.4329e-02, 9.2430e-01, 3.6185e-18, 1.3699e-03, 6.2628e-18, 2.1523e-08],\n grad_fn=)" 308 | }, 309 | "execution_count": 18, 310 | "metadata": {}, 311 | "output_type": "execute_result" 312 | } 313 | ], 314 | "source": [ 315 | "# Calculate the\n", 316 | "import torch.nn.functional as F\n", 317 | "\n", 318 | "attention_weights_2 = F.softmax(omega_2 / d_k ** .5, dim = 0)\n", 319 | "attention_weights_2" 320 | ], 321 | "metadata": { 322 | "collapsed": false, 323 | "ExecuteTime": { 324 | "end_time": "2023-06-29T18:55:35.660747Z", 325 | "start_time": "2023-06-29T18:55:35.655454Z" 326 | } 327 | } 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": 19, 332 | "outputs": [ 333 | { 334 | "data": { 335 | "text/plain": "torch.Size([28])" 336 | }, 337 | "execution_count": 19, 338 | "metadata": {}, 339 | "output_type": "execute_result" 340 | } 341 | ], 342 | "source": [ 343 | "context_vector_2 = attention_weights_2 @ values\n", 344 | "\n", 345 | "context_vector_2.shape" 346 | ], 347 | "metadata": { 348 | "collapsed": false, 349 | "ExecuteTime": { 350 | "end_time": "2023-06-29T19:42:13.014621Z", 351 | "start_time": "2023-06-29T19:42:13.008768Z" 352 | } 353 | } 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 21, 358 | "outputs": [], 359 | "source": [ 360 | "head = 3\n", 361 | "\n", 362 | "# (3, 24, 16)\n", 363 | "multihead_W_query = torch.nn.Parameter(torch.randn(head, d_q, d))\n", 364 | "multihead_W_key = torch.nn.Parameter(torch.randn(head, d_k, d))\n", 365 | "# (3, 28, 16)\n", 366 | "multihead_W_value = torch.nn.Parameter(torch.randn(head, d_v, d))" 367 | ], 368 | "metadata": { 369 | "collapsed": false, 370 | "ExecuteTime": { 371 | "end_time": "2023-06-29T19:50:25.733361Z", 372 | "start_time": "2023-06-29T19:50:25.730348Z" 373 | } 374 | } 375 | }, 376 | { 377 | "cell_type": "code", 378 | "execution_count": 29, 379 | "outputs": [], 380 | "source": [ 381 | "# q, k, v for x_2\n", 382 | "multihead_query_2 = multihead_W_query @ x_2 # (3, 24)\n", 383 | "multihead_key_2 = multihead_W_key @ x_2 # (3, 24)\n", 384 | "multihead_value_2 = multihead_W_value @ x_2 # (3, 24)\n", 385 | "\n", 386 | "\n", 387 | "# x_2 asks each other words, then we need to calculate the k, v for other tokens\n", 388 | "# first, we need to expand the input sequence embeddings to the number of heads\n", 389 | "stacked_inputs = embedded_sentence.T.repeat(head, 1, 1) # (3, 16, 6)\n", 390 | "\n", 391 | "\n", 392 | "multihead_keys = torch.bmm(multihead_W_key, stacked_inputs)# (3, 24, 6)\n", 393 | "multihead_values = torch.bmm(multihead_W_value, stacked_inputs) # (3, 28, 6)\n", 394 | "\n" 395 | ], 396 | "metadata": { 397 | "collapsed": false, 398 | "ExecuteTime": { 399 | "end_time": "2023-06-29T20:08:08.893835Z", 400 | "start_time": "2023-06-29T20:08:08.884179Z" 401 | } 402 | } 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": 33, 407 | "outputs": [ 408 | { 409 | "data": { 410 | "text/plain": "torch.Size([3, 6])" 411 | }, 412 | "execution_count": 33, 413 | "metadata": {}, 414 | "output_type": "execute_result" 415 | } 416 | ], 417 | "source": [ 418 | "# let x_2 asks every token -> unnormalized attention score\n", 419 | "multihead_query_2.unsqueeze(1)\n", 420 | "\n", 421 | "multihead_attention_unnormalized_score_2 = torch.bmm(multihead_query_2.unsqueeze(dim = 1),\n", 422 | " multihead_keys).squeeze() # (3, 6)\n", 423 | "\n", 424 | "multihead_attention_normalized_score_2 = F.softmax(multihead_attention_unnormalized_score_2 / d_k\n", 425 | " ** 0.5, dim = 1) # (3, 6)" 426 | ], 427 | "metadata": { 428 | "collapsed": false, 429 | "ExecuteTime": { 430 | "end_time": "2023-06-29T20:11:33.035618Z", 431 | "start_time": "2023-06-29T20:11:33.032119Z" 432 | } 433 | } 434 | }, 435 | { 436 | "cell_type": "code", 437 | "execution_count": 39, 438 | "outputs": [ 439 | { 440 | "data": { 441 | "text/plain": "torch.Size([3, 28])" 442 | }, 443 | "execution_count": 39, 444 | "metadata": {}, 445 | "output_type": "execute_result" 446 | } 447 | ], 448 | "source": [ 449 | "multihead_context_score_2 = torch.bmm(multihead_attention_normalized_score_2.unsqueeze(1),\n", 450 | " multihead_values.permute(0, 2, 1)).squeeze() # (3, 28)\n", 451 | "multihead_context_score_2.shape" 452 | ], 453 | "metadata": { 454 | "collapsed": false, 455 | "ExecuteTime": { 456 | "end_time": "2023-06-29T20:17:00.100346Z", 457 | "start_time": "2023-06-29T20:17:00.096019Z" 458 | } 459 | } 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "outputs": [], 465 | "source": [], 466 | "metadata": { 467 | "collapsed": false 468 | } 469 | } 470 | ], 471 | "metadata": { 472 | "kernelspec": { 473 | "display_name": "Python 3", 474 | "language": "python", 475 | "name": "python3" 476 | }, 477 | "language_info": { 478 | "codemirror_mode": { 479 | "name": "ipython", 480 | "version": 2 481 | }, 482 | "file_extension": ".py", 483 | "mimetype": "text/x-python", 484 | "name": "python", 485 | "nbconvert_exporter": "python", 486 | "pygments_lexer": "ipython2", 487 | "version": "2.7.6" 488 | } 489 | }, 490 | "nbformat": 4, 491 | "nbformat_minor": 0 492 | } 493 | -------------------------------------------------------------------------------- /PaperReplicate/data_setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Contains functionality for creating PyTorch DataLoaders for 3 | image classification data. 4 | """ 5 | 6 | from torchvision import datasets, transforms 7 | from torch.utils.data import DataLoader 8 | import os 9 | from pathlib import Path 10 | import requests 11 | import zipfile 12 | 13 | 14 | def create_dataloaders( 15 | train_dir: str, 16 | test_dir: str, 17 | transform: transforms.Compose, 18 | batch_size: int, 19 | num_workers: int = os.cpu_count() 20 | ): 21 | """Creates training and testing DataLoaders. 22 | Warning: Only suits standard Pytorch Image Path 23 | 24 | Takes in a training directory and testing directory path and turns 25 | them into PyTorch Datasets and then into PyTorch DataLoaders. 26 | 27 | Args: 28 | train_dir: Path to training directory. 29 | test_dir: Path to testing directory. 30 | transform: torchvision transforms to perform on training and testing data. 31 | batch_size: Number of samples per batch in each of the DataLoaders. 32 | num_workers: An integer for number of workers per DataLoader. 33 | 34 | Returns: 35 | A tuple of (train_dataloader, test_dataloader, class_names). 36 | Where class_names is a list of the target classes. 37 | Example usage: 38 | train_dataloader, test_dataloader, class_names = \ 39 | = create_dataloaders(train_dir=path/to/train_dir, 40 | test_dir=path/to/test_dir, 41 | transform=some_transform, 42 | batch_size=32, 43 | num_workers=4) 44 | """ 45 | # Use ImageFolder to create dataset(s) 46 | train_data = datasets.ImageFolder(train_dir, transform = transform) 47 | test_data = datasets.ImageFolder(test_dir, transform = transform) 48 | 49 | # Get class names 50 | class_names = train_data.classes 51 | class_to_idx = train_data.class_to_idx 52 | 53 | # Turn images into data loaders 54 | # we are using pin_memory = True to avoid unnecessary copying of memory between CPU and GPU 55 | # The benifits of this will likely be seen with larger dataset sizes 56 | # However, pin_memory = True doesn't always improve performance. 57 | 58 | train_dataloader = DataLoader( 59 | train_data, 60 | batch_size = batch_size, 61 | shuffle = True, 62 | num_workers = num_workers, 63 | pin_memory = True, 64 | ) 65 | test_dataloader = DataLoader( 66 | test_data, 67 | batch_size = batch_size, 68 | shuffle = False, 69 | num_workers = num_workers, 70 | pin_memory = True, 71 | ) 72 | 73 | return train_dataloader, test_dataloader, class_names, class_to_idx 74 | 75 | 76 | def download_data(source: str, 77 | destination: str, 78 | remove_source: bool = True) -> Path: 79 | """Downloads a zipped dataset from source and unzips to destination. 80 | 81 | Args: 82 | source (str): A link to a zipped file containing data. 83 | destination (str): A target directory to unzip data to. 84 | remove_source (bool): Whether to remove the source after downloading and extracting. 85 | 86 | Returns: 87 | pathlib.Path to downloaded data. 88 | 89 | Example usage: 90 | download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip", 91 | destination="pizza_steak_sushi") 92 | """ 93 | # Setup path to data folder 94 | data_path = Path("data/") 95 | image_path = data_path / destination 96 | 97 | # If the image folder doesn't exist, download it and prepare it... 98 | if image_path.is_dir(): 99 | print(f"[INFO] {image_path} directory exists, skipping download.") 100 | else: 101 | print(f"[INFO] Did not find {image_path} directory, creating one...") 102 | image_path.mkdir(parents = True, exist_ok = True) 103 | 104 | # Download pizza, steak, sushi data 105 | target_file = Path(source).name 106 | with open(data_path / target_file, "wb") as f: 107 | request = requests.get(source) 108 | print(f"[INFO] Downloading {target_file} from {source}...") 109 | f.write(request.content) 110 | 111 | # Unzip pizza, steak, sushi data 112 | with zipfile.ZipFile(data_path / target_file, "r") as zip_ref: 113 | print(f"[INFO] Unzipping {target_file} data...") 114 | zip_ref.extractall(image_path) 115 | 116 | # Remove .zip file 117 | if remove_source: 118 | os.remove(data_path / target_file) 119 | 120 | return image_path 121 | -------------------------------------------------------------------------------- /PaperReplicate/helper_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | A series of helper functions used throughout the course. 3 | 4 | If a function gets defined once and could be used over and over, it'll go in here. 5 | """ 6 | import torch 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import zipfile 11 | 12 | from pathlib import Path 13 | 14 | import requests 15 | 16 | # Walk through an image classification directory and find out how many files (images) 17 | # are in each subdirectory. 18 | 19 | import os 20 | os.environ["TORCH_USE_NNPACK"] = "0" 21 | 22 | def walk_through_dir(dir_path): 23 | """ 24 | Walks through dir_path returning its contents. 25 | Args: 26 | dir_path (str): target directory 27 | 28 | Returns: 29 | A print out of: 30 | number of subdiretories in dir_path 31 | number of images (files) in each subdirectory 32 | name of each subdirectory 33 | """ 34 | for dirpath, dirnames, filenames in os.walk(dir_path): 35 | print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.") 36 | 37 | def plot_decision_boundary(model: torch.nn.Module, X: torch.Tensor, y: torch.Tensor): 38 | """Plots decision boundaries of model predicting on X in comparison to y. 39 | 40 | Source - https://madewithml.com/courses/foundations/neural-networks/ (with modifications) 41 | """ 42 | # Put everything to CPU (works better with NumPy + Matplotlib) 43 | model.to("cpu") 44 | X, y = X.to("cpu"), y.to("cpu") 45 | 46 | # Setup prediction boundaries and grid 47 | x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 48 | y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 49 | xx, yy = np.meshgrid(np.linspace(x_min, x_max, 101), np.linspace(y_min, y_max, 101)) 50 | 51 | # Make features 52 | X_to_pred_on = torch.from_numpy(np.column_stack((xx.ravel(), yy.ravel()))).float() 53 | 54 | # Make predictions 55 | model.eval() 56 | with torch.inference_mode(): 57 | y_logits = model(X_to_pred_on) 58 | 59 | # Test for multi-class or binary and adjust logits to prediction labels 60 | if len(torch.unique(y)) > 2: 61 | y_pred = torch.softmax(y_logits, dim=1).argmax(dim=1) # mutli-class 62 | else: 63 | y_pred = torch.round(torch.sigmoid(y_logits)) # binary 64 | 65 | # Reshape preds and plot 66 | y_pred = y_pred.reshape(xx.shape).detach().numpy() 67 | plt.contourf(xx, yy, y_pred, cmap=plt.cm.RdYlBu, alpha=0.7) 68 | plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.RdYlBu) 69 | plt.xlim(xx.min(), xx.max()) 70 | plt.ylim(yy.min(), yy.max()) 71 | 72 | 73 | # Plot linear data or training and test and predictions (optional) 74 | def plot_predictions( 75 | train_data, train_labels, test_data, test_labels, predictions=None 76 | ): 77 | """ 78 | Plots linear training data and test data and compares predictions. 79 | """ 80 | plt.figure(figsize=(10, 7)) 81 | 82 | # Plot training data in blue 83 | plt.scatter(train_data, train_labels, c="b", s=4, label="Training data") 84 | 85 | # Plot test data in green 86 | plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data") 87 | 88 | if predictions is not None: 89 | # Plot the predictions in red (predictions were made on the test data) 90 | plt.scatter(test_data, predictions, c="r", s=4, label="Predictions") 91 | 92 | # Show the legend 93 | plt.legend(prop={"size": 14}) 94 | 95 | 96 | # Calculate accuracy (a classification metric) 97 | def accuracy_fn(y_true, y_pred): 98 | """Calculates accuracy between truth labels and predictions. 99 | 100 | Args: 101 | y_true (torch.Tensor): Truth labels for predictions. 102 | y_pred (torch.Tensor): Predictions to be compared to predictions. 103 | 104 | Returns: 105 | [torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45 106 | """ 107 | correct = torch.eq(y_true, y_pred).sum().item() 108 | acc = (correct / len(y_pred)) * 100 109 | return acc 110 | 111 | 112 | def print_train_time(start, end, device=None): 113 | """Prints difference between start and end time. 114 | 115 | Args: 116 | start (float): Start time of computation (preferred in timeit format). 117 | end (float): End time of computation. 118 | device ([type], optional): Device that compute is running on. Defaults to None. 119 | 120 | Returns: 121 | float: time between start and end in seconds (higher is longer). 122 | """ 123 | total_time = end - start 124 | print(f"\nTrain time on {device}: {total_time:.3f} seconds") 125 | return total_time 126 | 127 | 128 | # Plot loss curves of a model 129 | def plot_loss_curves(results): 130 | """Plots training curves of a result dictionary. 131 | 132 | Args: 133 | results (dict): dictionary containing list of values, e.g. 134 | {"train_loss": [...], 135 | "train_acc": [...], 136 | "test_loss": [...], 137 | "test_acc": [...]} 138 | """ 139 | loss = results["train_loss"] 140 | test_loss = results["test_loss"] 141 | 142 | accuracy = results["train_acc"] 143 | test_accuracy = results["test_acc"] 144 | 145 | epochs = range(len(results["train_loss"])) 146 | 147 | plt.figure(figsize=(15, 7)) 148 | 149 | # Plot loss 150 | plt.subplot(1, 2, 1) 151 | plt.plot(epochs, loss, label="train_loss") 152 | plt.plot(epochs, test_loss, label="test_loss") 153 | plt.title("Loss") 154 | plt.xlabel("Epochs") 155 | plt.legend() 156 | 157 | # Plot accuracy 158 | plt.subplot(1, 2, 2) 159 | plt.plot(epochs, accuracy, label="train_accuracy") 160 | plt.plot(epochs, test_accuracy, label="test_accuracy") 161 | plt.title("Accuracy") 162 | plt.xlabel("Epochs") 163 | plt.legend() 164 | 165 | 166 | # Pred and plot image function from notebook 04 167 | # See creation: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function 168 | from typing import List 169 | import torchvision 170 | 171 | 172 | def pred_and_plot_image( 173 | model: torch.nn.Module, 174 | image_path: str, 175 | class_names: List[str] = None, 176 | transform=None, 177 | device: torch.device = "cuda" if torch.cuda.is_available() else "cpu", 178 | ): 179 | """Makes a prediction on a target image with a trained model and plots the image. 180 | 181 | Args: 182 | model (torch.nn.Module): trained PyTorch image classification model. 183 | image_path (str): filepath to target image. 184 | class_names (List[str], optional): different class names for target image. Defaults to None. 185 | transform (_type_, optional): transform of target image. Defaults to None. 186 | device (torch.device, optional): target device to compute on. Defaults to "cuda" if torch.cuda.is_available() else "cpu". 187 | 188 | Returns: 189 | Matplotlib plot of target image and model prediction as title. 190 | 191 | Example usage: 192 | pred_and_plot_image(model=model, 193 | image="some_image.jpeg", 194 | class_names=["class_1", "class_2", "class_3"], 195 | transform=torchvision.transforms.ToTensor(), 196 | device=device) 197 | """ 198 | 199 | # 1. Load in image and convert the tensor values to float32 200 | target_image = torchvision.io.read_image(str(image_path)).type(torch.float32) 201 | 202 | # 2. Divide the image pixel values by 255 to get them between [0, 1] 203 | target_image = target_image / 255.0 204 | 205 | # 3. Transform if necessary 206 | if transform: 207 | target_image = transform(target_image) 208 | 209 | # 4. Make sure the model is on the target device 210 | model.to(device) 211 | 212 | # 5. Turn on model evaluation mode and inference mode 213 | model.eval() 214 | with torch.inference_mode(): 215 | # Add an extra dimension to the image 216 | target_image = target_image.unsqueeze(dim=0) 217 | 218 | # Make a prediction on image with an extra dimension and send it to the target device 219 | target_image_pred = model(target_image.to(device)) 220 | 221 | # 6. Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification) 222 | target_image_pred_probs = torch.softmax(target_image_pred, dim=1) 223 | 224 | # 7. Convert prediction probabilities -> prediction labels 225 | target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1) 226 | 227 | # 8. Plot the image alongside the prediction and prediction probability 228 | plt.imshow( 229 | target_image.squeeze().permute(1, 2, 0) 230 | ) # make sure it's the right size for matplotlib 231 | if class_names: 232 | title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}" 233 | else: 234 | title = f"Pred: {target_image_pred_label} | Prob: {target_image_pred_probs.max().cpu():.3f}" 235 | plt.title(title) 236 | plt.axis(False) 237 | 238 | def set_seeds(seed: int=42): 239 | """Sets random sets for torch operations. 240 | 241 | Args: 242 | seed (int, optional): Random seed to set. Defaults to 42. 243 | """ 244 | # Set the seed for general torch operations 245 | torch.manual_seed(seed) 246 | # Set the seed for CUDA torch operations (ones that happen on the GPU) 247 | torch.cuda.manual_seed(seed) 248 | 249 | 250 | -------------------------------------------------------------------------------- /PaperReplicate/predictions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utility functions to make predictions. 3 | 4 | """ 5 | import torch 6 | import torchvision 7 | from torchvision import transforms 8 | import matplotlib.pyplot as plt 9 | 10 | from typing import List, Tuple 11 | 12 | from PIL import Image 13 | 14 | # Set device 15 | device = "cuda" if torch.cuda.is_available() else "cpu" 16 | # Predict on a target image with a target model 17 | def pred_and_plot_image( 18 | model: torch.nn.Module, 19 | class_names: List[str], 20 | image_path: str, 21 | image_size: Tuple[int, int] = (224, 224), 22 | transform: torchvision.transforms = None, 23 | device: torch.device = device, 24 | ): 25 | """Predicts on a target image with a target model. 26 | 27 | Args: 28 | model (torch.nn.Module): A trained (or untrained) PyTorch model to predict on an image. 29 | class_names (List[str]): A list of target classes to map predictions to. 30 | image_path (str): Filepath to target image to predict on. 31 | image_size (Tuple[int, int], optional): Size to transform target image to. Defaults to (224, 224). 32 | transform (torchvision.transforms, optional): Transform to perform on image. Defaults to None which uses ImageNet normalization. 33 | device (torch.device, optional): Target device to perform prediction on. Defaults to device. 34 | """ 35 | 36 | # Open image 37 | img = Image.open(image_path) 38 | 39 | # Create transformation for image (if one doesn't exist) 40 | if transform is not None: 41 | image_transform = transform 42 | else: 43 | image_transform = transforms.Compose( 44 | [ 45 | transforms.Resize(image_size), 46 | transforms.ToTensor(), 47 | transforms.Normalize( 48 | mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] 49 | ), 50 | ] 51 | ) 52 | 53 | # Make sure the model is on the target device 54 | model.to(device) 55 | 56 | # Turn on model evaluation mode and inference mode 57 | model.eval() 58 | with torch.inference_mode(): 59 | # Transform and add an extra dimension to image (model requires samples in [batch_size, color_channels, height, width]) 60 | transformed_image = image_transform(img).unsqueeze(dim=0) 61 | 62 | # Make a prediction on image with an extra dimension and send it to the target device 63 | target_image_pred = model(transformed_image.to(device)) 64 | 65 | # Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification) 66 | target_image_pred_probs = torch.softmax(target_image_pred, dim=1) 67 | 68 | # Convert prediction probabilities -> prediction labels 69 | target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1) 70 | 71 | # Plot image with predicted label and probability 72 | plt.figure() 73 | plt.imshow(img) 74 | plt.title( 75 | f"Pred: {class_names[target_image_pred_label]} | Prob: {target_image_pred_probs.max():.3f}" 76 | ) 77 | plt.axis(False) 78 | -------------------------------------------------------------------------------- /PaperReplicate/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Contains various utility functions for PyTorch model training and saving. 3 | """ 4 | import torch 5 | from pathlib import Path 6 | from torchinfo import summary 7 | from torch.utils.tensorboard import SummaryWriter 8 | 9 | def create_writer(experiment_name: str, model_name: str, extra: str=None): 10 | from datetime import datetime 11 | import os 12 | 13 | timestamp = datetime.now().strftime("%Y-%m-%d") 14 | 15 | if extra: 16 | log_dir = os.path.join("runs", timestamp, experiment_name, model_name, extra) 17 | else: 18 | log_dir = os.path.join("runs", timestamp, experiment_name, model_name) 19 | 20 | print(f"[INFO] Created SummaryWriter, saving to: {log_dir}") 21 | return SummaryWriter(log_dir) 22 | 23 | 24 | def set_seed(seed: int = 42, device: torch.device = None): 25 | torch.manual_seed(seed) 26 | 27 | if device == "cuda": 28 | torch.cuda.manual_seed() 29 | 30 | 31 | 32 | def save_model(model: torch.nn.Module, 33 | target_dir: str, 34 | model_name: str): 35 | """Saves a PyTorch model to a target directory. 36 | 37 | Args: 38 | model: A target PyTorch model to save. 39 | target_dir: A directory for saving the model to. 40 | model_name: A filename for the saved model. Should include 41 | either ".pth" or ".pt" as the file extension. 42 | 43 | Example usage: 44 | save_model(model=model_0, 45 | target_dir="models", 46 | model_name="05_going_modular_tingvgg_model.pth") 47 | """ 48 | # Create target directory 49 | target_dir_path = Path(target_dir) 50 | target_dir_path.mkdir(parents=True, 51 | exist_ok=True) 52 | 53 | # Create model save path 54 | assert model_name.endswith(".pth") or model_name.endswith(".pt"), "model_name should end with '.pt' or '.pth'" 55 | model_save_path = target_dir_path / model_name 56 | 57 | # Save the model state_dict() 58 | print(f"[INFO] Saving model to: {model_save_path}") 59 | torch.save(obj=model.state_dict(), 60 | f=model_save_path) 61 | 62 | 63 | def device_check(): 64 | device = ( 65 | "cuda" 66 | if torch.cuda.is_available() 67 | else "mps" 68 | if torch.backends.mps.is_available() 69 | else "cpu" 70 | ) 71 | print(f"Using {device} device") 72 | return device 73 | 74 | 75 | import os 76 | 77 | def walk_through_dir(dir_path): 78 | for dirpath, dirnames, filenames in os.walk(dir_path): 79 | print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.") 80 | 81 | 82 | """ 83 | Contains functions for training and testing a PyTorch model. 84 | """ 85 | import torch 86 | 87 | from tqdm.auto import tqdm 88 | from typing import Dict, List, Tuple 89 | 90 | def train_step(model: torch.nn.Module, 91 | dataloader: torch.utils.data.DataLoader, 92 | loss_fn: torch.nn.Module, 93 | optimizer: torch.optim.Optimizer, scheduler: None, 94 | device: torch.device) -> Tuple[float, float]: 95 | """Trains a PyTorch model for a single epoch. 96 | 97 | Turns a target PyTorch model to training mode and then 98 | runs through all of the required training steps (forward 99 | pass, loss calculation, optimizer step). 100 | 101 | Args: 102 | model: A PyTorch model to be trained. 103 | dataloader: A DataLoader instance for the model to be trained on. 104 | loss_fn: A PyTorch loss function to minimize. 105 | optimizer: A PyTorch optimizer to help minimize the loss function. 106 | device: A target device to compute on (e.g. "cuda" or "cpu"). 107 | 108 | Returns: 109 | A tuple of training loss and training accuracy metrics. 110 | In the form (train_loss, train_accuracy). For example: 111 | 112 | (0.1112, 0.8743) 113 | """ 114 | # Put model in train mode 115 | model.train() 116 | 117 | # Setup train loss and train accuracy values 118 | train_loss, train_acc = 0, 0 119 | 120 | # Loop through data loader data batches 121 | for batch, (X, y) in enumerate(dataloader): 122 | # Send data to target device 123 | X, y = X.to(device), y.to(device) 124 | 125 | # 1. Forward pass 126 | y_pred = model(X) 127 | 128 | # 2. Calculate and accumulate loss 129 | loss = loss_fn(y_pred, y) 130 | train_loss += loss.item() 131 | 132 | # 3. Optimizer zero grad 133 | optimizer.zero_grad() 134 | 135 | # 4. Loss backward 136 | loss.backward() 137 | 138 | # 5. Optimizer step 139 | optimizer.step() 140 | 141 | if scheduler: 142 | scheduler.step() 143 | 144 | # Calculate and accumulate accuracy metric across all batches 145 | y_pred_class = torch.argmax(torch.softmax(y_pred, dim = 1), dim = 1) 146 | train_acc += (y_pred_class == y).sum().item() / len(y_pred) 147 | 148 | # Adjust metrics to get average loss and accuracy per batch 149 | train_loss = train_loss / len(dataloader) 150 | train_acc = train_acc / len(dataloader) 151 | return train_loss, train_acc 152 | 153 | 154 | def test_step(model: torch.nn.Module, 155 | dataloader: torch.utils.data.DataLoader, 156 | loss_fn: torch.nn.Module, 157 | device: torch.device) -> Tuple[float, float]: 158 | """Tests a PyTorch model for a single epoch. 159 | 160 | Turns a target PyTorch model to "eval" mode and then performs 161 | a forward pass on a testing dataset. 162 | 163 | Args: 164 | model: A PyTorch model to be tested. 165 | dataloader: A DataLoader instance for the model to be tested on. 166 | loss_fn: A PyTorch loss function to calculate loss on the test data. 167 | device: A target device to compute on (e.g. "cuda" or "cpu"). 168 | 169 | Returns: 170 | A tuple of testing loss and testing accuracy metrics. 171 | In the form (test_loss, test_accuracy). For example: 172 | 173 | (0.0223, 0.8985) 174 | """ 175 | # Put model in eval mode 176 | model.eval() 177 | 178 | # Setup test loss and test accuracy values 179 | test_loss, test_acc = 0, 0 180 | 181 | # Turn on inference context manager 182 | with torch.inference_mode(): 183 | # Loop through DataLoader batches 184 | for batch, (X, y) in enumerate(dataloader): 185 | # Send data to target device 186 | X, y = X.to(device), y.to(device) 187 | 188 | # 1. Forward pass 189 | test_pred_logits = model(X) 190 | 191 | # 2. Calculate and accumulate loss 192 | loss = loss_fn(test_pred_logits, y) 193 | test_loss += loss.item() 194 | 195 | # Calculate and accumulate accuracy 196 | test_pred_labels = test_pred_logits.argmax(dim = 1) 197 | test_acc += ((test_pred_labels == y).sum().item() / len(test_pred_labels)) 198 | 199 | # Adjust metrics to get average loss and accuracy per batch 200 | test_loss = test_loss / len(dataloader) 201 | test_acc = test_acc / len(dataloader) 202 | return test_loss, test_acc 203 | 204 | 205 | # Add writer parameter to train() 206 | def train(model: torch.nn.Module, 207 | train_dataloader: torch.utils.data.DataLoader, 208 | test_dataloader: torch.utils.data.DataLoader, 209 | optimizer: torch.optim.Optimizer, 210 | loss_fn: torch.nn.Module, 211 | epochs: int, 212 | device: torch.device, 213 | writer: torch.utils.tensorboard.writer.SummaryWriter # new parameter to take in a writer 214 | ) -> Dict[str, List]: 215 | """Trains and tests a PyTorch model. 216 | 217 | Passes a target PyTorch models through train_step() and test_step() 218 | functions for a number of epochs, training and testing the model 219 | in the same epoch loop. 220 | 221 | Calculates, prints and stores evaluation metrics throughout. 222 | 223 | Stores metrics to specified writer log_dir if present. 224 | 225 | Args: 226 | model: A PyTorch model to be trained and tested. 227 | train_dataloader: A DataLoader instance for the model to be trained on. 228 | test_dataloader: A DataLoader instance for the model to be tested on. 229 | optimizer: A PyTorch optimizer to help minimize the loss function. 230 | loss_fn: A PyTorch loss function to calculate loss on both datasets. 231 | epochs: An integer indicating how many epochs to train for. 232 | device: A target device to compute on (e.g. "cuda" or "cpu"). 233 | writer: A SummaryWriter() instance to log model results to. 234 | 235 | Returns: 236 | A dictionary of training and testing loss as well as training and 237 | testing accuracy metrics. Each metric has a value in a list for 238 | each epoch. 239 | """ 240 | # Create empty results dictionary 241 | results = {"train_loss": [], 242 | "train_acc": [], 243 | "test_loss": [], 244 | "test_acc": [] 245 | } 246 | 247 | # Loop through training and testing steps for a number of epochs 248 | for epoch in tqdm(range(epochs)): 249 | train_loss, train_acc = train_step(model=model, 250 | dataloader=train_dataloader, 251 | loss_fn=loss_fn, 252 | optimizer=optimizer, 253 | scheduler = None, 254 | device=device) 255 | test_loss, test_acc = test_step(model=model, 256 | dataloader=test_dataloader, 257 | loss_fn=loss_fn, 258 | device=device) 259 | 260 | # Print out what's happening 261 | print( 262 | f"Epoch: {epoch+1} | " 263 | f"train_loss: {train_loss:.4f} | " 264 | f"train_acc: {train_acc:.4f} | " 265 | f"test_loss: {test_loss:.4f} | " 266 | f"test_acc: {test_acc:.4f}" 267 | ) 268 | 269 | # Update results dictionary 270 | results["train_loss"].append(train_loss) 271 | results["train_acc"].append(train_acc) 272 | results["test_loss"].append(test_loss) 273 | results["test_acc"].append(test_acc) 274 | 275 | 276 | ### New: Use the writer parameter to track experiments ### 277 | # See if there's a writer, if so, log to it 278 | if writer: 279 | writer.add_scalar(tag = "Train Loss", scalar_value = train_loss, global_step = epoch) 280 | writer.add_scalar(tag = "Test Loss", scalar_value = test_loss, global_step = epoch) 281 | writer.add_scalar(tag = "Train Acc", scalar_value = train_acc, global_step = epoch) 282 | writer.add_scalar(tag = "Test Acc", scalar_value = test_acc, global_step = epoch) 283 | 284 | writer.add_graph(model = model, 285 | input_to_model = torch.randn(32, 3, 224, 224).to(device)) 286 | 287 | 288 | if writer: 289 | writer.close() 290 | 291 | return results 292 | 293 | import matplotlib.pyplot as plt 294 | # Plot loss curves of a model 295 | def plot_loss_curves(results): 296 | """Plots training curves of a result dictionary. 297 | 298 | Args: 299 | results (dict): dictionary containing list of values, e.g. 300 | {"train_loss": [...], 301 | "train_acc": [...], 302 | "test_loss": [...], 303 | "test_acc": [...]} 304 | """ 305 | loss = results["train_loss"] 306 | test_loss = results["test_loss"] 307 | 308 | accuracy = results["train_acc"] 309 | test_accuracy = results["test_acc"] 310 | 311 | epochs = range(len(results["train_loss"])) 312 | 313 | plt.figure(figsize=(15, 7)) 314 | 315 | # Plot loss 316 | plt.subplot(1, 2, 1) 317 | plt.plot(epochs, loss, label="train_loss") 318 | plt.plot(epochs, test_loss, label="test_loss") 319 | plt.title("Loss") 320 | plt.xlabel("Epochs") 321 | plt.legend() 322 | 323 | # Plot accuracy 324 | plt.subplot(1, 2, 2) 325 | plt.plot(epochs, accuracy, label="train_accuracy") 326 | plt.plot(epochs, test_accuracy, label="test_accuracy") 327 | plt.title("Accuracy") 328 | plt.xlabel("Epochs") 329 | plt.legend() -------------------------------------------------------------------------------- /PracticePytorch/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/.DS_Store -------------------------------------------------------------------------------- /PracticePytorch/03CV.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true, 8 | "ExecuteTime": { 9 | "end_time": "2023-06-12T17:19:47.960360Z", 10 | "start_time": "2023-06-12T17:19:46.651253Z" 11 | } 12 | }, 13 | "outputs": [], 14 | "source": [ 15 | "import torch\n", 16 | "from torch import nn\n", 17 | "import torchvision\n", 18 | "from torchvision import transforms as trans\n", 19 | "from torchvision import datasets\n", 20 | "\n", 21 | "import matplotlib.pyplot as plt\n", 22 | "\n" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": 2, 28 | "outputs": [ 29 | { 30 | "name": "stdout", 31 | "output_type": "stream", 32 | "text": [ 33 | "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz\n", 34 | "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to ./data/FashionMNIST/FashionMNIST/raw/train-images-idx3-ubyte.gz\n" 35 | ] 36 | }, 37 | { 38 | "data": { 39 | "text/plain": " 0%| | 0/26421880 [00:00", 172 | "image/png": "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" 173 | }, 174 | "metadata": {}, 175 | "output_type": "display_data" 176 | } 177 | ], 178 | "source": [ 179 | "# transfer tensor to np\n", 180 | "print(train_set.train_data.size())\n", 181 | "\n", 182 | "plt.figure(figsize = (4, 4))\n", 183 | "img = train_set.train_data[0].numpy()\n", 184 | "plt.title(train_set.train_labels[0])\n", 185 | "plt.imshow(img, cmap='gray')\n", 186 | "plt.show()\n", 187 | "\n" 188 | ], 189 | "metadata": { 190 | "collapsed": false, 191 | "ExecuteTime": { 192 | "end_time": "2023-06-12T17:27:52.398329Z", 193 | "start_time": "2023-06-12T17:27:52.328533Z" 194 | } 195 | } 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 9, 200 | "outputs": [ 201 | { 202 | "data": { 203 | "text/plain": "['T-shirt/top',\n 'Trouser',\n 'Pullover',\n 'Dress',\n 'Coat',\n 'Sandal',\n 'Shirt',\n 'Sneaker',\n 'Bag',\n 'Ankle boot']" 204 | }, 205 | "execution_count": 9, 206 | "metadata": {}, 207 | "output_type": "execute_result" 208 | } 209 | ], 210 | "source": [ 211 | "train_set.data.__len__()\n", 212 | "\n", 213 | "train_set.classes\n" 214 | ], 215 | "metadata": { 216 | "collapsed": false, 217 | "ExecuteTime": { 218 | "end_time": "2023-06-12T17:36:29.090501Z", 219 | "start_time": "2023-06-12T17:36:29.085122Z" 220 | } 221 | } 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 10, 226 | "outputs": [], 227 | "source": [ 228 | "batch_size = 32\n", 229 | "train_loader = torch.utils.data.DataLoader(\n", 230 | " dataset = train_set,\n", 231 | " batch_size = batch_size,\n", 232 | " shuffle = True\n", 233 | " )\n", 234 | "\n", 235 | "test_loader = torch.utils.data.DataLoader(\n", 236 | " dataset = test_set,\n", 237 | " batch_size = batch_size,\n", 238 | " shuffle = False\n", 239 | " )\n", 240 | "\n" 241 | ], 242 | "metadata": { 243 | "collapsed": false, 244 | "ExecuteTime": { 245 | "end_time": "2023-06-12T17:44:30.188280Z", 246 | "start_time": "2023-06-12T17:44:30.176327Z" 247 | } 248 | } 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 15, 253 | "outputs": [ 254 | { 255 | "data": { 256 | "text/plain": "(torch.Size([32, 1, 28, 28]), torch.Size([32]))" 257 | }, 258 | "execution_count": 15, 259 | "metadata": {}, 260 | "output_type": "execute_result" 261 | } 262 | ], 263 | "source": [ 264 | "train_imgs, train_labels = next(iter(train_loader))\n", 265 | "train_imgs.shape, train_labels.shape" 266 | ], 267 | "metadata": { 268 | "collapsed": false, 269 | "ExecuteTime": { 270 | "end_time": "2023-06-12T17:46:35.856399Z", 271 | "start_time": "2023-06-12T17:46:35.848158Z" 272 | } 273 | } 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": null, 278 | "outputs": [], 279 | "source": [ 280 | "# TinyVGG\n", 281 | "class TinyVGG(nn.Module):\n", 282 | " def __init__(self, in_channel: int, output_channel: int, hidden_unit: int):\n", 283 | " super(TinyVGG, self).__init__()\n", 284 | " self.block1 = nn.Sequential(nn.Conv2d(in_channel = in_channel, out_channel = hidden_unit,\n", 285 | " kernel_size = 3,\n", 286 | " stride = 1, padding = 1),\n", 287 | " nn.RelU(),\n", 288 | " nn.Conv2d(in_channel = hidden_unit,\n", 289 | " out_channel = hidden_unit,\n", 290 | " kernel_size = 3, stride = 1, padding = 1),\n", 291 | " nn.RelU(),\n", 292 | " nn.MaxPool2d(kernel_size = 2, stride = 2))\n", 293 | "\n", 294 | " self.block2 = nn.Sequential()" 295 | ], 296 | "metadata": { 297 | "collapsed": false 298 | } 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": null, 303 | "outputs": [], 304 | "source": [], 305 | "metadata": { 306 | "collapsed": false 307 | } 308 | } 309 | ], 310 | "metadata": { 311 | "kernelspec": { 312 | "display_name": "Python 3", 313 | "language": "python", 314 | "name": "python3" 315 | }, 316 | "language_info": { 317 | "codemirror_mode": { 318 | "name": "ipython", 319 | "version": 2 320 | }, 321 | "file_extension": ".py", 322 | "mimetype": "text/x-python", 323 | "name": "python", 324 | "nbconvert_exporter": "python", 325 | "pygments_lexer": "ipython2", 326 | "version": "2.7.6" 327 | } 328 | }, 329 | "nbformat": 4, 330 | "nbformat_minor": 0 331 | } 332 | -------------------------------------------------------------------------------- /PracticePytorch/backbone.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torchvision import transforms 4 | import data_setup, engine 5 | from helper_functions import download_data, set_seeds, plot_loss_curves 6 | from utils import device_check 7 | from module import StandardVit 8 | from torchinfo import summary 9 | from torch.optim.lr_scheduler import LambdaLR 10 | 11 | 12 | # CONFIG 13 | IMG_SIZE = HEIGHT = WIDTH = 224 # image info 14 | CHANNELS = 3 15 | PIN_MEMORY = True # avoid unnecessary copies between CPU and GPU 16 | BATCH_SIZE = 512 # 4096 by default 17 | PATCH_SIZE = 16 18 | TRANSFORMER_LAYER_NUM = 12 19 | HIDDEN_UNIT = 3072 20 | HEAD = 12 21 | MSA_DROPOUT = .0 22 | MLP_DROPOUT = .1 23 | EMBEDDING_DROPOUT = .1 24 | BETA_1 = 0.9 # for Adam optimizer 25 | BETA_2 = 0.999 26 | WEIGHT_DECAY = 0.3 27 | LEARNING_RATE = 0.008 28 | 29 | # number of patches 30 | N = (HEIGHT * WIDTH) // (PATCH_SIZE ** 2) 31 | 32 | 33 | # Get data and set image_path 34 | image_path = download_data( 35 | source = "https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip", 36 | destination = "pizza_steak_sushi" 37 | ) 38 | train_dir = image_path / "train" 39 | test_dir = image_path / "test" 40 | 41 | # Create Dataloader 42 | img_transform = transforms.Compose( 43 | [ 44 | transforms.Resize([IMG_SIZE, IMG_SIZE]), 45 | transforms.ToTensor() 46 | ] 47 | ) 48 | 49 | train_data, test_data, class_names = data_setup.create_dataloaders( 50 | train_dir = train_dir, 51 | test_dir = test_dir, 52 | transform = img_transform, 53 | batch_size = BATCH_SIZE) 54 | 55 | # Build the model 56 | vit = StandardVit(img_size = IMG_SIZE, 57 | in_channels = CHANNELS, 58 | patch_size = PATCH_SIZE, 59 | transformer_layers_num = TRANSFORMER_LAYER_NUM, 60 | mlp_size = HIDDEN_UNIT, 61 | h = HEAD, 62 | msa_dropout = MSA_DROPOUT, 63 | mlp_dropout = MLP_DROPOUT, 64 | embedding_dropout = EMBEDDING_DROPOUT, 65 | num_classes = len(class_names)) 66 | 67 | vit = nn.DataParallel(vit) 68 | 69 | # Print the model info 70 | model_config = summary( model = vit, input_size = (BATCH_SIZE, CHANNELS, HEIGHT, WIDTH), 71 | col_names = ["input_size", "output_size", "num_params", "trainable"], 72 | col_width = 20, 73 | row_settings = ["var_names"]) 74 | 75 | # Train 76 | optimizer = torch.optim.Adam(params = vit.parameters(), 77 | lr = LEARNING_RATE, 78 | betas = (BETA_1, BETA_2), 79 | weight_decay = WEIGHT_DECAY) 80 | num_training_steps = 10000 81 | num_warmup_steps = 1000 82 | 83 | # Define a lambda function for the learning rate schedule 84 | lr_lambda = lambda step: step ** (-0.5) if step != 0 else 1e-4 85 | scheduler = LambdaLR(optimizer, lr_lambda) 86 | 87 | loss = nn.CrossEntropyLoss() 88 | set_seeds() 89 | 90 | result = engine.train(vit, train_data, test_data, optimizer, scheduler, loss, epochs = 1000, 91 | device = device_check()) 92 | 93 | plot_loss_curves(result) 94 | -------------------------------------------------------------------------------- /PracticePytorch/faces/0805personali01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/0805personali01.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/1084239450_e76e00b7e7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/1084239450_e76e00b7e7.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/10comm-decarlo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/10comm-decarlo.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/110276240_bec305da91.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/110276240_bec305da91.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/1198_0_861.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/1198_0_861.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/137341995_e7c48e9a75.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/137341995_e7c48e9a75.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/1383023626_8a49e4879a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/1383023626_8a49e4879a.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/144044282_87cf3ff76e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/144044282_87cf3ff76e.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/152601997_ec6429a43c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/152601997_ec6429a43c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/1549040388_b99e9fa295.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/1549040388_b99e9fa295.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/1878519279_f905d4f34e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/1878519279_f905d4f34e.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2046713398_91aaa6fe1c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2046713398_91aaa6fe1c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2173711035_dbd53b4f9f.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2173711035_dbd53b4f9f.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2210514040_6b03ff2629.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2210514040_6b03ff2629.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2322901504_08122b01ba.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2322901504_08122b01ba.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2327253037_66a61ea6fe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2327253037_66a61ea6fe.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2328398005_d328a70b4c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2328398005_d328a70b4c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2370961440_6bc8ce346c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2370961440_6bc8ce346c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2382SJ8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2382SJ8.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/252418361_440b75751b.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/252418361_440b75751b.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/262007783_943bbcf613.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/262007783_943bbcf613.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2633371780_45b740b670.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2633371780_45b740b670.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2647088981_60e9fe40cd.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2647088981_60e9fe40cd.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2711409561_a0786a3d3d.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2711409561_a0786a3d3d.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2722779845_7fcb64a096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2722779845_7fcb64a096.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2795838930_0cc5aa5f41.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2795838930_0cc5aa5f41.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2902323565_100017b63c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2902323565_100017b63c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2902760364_89c50bde40.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2902760364_89c50bde40.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/2956581526_cd803f2daa.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/2956581526_cd803f2daa.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/297448785_b2dda4b2c0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/297448785_b2dda4b2c0.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/299733036_fff5ea6f8e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/299733036_fff5ea6f8e.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/303808204_1f744bc407.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/303808204_1f744bc407.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3074791551_baee7fa0c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3074791551_baee7fa0c1.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3152653555_68322314f3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3152653555_68322314f3.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3264867945_fe18d442c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3264867945_fe18d442c1.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3273658251_b95f65c244.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3273658251_b95f65c244.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3298715079_5af7c78fcb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3298715079_5af7c78fcb.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3325611505_ddc7beffa1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3325611505_ddc7beffa1.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3362762930_24f76cb89c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3362762930_24f76cb89c.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/343583208_e986824d77.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/343583208_e986824d77.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3461016494_56cce9c984.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3461016494_56cce9c984.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/348272697_832ce65324.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/348272697_832ce65324.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3534188114_2108895291.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3534188114_2108895291.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3534189272_8ef88ba368.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3534189272_8ef88ba368.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3555944509_7b477069c6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3555944509_7b477069c6.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3574737496_6ee8207045.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3574737496_6ee8207045.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/362167809_d5a5dcbfdb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/362167809_d5a5dcbfdb.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/363149951_8be04dc6c0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/363149951_8be04dc6c0.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3638950581_3387685d3a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3638950581_3387685d3a.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3646828311_bfeb429ef7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3646828311_bfeb429ef7.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3689162471_5f9ffb5aa0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3689162471_5f9ffb5aa0.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3718903026_c1bf5dfcf8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3718903026_c1bf5dfcf8.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3790616528_297c0ac935.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3790616528_297c0ac935.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3855944735_e252959937.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3855944735_e252959937.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3856149136_d4595ffdd4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3856149136_d4595ffdd4.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/3872768751_e60d7fdbd5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/3872768751_e60d7fdbd5.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/529447797_0f9d2fb756.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/529447797_0f9d2fb756.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/57635685_d41c98f8ca.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/57635685_d41c98f8ca.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/809285949_6889026b53.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/809285949_6889026b53.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/92053278_be61a225d2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/92053278_be61a225d2.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/96063776_bdb3617b64.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/96063776_bdb3617b64.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/97308305_4b737d0873.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/97308305_4b737d0873.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/britney-bald.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/britney-bald.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/create_landmark_dataset.py: -------------------------------------------------------------------------------- 1 | """Create a sample face landmarks dataset. 2 | 3 | Adapted from dlib/python_examples/face_landmark_detection.py 4 | See this file for more explanation. 5 | 6 | Download a trained facial shape predictor from: 7 | http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 8 | """ 9 | import dlib 10 | import glob 11 | import csv 12 | from skimage import io 13 | 14 | detector = dlib.get_frontal_face_detector() 15 | predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') 16 | num_landmarks = 68 17 | 18 | with open('face_landmarks.csv', 'w', newline= '') as csvfile: 19 | csv_writer = csv.writer(csvfile) 20 | 21 | header = ['image_name'] 22 | for i in range(num_landmarks): 23 | header += ['part_{}_x'.format(i), 'part_{}_y'.format(i)] 24 | 25 | csv_writer.writerow(header) 26 | 27 | for f in glob.glob('*.jpg'): 28 | img = io.imread(f) 29 | dets = detector(img, 1) # face detection 30 | 31 | # ignore all the files with no or more than one faces detected. 32 | if len(dets) == 1: 33 | row = [f] 34 | 35 | d = dets[0] 36 | # Get the landmarks/parts for the face in box d. 37 | shape = predictor(img, d) 38 | for i in range(num_landmarks): 39 | part_i_x = shape.part(i).x 40 | part_i_y = shape.part(i).y 41 | row += [part_i_x, part_i_y] 42 | 43 | csv_writer.writerow(row) 44 | -------------------------------------------------------------------------------- /PracticePytorch/faces/deeny.peggy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/deeny.peggy.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/face_landmarks.csv: -------------------------------------------------------------------------------- 1 | image_name,part_0_x,part_0_y,part_1_x,part_1_y,part_2_x,part_2_y,part_3_x,part_3_y,part_4_x,part_4_y,part_5_x,part_5_y,part_6_x,part_6_y,part_7_x,part_7_y,part_8_x,part_8_y,part_9_x,part_9_y,part_10_x,part_10_y,part_11_x,part_11_y,part_12_x,part_12_y,part_13_x,part_13_y,part_14_x,part_14_y,part_15_x,part_15_y,part_16_x,part_16_y,part_17_x,part_17_y,part_18_x,part_18_y,part_19_x,part_19_y,part_20_x,part_20_y,part_21_x,part_21_y,part_22_x,part_22_y,part_23_x,part_23_y,part_24_x,part_24_y,part_25_x,part_25_y,part_26_x,part_26_y,part_27_x,part_27_y,part_28_x,part_28_y,part_29_x,part_29_y,part_30_x,part_30_y,part_31_x,part_31_y,part_32_x,part_32_y,part_33_x,part_33_y,part_34_x,part_34_y,part_35_x,part_35_y,part_36_x,part_36_y,part_37_x,part_37_y,part_38_x,part_38_y,part_39_x,part_39_y,part_40_x,part_40_y,part_41_x,part_41_y,part_42_x,part_42_y,part_43_x,part_43_y,part_44_x,part_44_y,part_45_x,part_45_y,part_46_x,part_46_y,part_47_x,part_47_y,part_48_x,part_48_y,part_49_x,part_49_y,part_50_x,part_50_y,part_51_x,part_51_y,part_52_x,part_52_y,part_53_x,part_53_y,part_54_x,part_54_y,part_55_x,part_55_y,part_56_x,part_56_y,part_57_x,part_57_y,part_58_x,part_58_y,part_59_x,part_59_y,part_60_x,part_60_y,part_61_x,part_61_y,part_62_x,part_62_y,part_63_x,part_63_y,part_64_x,part_64_y,part_65_x,part_65_y,part_66_x,part_66_y,part_67_x,part_67_y 2 | 0805personali01.jpg,27,83,27,98,29,113,33,127,39,139,49,150,60,159,73,166,87,168,100,166,111,160,120,151,128,141,133,128,137,116,138,102,138,89,44,70,53,66,63,65,73,66,82,70,103,72,111,69,120,68,128,69,135,73,92,82,92,91,92,100,92,109,82,117,86,119,91,120,95,119,99,118,55,82,62,78,70,79,76,84,69,86,61,85,106,86,111,81,119,81,125,85,120,88,112,88,71,137,78,131,85,127,90,129,94,129,99,134,103,142,97,144,92,145,88,145,83,144,77,141,75,137,85,134,89,135,93,136,100,141,93,135,89,135,84,134 3 | 1084239450_e76e00b7e7.jpg,70,236,71,257,75,278,82,299,90,320,100,340,111,359,126,375,149,379,175,376,197,364,218,346,236,322,249,296,254,266,256,237,256,207,65,210,69,197,80,193,93,196,106,201,143,196,160,185,179,180,198,182,212,193,127,212,126,230,126,248,125,266,113,279,122,283,132,285,143,281,154,277,81,224,87,216,98,215,110,222,99,225,88,227,159,216,170,207,181,206,192,212,183,215,171,216,110,314,117,310,126,308,135,309,147,307,164,306,184,307,167,317,152,321,139,323,130,322,120,318,114,313,127,312,136,313,148,311,179,308,149,312,137,314,128,312 4 | 10comm-decarlo.jpg,66,114,65,128,67,142,68,156,72,169,80,180,91,189,103,195,115,197,128,197,139,192,148,184,154,173,160,162,164,150,169,138,171,126,80,101,87,95,98,92,108,96,116,101,139,103,147,100,156,100,164,105,168,113,127,113,127,121,126,128,126,136,115,143,119,145,124,147,128,146,132,146,90,112,97,108,104,109,110,114,103,115,96,114,139,118,146,114,153,116,157,121,152,122,146,121,101,163,109,157,117,155,123,157,129,156,134,160,139,168,133,171,126,172,120,172,114,171,107,168,104,162,116,161,122,162,128,162,136,167,127,166,121,165,116,164 5 | 110276240_bec305da91.jpg,42,140,45,161,51,180,61,200,73,220,89,238,108,255,129,268,155,268,180,261,203,244,222,224,238,199,247,172,248,144,245,116,241,87,39,114,45,102,57,97,72,96,87,99,120,91,136,78,155,70,178,66,199,71,108,114,111,132,115,150,118,168,107,180,116,182,127,182,138,177,147,171,57,134,65,127,77,122,92,125,80,130,68,134,143,111,155,103,167,100,182,101,170,107,158,109,98,207,107,199,120,193,131,193,142,188,162,185,184,187,168,206,151,218,139,222,127,223,113,219,103,206,122,203,133,201,144,197,180,189,147,204,136,208,125,209 6 | 1198_0_861.jpg,138,392,141,427,145,464,152,501,166,536,186,567,214,594,249,614,290,616,329,608,363,589,390,562,411,529,421,491,425,450,425,409,423,370,162,345,178,330,200,326,224,328,246,335,282,331,308,320,336,313,365,314,387,329,269,362,271,386,272,409,274,433,249,459,263,460,277,462,290,459,304,458,190,372,204,365,220,364,236,373,220,377,204,377,312,368,328,356,346,354,361,361,348,368,330,369,228,514,246,502,264,495,278,499,292,495,315,502,341,511,318,530,297,538,281,539,266,537,248,529,239,513,265,507,278,509,293,507,331,511,294,516,279,518,265,516 7 | 137341995_e7c48e9a75.jpg,-4,129,1,178,10,231,30,276,59,314,98,349,135,375,171,398,205,402,242,387,284,358,327,327,366,290,390,240,398,185,394,126,391,66,10,77,23,45,52,23,92,14,130,21,180,13,209,-5,248,-6,284,2,317,19,157,67,158,93,160,121,161,150,129,184,152,188,176,190,197,182,216,170,47,102,65,81,91,78,123,91,95,100,69,105,211,72,232,54,258,48,283,58,263,70,237,74,119,265,134,240,156,224,178,226,199,216,237,224,271,238,249,289,218,311,194,316,170,318,144,303,130,265,161,244,182,241,204,238,260,241,210,281,188,286,166,286 8 | 1383023626_8a49e4879a.jpg,0,48,-6,94,-10,141,-8,186,6,228,26,265,49,299,78,325,110,334,140,328,166,303,191,276,218,248,245,219,265,187,278,152,287,114,55,64,84,58,113,61,141,70,164,85,216,90,236,79,258,75,278,75,291,84,185,113,182,145,180,176,176,208,127,198,145,210,164,221,185,214,200,203,80,96,101,99,119,101,135,107,116,107,98,104,214,112,233,110,249,111,263,112,248,117,232,116,70,216,104,222,135,226,152,231,168,228,185,225,201,225,180,263,158,282,140,286,121,283,93,264,78,221,132,232,149,235,165,233,194,230,163,263,145,268,128,265 9 | 144044282_87cf3ff76e.jpg,122,104,121,116,121,129,122,142,125,155,130,167,137,178,147,187,159,190,174,189,189,183,202,175,213,165,220,152,223,138,225,123,227,108,128,96,134,92,141,92,149,95,156,98,174,96,182,94,191,93,200,94,207,99,163,105,162,113,160,121,159,130,151,135,155,137,160,139,165,138,171,137,136,103,141,101,146,102,151,105,146,105,141,105,179,106,183,104,189,104,195,106,189,108,184,108,144,152,149,149,155,148,159,150,165,149,172,151,181,154,172,158,164,159,158,160,154,159,148,157,147,152,155,153,159,154,165,154,178,154,164,153,159,154,154,153 10 | 152601997_ec6429a43c.jpg,109,66,108,98,111,132,118,169,127,203,141,236,157,264,180,281,207,288,240,288,278,279,312,261,342,236,362,200,373,161,377,118,378,75,110,40,124,28,143,26,163,29,184,34,213,28,240,19,268,17,297,23,322,36,196,68,192,93,187,118,182,143,172,164,181,168,190,170,202,167,216,166,132,70,142,61,159,62,174,77,158,80,141,79,242,75,255,57,274,56,292,64,276,75,257,78,165,223,173,209,183,201,193,203,204,199,224,205,247,220,226,227,209,231,197,231,187,230,177,228,172,222,184,217,194,217,205,216,239,220,208,216,197,217,187,216 11 | 1549040388_b99e9fa295.jpg,149,89,139,123,136,159,139,195,146,234,156,274,168,310,184,343,214,360,256,361,303,347,350,326,393,298,423,259,439,212,448,163,453,112,144,39,154,23,173,19,194,22,212,33,261,33,291,22,324,22,356,34,380,55,227,74,219,105,210,135,200,167,187,181,197,190,210,197,229,193,248,190,160,72,172,62,190,64,206,79,188,79,171,78,285,83,302,70,322,71,343,83,323,87,303,86,174,222,182,219,197,221,212,227,231,226,264,232,301,241,264,262,232,269,211,267,194,261,181,245,182,225,196,232,212,237,231,238,292,243,232,251,212,248,196,242 12 | 1878519279_f905d4f34e.jpg,144,178,145,191,149,205,157,220,166,233,175,245,184,257,194,267,205,270,221,267,238,257,257,245,271,229,281,210,284,189,283,167,281,144,142,150,145,143,152,142,159,144,167,148,184,145,196,137,210,132,224,132,239,137,177,163,177,174,176,185,175,196,172,207,177,209,183,209,190,206,198,203,150,168,154,160,162,159,170,166,163,170,155,171,202,160,207,149,216,148,226,152,219,158,209,161,177,238,176,227,180,221,186,221,191,219,204,222,218,228,210,238,199,243,193,245,187,246,182,244,180,236,183,228,188,227,193,226,213,228,196,234,190,235,185,236 13 | 2046713398_91aaa6fe1c.jpg,67,201,69,233,74,264,81,294,93,322,112,347,138,365,169,375,199,377,224,370,243,352,256,330,264,306,271,281,277,257,282,232,281,208,107,177,124,164,147,158,170,162,191,172,230,175,244,167,260,161,276,164,286,176,209,197,211,217,213,237,216,257,189,270,199,275,210,278,220,274,227,269,130,199,144,190,160,190,173,203,158,206,142,206,228,204,242,191,257,191,267,201,258,208,243,207,160,310,181,303,198,298,208,301,217,298,228,302,238,306,227,318,217,324,207,325,195,325,179,321,167,310,197,310,208,311,217,309,231,307,216,309,207,311,197,310 14 | 2173711035_dbd53b4f9f.jpg,28,127,29,172,34,214,42,255,58,292,82,326,110,355,140,378,173,382,203,373,227,350,250,324,272,297,288,264,301,229,313,192,320,153,66,145,93,132,125,134,155,142,182,154,221,155,246,146,271,141,295,140,312,152,199,179,198,211,198,245,198,277,158,275,174,283,191,291,208,285,221,277,98,173,118,170,138,170,155,179,136,182,116,182,230,180,250,173,268,173,282,176,268,185,250,184,124,302,149,302,171,302,185,306,200,302,213,303,228,300,211,319,197,332,181,336,166,335,145,324,133,305,169,312,184,315,199,312,221,304,198,311,183,315,168,313 15 | 2210514040_6b03ff2629.jpg,265,271,264,276,264,281,263,287,263,292,264,296,267,300,270,304,275,306,280,306,286,305,292,303,297,300,301,296,304,292,307,287,310,281,269,270,272,268,276,268,279,269,282,271,291,273,295,272,299,273,303,274,306,276,286,275,284,278,283,282,282,285,278,286,279,287,281,288,283,288,285,288,271,274,274,274,277,274,279,276,276,276,273,275,292,277,295,277,298,277,300,279,298,279,295,278,271,292,274,291,277,291,279,292,282,292,285,294,287,296,284,298,280,299,277,298,275,298,273,295,272,292,277,293,279,294,281,294,286,296,281,295,278,295,276,294 16 | 2322901504_08122b01ba.jpg,195,202,191,219,187,236,191,254,198,272,207,290,214,308,222,326,238,335,262,335,291,327,319,317,344,303,362,281,368,254,370,226,370,200,192,167,195,159,203,160,211,165,219,173,243,171,261,163,280,160,300,166,316,177,229,189,224,203,217,216,211,230,206,241,213,246,222,250,232,247,244,245,201,189,206,182,216,183,225,193,215,194,205,194,259,196,270,186,283,187,296,196,283,200,271,199,207,266,208,262,216,260,224,263,233,262,254,266,281,271,257,287,237,292,228,291,219,289,211,280,212,267,218,268,225,269,234,269,273,272,235,279,226,277,219,274 17 | 2327253037_66a61ea6fe.jpg,118,198,123,225,130,253,140,279,156,304,178,324,204,338,231,345,257,341,276,331,292,311,303,290,313,267,320,244,321,222,317,202,313,182,150,177,162,162,182,152,203,149,222,155,248,147,261,139,276,138,289,145,295,157,238,168,243,186,247,203,252,221,219,234,232,238,246,242,259,236,269,230,174,185,185,180,196,178,207,180,199,182,188,184,257,175,266,171,275,171,285,175,276,176,267,176,190,260,211,256,233,254,247,256,259,252,274,253,288,255,275,273,262,284,248,286,235,285,212,278,196,261,233,260,247,260,259,258,282,257,261,274,247,278,234,276 18 | 2328398005_d328a70b4c.jpg,13,183,8,224,6,267,11,308,31,343,61,372,96,393,134,408,169,414,196,408,213,387,228,365,242,340,255,314,264,287,269,262,270,236,98,160,124,152,152,152,179,158,202,172,234,188,248,183,264,182,276,185,282,196,214,206,216,228,218,251,221,275,175,286,189,293,203,299,215,298,224,291,121,192,139,188,154,190,166,204,150,204,135,201,225,216,241,209,254,211,261,223,252,226,238,222,131,327,162,326,185,326,194,331,202,329,209,333,213,338,204,349,196,352,187,352,177,351,157,345,139,330,182,335,192,337,199,337,208,338,199,339,191,338,181,337 19 | 2370961440_6bc8ce346c.jpg,66,132,68,160,72,187,82,214,99,234,124,247,152,254,178,259,203,260,222,255,234,241,245,225,251,206,256,186,256,166,252,146,245,127,108,95,123,84,142,78,162,78,181,85,203,89,215,87,228,89,237,93,244,102,196,109,199,119,204,129,208,140,182,161,192,164,202,165,209,164,216,161,130,113,142,106,153,106,164,114,153,115,141,115,207,118,217,112,227,114,233,122,226,122,216,120,167,199,186,190,199,184,205,186,211,184,219,189,225,198,219,204,212,205,206,206,199,206,186,205,173,199,199,195,205,194,210,194,221,197,211,195,206,195,200,195 20 | 2382SJ8.jpg,50,100,49,112,50,124,52,137,56,149,63,159,71,169,82,175,95,178,109,177,121,171,131,164,138,154,144,143,147,130,149,118,150,105,58,94,64,86,74,83,84,84,94,86,108,86,118,84,128,84,136,88,142,96,100,96,99,103,98,109,98,116,83,121,90,123,97,125,105,124,112,124,66,99,73,96,79,96,85,99,79,99,73,99,115,101,121,97,127,97,132,101,127,101,121,101,73,141,80,133,90,130,97,132,105,131,114,136,122,145,113,152,104,155,96,155,88,153,79,149,76,140,89,136,97,136,104,137,118,144,104,147,96,147,89,146 21 | 252418361_440b75751b.jpg,265,146,263,166,266,188,273,211,282,233,293,252,305,272,318,287,340,291,367,288,399,277,430,261,455,237,472,207,476,172,472,134,468,99,257,114,259,105,266,100,277,99,288,102,308,94,329,84,352,78,376,81,398,91,300,117,297,135,293,153,289,171,289,189,297,193,307,194,317,188,329,184,272,129,277,120,287,117,297,124,288,129,278,131,341,114,348,103,361,100,375,105,364,112,352,114,300,232,298,226,305,222,314,223,324,219,344,219,368,220,350,231,333,240,322,242,313,243,304,239,302,231,308,229,316,229,327,227,361,221,328,227,318,229,309,228 22 | 262007783_943bbcf613.jpg,123,137,128,176,137,215,150,250,171,278,200,302,230,318,262,329,289,326,307,315,320,291,330,268,341,244,352,220,360,195,363,169,361,145,177,107,197,89,224,82,252,84,278,95,326,99,338,91,351,88,363,89,367,99,305,131,310,159,317,187,324,215,283,225,297,229,310,233,321,229,328,221,212,134,227,121,246,121,260,135,246,140,227,140,315,134,328,119,344,119,351,130,344,137,329,137,247,258,271,253,292,250,302,252,311,248,317,248,321,250,317,260,312,269,302,273,289,273,270,269,255,258,291,259,301,260,311,256,316,252,312,254,302,258,292,258 23 | 2633371780_45b740b670.jpg,101,174,117,201,137,226,159,248,186,268,213,285,236,301,261,312,287,307,313,288,335,260,353,228,365,192,368,153,358,113,345,73,328,35,83,144,86,130,100,122,117,118,138,117,159,99,178,80,200,66,226,57,255,58,163,134,172,163,180,192,189,221,180,228,194,232,210,232,223,220,235,208,112,157,118,147,131,141,147,143,136,151,124,157,205,116,212,103,226,95,245,92,234,103,220,111,204,260,208,257,216,252,227,251,236,242,257,233,281,222,272,247,258,263,248,270,236,273,222,270,209,260,221,257,232,255,242,249,276,227,248,250,238,256,227,257 24 | 2647088981_60e9fe40cd.jpg,93,213,99,226,106,238,113,250,124,260,138,266,153,268,169,269,183,266,192,261,197,252,201,242,201,229,199,216,196,204,192,192,188,182,107,201,112,192,122,186,133,184,144,185,155,181,161,175,168,171,177,171,182,176,153,190,158,197,162,204,167,211,156,223,162,222,168,222,171,219,174,216,122,202,126,197,132,195,138,197,134,200,128,202,163,189,166,183,172,181,176,183,174,186,169,188,151,247,158,239,165,234,170,233,173,231,179,230,184,233,182,235,178,237,175,239,170,241,162,244,153,245,166,237,171,236,175,234,182,233,176,234,172,236,168,238 25 | 2711409561_a0786a3d3d.jpg,179,159,180,186,182,211,185,238,191,264,202,285,217,306,233,325,256,332,283,331,309,318,331,302,351,281,367,255,377,225,381,194,383,161,180,143,188,131,206,132,222,139,238,150,274,152,294,145,314,141,336,144,352,154,258,174,258,196,258,217,257,238,237,241,247,248,258,253,270,250,281,245,198,164,208,157,224,160,235,173,221,176,206,174,291,177,303,167,317,167,330,174,318,180,304,180,222,276,234,273,246,273,257,276,270,273,283,273,298,278,283,291,268,298,256,299,243,297,231,290,227,277,246,280,257,281,269,280,291,279,269,285,257,287,245,285 26 | 2722779845_7fcb64a096.jpg,71,128,63,151,58,173,56,196,57,218,63,240,74,257,90,270,111,280,135,287,161,288,187,286,208,277,224,262,238,244,249,224,259,203,89,107,103,95,123,93,142,99,158,111,181,119,205,120,228,127,245,141,251,164,162,140,156,149,149,158,142,168,122,184,129,189,136,194,146,197,156,200,101,129,114,123,129,126,138,141,124,141,110,137,185,159,202,152,216,158,224,173,212,173,197,167,95,215,109,210,121,210,128,216,137,217,149,228,163,244,143,244,129,240,120,236,111,232,103,225,101,216,118,219,126,223,135,226,156,240,133,228,124,225,116,221 27 | 2795838930_0cc5aa5f41.jpg,234,92,228,107,222,122,218,139,218,154,222,169,229,182,238,193,253,201,269,206,287,204,302,199,315,191,325,181,334,169,341,156,347,143,250,87,260,82,271,83,282,88,290,98,302,104,315,105,328,108,339,117,342,129,292,112,287,123,283,132,278,143,261,144,267,149,273,154,281,155,289,156,256,101,263,101,270,104,274,110,267,108,260,105,307,124,315,123,322,127,327,132,320,131,313,128,243,155,254,157,263,159,269,163,276,165,284,171,293,176,280,177,269,176,262,173,256,169,249,163,246,157,261,164,267,168,274,170,290,176,272,170,265,168,259,164 28 | 2902323565_100017b63c.jpg,79,219,77,246,78,273,82,300,88,325,99,350,114,372,132,388,155,394,177,391,195,377,211,359,225,339,236,317,244,294,249,270,252,245,97,207,109,195,126,192,143,195,159,204,187,208,203,204,220,205,235,212,242,228,170,229,168,249,166,267,165,287,143,296,152,300,162,305,172,303,181,300,112,225,123,218,135,221,145,233,133,234,120,232,189,239,201,230,213,231,222,241,213,244,200,243,123,322,136,320,151,320,161,323,171,321,184,322,195,324,184,341,171,350,160,351,149,349,135,339,128,324,150,328,160,330,170,328,190,325,171,334,161,336,151,334 29 | 2902760364_89c50bde40.jpg,69,235,72,263,78,290,84,316,95,340,112,360,132,378,151,394,172,398,193,393,214,377,235,359,253,338,264,313,269,284,272,255,274,224,80,235,95,225,114,225,133,230,152,237,188,235,206,226,224,220,243,218,259,226,169,256,169,274,168,293,168,312,150,318,159,321,169,324,178,321,187,317,106,250,118,242,134,243,145,257,132,260,116,259,195,255,206,240,222,238,235,245,225,255,209,257,132,340,147,341,160,340,168,342,176,339,190,341,206,339,190,353,177,360,168,361,159,360,147,354,139,343,160,347,168,348,177,347,199,342,177,347,168,349,160,347 30 | 2956581526_cd803f2daa.jpg,79,65,77,81,78,96,80,111,83,126,88,139,97,150,109,159,122,162,138,162,156,158,172,150,183,139,190,124,194,108,198,92,201,74,83,52,89,45,99,43,109,45,119,51,144,52,155,49,168,48,179,52,187,60,130,66,129,77,127,89,125,100,116,105,120,108,126,110,132,109,139,107,94,63,101,59,109,61,116,68,108,68,99,66,149,70,157,64,165,64,172,70,165,71,156,71,105,120,114,120,120,119,126,121,132,121,140,123,151,126,139,130,130,131,124,130,118,129,112,127,109,122,120,124,126,125,131,126,147,126,131,125,125,124,119,123 31 | 297448785_b2dda4b2c0.jpg,25,194,27,239,34,283,44,326,61,368,83,407,109,441,143,466,176,477,210,473,243,453,271,422,295,387,316,347,332,304,345,259,350,215,53,139,71,113,101,102,134,103,165,112,228,114,259,107,290,109,317,122,332,148,194,160,192,181,190,202,187,223,161,256,173,262,185,265,200,265,213,263,89,170,107,156,133,156,153,174,132,179,106,179,234,178,254,162,280,165,298,183,280,190,255,187,141,353,147,316,169,300,180,305,195,305,215,329,222,372,211,391,192,403,176,403,161,398,144,379,151,351,168,323,179,325,193,328,211,367,192,378,178,377,165,373 32 | 299733036_fff5ea6f8e.jpg,122,149,121,163,119,177,119,192,124,205,134,216,146,226,158,233,172,237,182,236,189,229,194,219,198,210,202,200,206,191,209,182,211,174,149,144,159,140,169,140,179,143,187,149,199,153,205,152,211,152,216,155,217,161,191,161,192,169,193,176,194,183,178,188,182,191,187,193,190,193,193,192,157,155,163,153,169,155,173,160,168,160,162,158,194,167,200,164,205,166,207,170,204,171,198,170,163,204,172,199,180,199,184,201,188,201,190,206,190,213,187,214,184,214,180,213,175,211,169,208,166,204,179,204,183,206,186,207,188,211,186,207,182,206,178,204 33 | 303808204_1f744bc407.jpg,167,137,170,168,176,199,182,230,192,260,210,284,233,304,260,320,291,323,321,315,344,295,363,272,377,245,383,215,386,185,389,155,390,126,187,130,204,118,226,115,249,116,270,123,292,121,312,115,334,112,356,114,373,126,282,148,283,167,284,186,286,205,263,221,274,224,287,226,298,222,308,218,213,147,226,141,241,142,253,153,240,155,224,155,311,151,323,140,338,138,351,144,340,152,325,153,248,259,263,249,276,244,287,247,298,243,312,246,326,253,314,262,301,268,289,270,278,269,264,267,255,258,277,255,288,256,299,253,319,252,300,254,288,257,277,256 34 | 3074791551_baee7fa0c1.jpg,187,160,186,179,188,198,193,216,200,232,210,248,221,261,233,271,247,275,263,275,278,266,291,254,303,239,312,222,320,205,326,187,329,168,196,147,208,142,221,143,234,148,246,156,277,158,289,152,302,149,315,151,324,158,258,169,256,185,254,200,253,216,238,219,245,222,252,226,260,223,268,221,209,163,218,159,229,160,238,169,227,170,216,169,280,172,290,165,301,165,309,170,301,175,290,175,224,237,234,236,244,235,251,238,258,236,267,238,278,241,267,250,257,253,250,253,242,252,233,247,229,238,243,240,250,242,258,241,273,242,258,241,250,242,243,240 35 | 3152653555_68322314f3.jpg,88,63,84,83,82,103,82,124,85,144,94,162,106,178,118,192,133,197,146,197,159,187,171,175,182,163,193,150,202,136,210,122,216,106,112,62,126,58,141,58,155,63,167,72,186,78,197,76,207,76,216,79,219,88,173,91,171,104,169,117,166,130,148,131,154,136,159,140,165,140,169,139,126,81,136,79,145,81,150,89,143,89,133,87,182,98,192,95,201,97,205,102,199,105,191,103,118,143,133,145,147,146,152,149,159,150,166,154,171,158,160,167,151,169,143,168,137,166,127,157,123,145,144,150,150,153,156,154,166,158,154,161,147,160,141,157 36 | 3264867945_fe18d442c1.jpg,194,167,194,185,195,204,199,222,206,239,216,255,228,269,243,278,259,279,275,276,289,267,301,254,311,238,317,222,320,204,320,186,319,169,201,148,207,135,219,129,234,129,247,134,266,134,278,129,292,129,304,135,310,147,257,152,257,161,257,170,257,179,246,197,252,198,257,199,262,198,268,197,216,157,222,151,232,150,241,158,232,160,222,161,272,158,279,151,289,151,296,158,289,161,280,160,236,235,242,225,251,219,257,222,261,220,271,225,277,235,271,246,263,251,257,251,251,251,242,246,241,234,251,228,257,228,261,228,273,234,262,239,257,240,251,239 37 | 3273658251_b95f65c244.jpg,220,85,221,110,224,135,229,159,237,182,251,202,270,219,290,234,315,238,339,235,356,222,371,204,384,183,391,161,396,137,399,113,399,89,238,72,250,59,269,54,287,55,305,60,325,60,342,54,360,53,377,59,388,72,315,81,316,96,316,112,317,128,296,140,306,142,316,145,327,142,336,140,258,86,268,80,279,80,289,87,278,89,267,89,339,87,349,80,360,80,370,86,361,90,350,89,281,176,293,167,306,162,316,165,326,162,338,168,349,177,338,187,327,192,316,192,306,191,294,186,288,177,306,175,316,176,326,175,343,177,326,174,316,175,306,174 38 | 3298715079_5af7c78fcb.jpg,194,112,187,128,182,146,181,165,182,183,187,203,193,220,202,235,218,243,240,244,269,241,297,233,321,220,337,201,345,176,349,150,352,125,193,86,197,80,204,79,211,80,218,84,236,84,251,80,269,80,286,86,300,96,222,102,216,113,209,124,202,135,198,152,204,155,210,158,219,157,229,156,197,109,201,101,209,101,217,107,209,109,201,110,250,109,258,102,268,103,280,109,268,111,258,111,197,185,199,178,204,173,210,175,216,174,230,181,249,190,230,196,217,198,210,198,204,196,199,192,200,185,205,184,210,184,217,184,242,189,217,186,210,185,205,185 39 | 3325611505_ddc7beffa1.jpg,134,118,135,133,137,149,139,164,144,178,152,191,161,202,172,211,185,214,197,212,207,204,215,192,224,179,229,165,233,150,235,135,236,120,142,119,149,112,159,110,168,113,178,117,195,118,204,113,214,110,224,112,229,120,186,131,186,142,186,153,187,164,176,169,181,170,186,172,191,171,196,169,153,129,159,125,167,126,173,132,166,135,158,134,198,133,204,127,212,125,218,130,213,134,205,135,168,186,175,184,181,182,186,184,190,182,196,184,202,186,196,192,191,194,186,195,180,194,174,191,171,186,180,187,185,188,190,187,199,187,191,187,186,188,181,187 40 | 3362762930_24f76cb89c.jpg,106,142,114,175,123,209,135,240,153,268,176,291,203,310,232,319,260,318,285,307,307,290,325,270,340,245,350,217,353,186,353,155,351,124,131,123,148,110,170,107,195,109,219,116,268,116,286,105,305,95,325,93,342,102,243,134,247,155,250,176,254,198,224,209,239,210,255,213,268,206,281,199,160,146,174,136,191,134,207,143,192,148,175,149,274,135,285,121,301,118,317,124,305,131,289,134,192,239,216,233,240,227,256,227,269,221,290,220,311,221,294,248,275,262,259,268,243,268,218,261,200,240,241,237,257,237,270,232,304,225,272,248,258,252,242,253 41 | 343583208_e986824d77.jpg,-8,339,2,368,14,398,31,424,55,442,86,452,118,457,151,458,179,451,199,438,209,419,217,398,220,374,219,351,217,327,209,302,197,280,21,294,34,275,55,263,79,260,103,263,138,257,150,246,164,241,178,240,188,249,128,283,136,297,144,309,153,322,128,349,141,348,154,346,163,342,171,336,54,304,66,291,81,287,98,296,85,303,68,307,147,284,156,269,169,266,180,273,173,281,160,283,120,402,136,383,152,370,164,370,173,364,186,366,195,377,193,390,185,399,175,403,163,407,144,407,129,399,154,385,165,382,175,378,189,377,180,381,170,385,159,387 42 | 3461016494_56cce9c984.jpg,100,187,102,204,106,221,112,236,119,250,129,263,140,272,154,279,169,280,184,276,196,266,207,253,215,238,221,222,223,205,224,187,224,169,108,178,116,170,127,169,138,170,149,172,171,167,182,161,193,156,205,156,214,161,163,183,164,195,165,207,166,220,153,225,160,227,166,229,174,226,180,222,122,192,130,189,138,188,146,189,139,192,131,193,181,184,189,181,197,179,204,179,198,184,190,185,144,245,154,242,161,239,166,241,172,238,179,239,188,240,180,247,174,252,167,253,161,253,154,251,148,245,161,245,167,245,173,244,184,241,173,242,166,244,161,244 43 | 348272697_832ce65324.jpg,127,222,127,246,128,269,130,292,136,315,151,333,172,345,198,352,226,356,252,354,274,346,290,332,299,314,304,294,306,274,309,254,310,235,156,197,169,182,189,176,210,176,229,182,251,184,268,183,284,186,298,195,304,210,241,195,241,206,242,217,243,229,219,250,228,252,237,255,246,254,254,253,176,202,187,195,199,195,209,203,198,203,187,203,258,207,269,202,280,204,288,213,279,212,268,210,191,287,209,279,224,276,233,279,242,278,253,285,263,296,250,297,239,296,230,295,220,294,206,291,197,287,223,284,232,286,241,286,258,294,240,287,231,287,222,285 44 | 3534188114_2108895291.jpg,189,153,188,170,189,187,192,203,199,218,210,231,224,241,237,250,251,253,264,251,274,241,282,230,289,219,295,207,300,194,303,180,303,167,213,143,222,136,234,135,246,139,256,145,274,146,282,143,290,142,297,144,300,152,265,156,265,165,266,174,267,184,249,188,256,191,262,194,267,193,271,192,224,154,230,151,237,152,243,157,236,158,229,157,273,161,280,157,287,158,291,162,286,164,280,163,225,204,238,201,249,201,257,204,264,203,271,205,276,210,269,219,261,222,254,222,245,220,235,214,229,204,248,205,256,207,263,207,273,210,262,216,255,217,247,215 45 | 3534189272_8ef88ba368.jpg,212,152,210,165,210,178,211,192,214,205,218,218,226,229,235,237,248,241,262,241,275,237,287,230,296,220,304,208,309,195,313,182,315,168,219,138,225,132,233,129,242,131,249,137,270,136,279,133,289,134,298,139,303,147,257,147,255,156,254,166,252,175,242,180,246,184,252,186,258,184,265,182,227,149,232,144,239,145,246,150,239,150,232,150,273,153,280,149,287,150,292,155,286,155,279,154,230,194,239,194,247,194,252,195,258,194,268,196,278,199,268,207,258,210,251,210,245,209,238,205,234,196,246,197,252,198,258,198,275,199,258,205,252,205,246,204 46 | 3555944509_7b477069c6.jpg,27,131,27,166,31,200,36,233,48,263,66,290,88,313,116,331,147,337,181,336,211,321,233,296,254,267,269,234,278,199,287,162,292,122,43,98,60,86,84,84,107,89,128,98,180,97,206,86,233,81,260,85,279,101,153,129,152,157,151,184,150,211,124,219,136,226,150,232,165,228,179,223,70,127,86,119,104,120,119,133,101,135,84,135,192,134,210,120,229,119,245,129,231,137,211,137,105,259,123,254,140,253,151,259,164,256,184,261,205,268,184,283,163,288,149,287,136,283,121,272,112,260,139,265,151,269,164,269,197,268,163,273,150,272,138,267 47 | 3574737496_6ee8207045.jpg,186,149,184,166,183,184,185,201,192,217,204,230,217,240,232,248,247,250,261,248,271,240,279,229,287,218,293,206,296,192,297,178,297,165,206,138,217,130,230,130,242,133,254,139,269,140,278,138,287,137,296,141,298,150,262,152,262,161,264,169,265,178,245,184,252,186,259,189,266,188,271,187,222,150,229,147,236,148,241,153,235,153,228,152,269,157,276,154,282,155,286,159,282,160,275,159,226,201,238,199,250,198,256,201,262,200,269,203,273,207,266,219,258,223,252,222,245,220,235,213,229,202,249,202,255,204,261,204,270,208,260,213,254,214,247,212 48 | 362167809_d5a5dcbfdb.jpg,111,150,116,170,121,190,129,209,142,225,160,237,183,244,207,245,228,242,244,235,254,221,260,205,263,187,263,170,261,153,258,137,254,121,134,125,144,114,158,106,174,105,189,107,210,103,220,97,232,94,242,96,248,105,204,121,208,132,213,142,217,153,199,170,207,171,216,172,221,168,226,164,153,136,160,128,170,126,180,131,171,135,161,137,216,124,222,116,231,114,238,119,233,124,224,125,186,202,200,196,211,190,218,191,222,187,229,188,237,189,232,196,227,200,221,202,215,204,202,204,191,201,212,197,219,196,223,194,233,190,225,193,220,196,213,197 49 | 363149951_8be04dc6c0.jpg,88,160,90,181,92,201,94,222,99,241,110,257,124,271,141,282,160,285,178,282,194,272,208,259,219,243,224,224,226,204,230,185,233,165,99,152,108,143,121,139,135,140,148,145,174,147,187,143,201,143,214,147,222,157,160,159,160,170,160,181,160,192,143,203,151,205,159,208,168,206,175,204,114,160,122,155,132,155,141,162,132,163,122,163,179,163,188,157,198,157,206,163,198,165,188,164,125,226,137,222,149,221,158,223,168,222,181,224,192,230,181,243,168,247,158,248,148,246,136,240,130,226,149,226,158,227,168,227,188,230,168,239,159,240,149,238 50 | 3638950581_3387685d3a.jpg,164,135,160,150,158,165,162,180,168,195,173,209,176,225,179,242,190,249,208,251,228,246,248,236,268,222,282,205,292,183,297,159,300,135,162,112,164,105,169,104,176,107,181,112,203,111,217,106,233,104,249,108,261,118,190,127,185,141,179,154,174,167,171,173,176,178,183,181,192,178,202,176,168,127,172,122,181,122,187,129,179,130,172,129,217,131,225,124,234,124,243,130,234,132,225,132,175,189,175,188,181,189,187,192,195,191,212,193,233,195,214,210,197,216,188,216,181,213,176,203,177,191,181,194,187,196,195,196,229,196,196,207,188,207,182,203 51 | 3646828311_bfeb429ef7.jpg,103,188,107,205,113,223,120,240,131,253,147,265,163,275,179,283,195,283,210,276,221,262,232,249,242,233,248,216,249,198,248,179,246,159,108,174,115,166,126,162,139,162,151,164,181,160,191,152,203,146,216,144,230,149,170,178,172,193,175,208,178,224,163,230,172,231,181,232,189,228,196,224,125,185,132,180,141,179,151,183,143,185,133,187,190,176,198,168,207,165,217,167,210,172,200,174,152,241,163,242,173,241,182,242,190,239,202,236,214,232,206,246,195,255,186,257,177,257,165,253,156,243,174,244,183,244,192,242,210,235,193,246,185,249,175,249 52 | 3689162471_5f9ffb5aa0.jpg,237,83,235,94,233,106,233,118,235,129,240,140,246,150,254,158,263,162,272,162,281,156,289,149,296,142,301,133,305,124,309,115,312,105,250,85,257,84,264,86,270,89,276,93,291,96,298,95,304,95,309,96,312,101,282,101,280,109,278,117,277,124,267,125,270,127,274,130,278,129,281,128,256,94,261,92,266,94,269,98,264,98,259,97,289,103,294,101,299,102,302,105,298,106,293,105,258,133,263,136,269,137,272,138,276,138,280,139,283,140,278,144,274,145,270,145,266,144,261,140,260,135,268,139,271,140,275,140,281,141,275,140,271,140,267,139 53 | 3718903026_c1bf5dfcf8.jpg,125,220,124,245,123,269,125,295,134,318,151,337,169,354,189,368,213,373,238,369,259,355,277,340,294,323,305,302,310,278,312,255,315,231,146,206,156,195,171,190,187,193,201,201,247,203,262,196,278,195,293,201,301,214,223,223,222,241,221,259,220,277,195,275,206,281,219,288,232,283,242,278,164,225,176,225,185,225,195,226,185,226,175,226,249,228,260,229,270,229,280,230,270,230,260,229,163,293,182,291,201,294,216,298,233,296,251,295,268,298,251,323,231,332,214,333,198,331,179,320,168,295,201,298,216,301,232,300,263,300,232,323,215,324,199,320 54 | 3790616528_297c0ac935.jpg,51,192,52,216,54,240,59,263,70,285,87,301,108,314,130,323,150,325,169,321,185,309,201,294,211,276,217,255,220,233,220,212,221,193,77,182,91,173,108,171,125,175,142,180,164,182,179,178,192,174,207,176,215,186,154,191,156,203,158,216,160,228,135,240,145,242,154,244,163,242,170,240,96,191,106,189,116,188,125,194,116,195,106,194,172,195,182,190,192,190,200,194,192,197,182,197,113,270,128,264,141,261,150,263,160,261,170,266,181,272,170,277,159,279,150,279,140,277,129,275,119,269,141,268,150,269,160,269,176,272,159,270,150,270,141,269 55 | 3855944735_e252959937.jpg,21,260,25,288,29,315,39,339,55,358,75,371,102,379,131,377,161,374,187,370,205,362,218,346,224,326,229,304,229,282,225,262,220,244,63,205,77,186,97,173,120,170,139,178,169,179,184,172,200,173,214,181,222,196,155,193,159,204,163,215,166,226,136,253,148,254,161,256,172,253,182,250,85,217,98,208,110,204,123,209,111,212,99,214,176,205,190,202,200,202,207,209,198,207,189,206,111,306,128,284,149,277,163,278,175,275,189,280,198,298,189,309,176,314,164,316,149,316,130,315,118,303,149,284,164,283,175,282,193,297,175,305,164,306,149,307 56 | 3856149136_d4595ffdd4.jpg,74,161,79,191,88,219,95,247,102,275,117,300,137,321,162,338,189,343,216,338,238,321,255,299,268,273,274,244,280,215,285,185,287,156,92,155,106,141,125,137,146,138,167,141,193,141,215,138,236,136,256,140,270,152,182,159,183,178,185,197,186,217,162,231,174,234,186,237,197,234,208,230,114,162,125,155,138,155,151,164,138,164,125,165,212,163,224,154,237,155,250,161,238,164,225,163,144,270,160,263,175,258,185,261,195,258,211,263,227,268,212,281,197,287,186,289,175,287,160,281,151,271,175,269,185,270,196,269,221,269,196,271,185,273,175,271 57 | 3872768751_e60d7fdbd5.jpg,268,110,271,124,277,136,283,148,290,160,301,170,314,176,328,180,341,179,353,174,362,165,371,155,377,142,378,128,378,114,377,101,376,88,279,96,285,89,294,84,305,82,314,84,330,81,337,75,346,72,355,72,364,75,324,94,326,102,328,110,330,118,321,129,327,130,332,130,337,127,341,123,292,104,297,100,304,98,311,101,305,104,298,105,338,95,343,90,349,89,355,91,350,94,344,95,311,147,321,144,329,142,334,142,339,140,347,139,356,137,349,146,343,151,337,153,332,154,323,152,314,147,329,145,335,145,340,143,353,139,341,146,336,148,330,149 58 | 529447797_0f9d2fb756.jpg,78,173,81,219,89,266,105,312,128,353,153,392,180,427,210,451,247,457,282,452,311,431,340,398,366,360,386,318,401,272,408,223,410,177,102,163,123,138,155,133,188,141,218,156,260,153,293,139,327,132,361,140,384,164,240,188,241,225,242,263,242,300,209,307,224,314,241,321,258,315,274,308,138,185,157,172,183,174,202,194,180,199,155,198,281,193,302,172,327,171,346,184,330,197,305,198,185,353,205,348,226,345,240,350,255,346,279,351,299,357,280,389,258,408,242,410,226,406,207,387,193,357,226,356,240,359,256,357,291,361,257,383,241,387,226,382 59 | 57635685_d41c98f8ca.jpg,86,118,87,153,87,189,93,225,113,253,141,273,173,287,206,297,235,297,255,288,262,267,268,246,273,224,278,200,280,179,280,156,274,138,155,113,174,101,198,96,221,100,238,112,248,114,258,107,269,106,279,109,281,120,246,131,251,145,257,159,263,174,224,190,237,194,250,199,261,195,269,189,175,126,188,122,199,123,209,131,199,131,187,130,248,134,258,128,267,129,272,135,266,136,257,135,197,230,219,221,237,217,247,221,254,219,260,222,260,231,258,241,252,245,244,245,234,243,217,238,204,228,236,226,247,227,253,226,256,229,252,232,246,232,235,230 60 | 809285949_6889026b53.jpg,27,108,30,123,34,138,40,152,48,165,58,176,69,185,81,195,97,196,115,192,133,183,151,172,165,157,173,138,175,118,174,95,170,74,26,95,30,88,39,86,50,86,60,90,75,87,88,77,103,71,121,68,137,73,71,99,71,111,72,123,72,136,65,142,72,145,80,146,89,142,98,137,39,107,44,103,52,101,62,104,54,107,46,109,97,97,103,91,112,89,122,90,114,95,105,96,67,160,70,156,77,154,85,155,92,151,105,150,119,150,108,160,97,167,89,169,81,169,73,166,71,160,78,159,86,159,94,157,115,151,94,157,87,159,79,159 61 | 92053278_be61a225d2.jpg,145,83,143,112,143,140,148,167,158,193,174,215,193,235,212,257,235,265,261,264,290,255,319,243,343,222,358,195,364,163,368,129,370,96,157,59,167,47,183,43,200,45,217,52,264,54,283,47,303,47,322,54,338,66,236,79,234,98,230,117,227,136,213,148,222,152,231,156,243,153,254,151,174,83,186,72,200,73,214,87,199,89,184,89,274,90,286,77,302,77,315,89,302,94,287,93,198,177,212,172,224,172,235,174,247,173,266,176,289,182,266,197,247,202,234,202,223,199,210,192,204,178,224,176,235,179,247,179,282,182,247,192,235,192,224,189 62 | 96063776_bdb3617b64.jpg,162,177,165,198,170,219,175,240,182,260,195,278,212,291,233,300,257,303,278,296,296,283,310,265,317,245,321,223,323,201,325,179,324,156,178,160,188,147,204,140,222,140,238,145,264,140,277,132,292,129,307,132,316,144,252,160,253,172,254,184,255,197,238,213,247,214,255,215,264,213,271,210,198,166,209,158,220,157,230,166,220,169,209,169,272,161,281,151,292,149,301,155,294,160,283,162,222,244,232,235,246,232,256,233,265,230,277,232,287,240,278,256,266,263,256,265,245,265,232,258,227,243,246,236,256,237,265,235,282,240,265,255,255,257,245,256 63 | 97308305_4b737d0873.jpg,137,157,139,190,142,223,149,255,164,283,182,305,205,322,233,332,264,333,289,326,304,310,315,289,324,266,334,242,342,215,348,188,350,160,173,135,189,119,210,113,233,115,253,125,287,123,303,115,321,113,338,118,347,132,272,140,274,161,275,183,277,205,244,213,258,217,272,221,284,218,295,214,196,145,208,139,221,139,233,147,221,148,208,148,297,147,310,140,322,140,331,146,322,149,310,148,220,255,241,248,259,246,270,248,281,246,294,249,305,256,292,271,279,276,267,277,255,275,238,270,226,255,258,253,270,255,281,254,298,257,279,261,268,262,256,261 64 | britney-bald.jpg,52,134,54,149,56,164,60,179,65,193,73,207,81,219,92,228,106,232,121,230,136,222,150,212,160,198,167,183,171,166,174,149,174,131,54,127,61,122,71,122,81,124,90,128,115,129,125,125,137,122,148,122,159,127,102,138,102,149,102,160,101,171,92,176,97,179,103,180,109,178,115,176,66,137,73,133,81,133,89,139,80,141,72,141,122,140,130,133,139,133,146,138,139,142,130,142,83,191,91,190,99,188,104,189,110,188,120,190,130,192,120,203,110,207,104,208,98,207,91,202,87,193,98,192,104,193,110,193,126,193,110,199,104,200,98,198 65 | deeny.peggy.jpg,39,95,40,106,41,116,44,126,49,136,54,145,60,152,66,159,75,161,84,158,95,153,106,146,115,137,121,126,124,113,125,98,126,84,38,91,40,86,46,84,52,84,59,85,68,83,76,80,85,78,94,79,103,83,63,94,63,103,62,111,62,119,58,124,61,125,66,126,70,124,75,122,44,95,48,92,54,92,58,96,54,99,48,99,78,94,82,88,89,87,94,90,90,94,83,95,60,137,61,136,65,134,68,135,71,133,78,133,88,133,80,139,73,141,69,142,66,143,63,141,62,137,65,137,68,137,72,136,85,134,72,137,69,138,66,137 66 | matt-mathes.jpg,85,152,83,173,83,195,85,217,91,238,103,257,117,274,134,287,154,290,176,287,197,276,218,263,235,247,246,227,251,205,253,181,254,157,91,136,98,127,112,125,126,129,140,135,162,134,177,128,193,126,209,126,222,134,148,149,146,162,144,176,143,190,129,199,137,203,147,206,157,202,167,199,103,148,111,142,122,143,131,151,121,151,111,151,177,150,186,143,196,143,205,148,197,151,186,151,116,224,127,221,140,221,149,223,160,220,177,220,195,224,179,238,163,244,152,245,141,244,129,239,120,225,140,225,150,226,160,224,190,225,162,236,151,237,141,235 67 | person-7.jpg,32,65,33,76,34,86,34,97,37,107,41,116,50,122,61,126,72,127,83,126,95,123,107,119,115,111,118,101,120,91,122,80,122,68,39,52,45,46,53,44,61,46,68,49,82,49,90,45,98,44,106,46,112,52,74,57,74,63,74,69,74,75,67,83,70,84,74,85,78,84,82,83,47,61,51,57,58,57,63,61,57,63,51,63,87,62,93,58,98,58,103,61,99,63,93,63,55,98,63,96,70,94,75,95,80,94,86,95,94,99,86,103,79,105,74,105,69,105,62,103,58,99,70,98,74,98,79,98,91,99,79,99,74,99,69,99 68 | person.jpg,78,83,79,93,80,103,81,112,85,121,91,129,98,136,106,142,115,144,125,142,134,137,142,130,149,122,153,113,154,102,155,91,156,79,84,75,87,71,93,70,99,69,104,72,121,71,127,68,134,67,140,68,146,72,113,81,113,88,112,95,112,102,105,105,109,107,113,108,117,106,121,104,91,83,95,81,100,81,105,84,100,84,95,85,123,83,127,80,132,79,137,81,133,83,128,83,96,114,102,112,109,112,114,114,119,112,126,112,134,113,127,122,120,126,114,126,109,126,102,122,99,115,109,115,114,116,119,115,132,114,120,121,114,122,109,121 69 | person_TjahjonoDGondhowiardjo.jpg,41,92,41,103,43,114,44,125,48,134,54,142,61,148,70,152,80,154,90,153,99,149,107,143,113,135,117,126,119,115,121,104,122,93,49,83,54,79,60,78,67,79,73,82,87,81,94,79,101,78,108,80,112,84,80,90,80,96,80,102,80,108,72,115,76,116,80,116,84,116,88,115,57,90,61,87,67,87,71,91,66,92,61,92,91,91,95,88,101,88,105,91,101,93,95,93,66,130,72,127,77,125,81,126,85,125,90,127,96,130,90,132,85,134,81,134,77,133,71,133,68,130,77,130,81,130,85,130,94,130,85,128,81,128,77,128 70 | personalpic.jpg,40,109,40,122,41,135,42,148,44,161,49,174,56,186,64,196,76,199,89,198,103,192,116,183,127,173,135,160,140,145,142,129,144,112,39,103,44,97,53,96,61,98,70,100,84,100,96,97,108,96,118,100,126,107,76,109,75,121,74,132,72,143,63,144,68,148,73,151,80,149,87,146,49,109,54,106,61,106,66,110,60,111,54,111,94,112,100,108,107,109,113,112,107,114,100,114,58,162,63,160,68,160,74,163,80,161,88,163,97,165,87,169,79,171,73,171,67,170,62,167,60,162,68,164,74,166,80,165,94,165,80,165,74,165,68,164 71 | -------------------------------------------------------------------------------- /PracticePytorch/faces/matt-mathes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/matt-mathes.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/person-7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/person-7.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/person.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/person.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/person_TjahjonoDGondhowiardjo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/person_TjahjonoDGondhowiardjo.jpg -------------------------------------------------------------------------------- /PracticePytorch/faces/personalpic.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/faces/personalpic.jpg -------------------------------------------------------------------------------- /PracticePytorch/runs/Jun18_14-46-04_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687117564.Sherlocks-MacBook-Pro.local.51259.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/Jun18_14-46-04_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687117564.Sherlocks-MacBook-Pro.local.51259.0 -------------------------------------------------------------------------------- /PracticePytorch/runs/Jun18_15-03-00_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687118580.Sherlocks-MacBook-Pro.local.51259.1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/Jun18_15-03-00_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687118580.Sherlocks-MacBook-Pro.local.51259.1 -------------------------------------------------------------------------------- /PracticePytorch/runs/Jun18_15-03-00_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687119446.Sherlocks-MacBook-Pro.local.51259.2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/Jun18_15-03-00_Sherlocks-MacBook-Pro.local/events.out.tfevents.1687119446.Sherlocks-MacBook-Pro.local.51259.2 -------------------------------------------------------------------------------- /PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686965428.Sherlocks-MacBook-Pro.local.31548.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686965428.Sherlocks-MacBook-Pro.local.31548.0 -------------------------------------------------------------------------------- /PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686965887.Sherlocks-MacBook-Pro.local.32194.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686965887.Sherlocks-MacBook-Pro.local.32194.0 -------------------------------------------------------------------------------- /PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686966251.Sherlocks-MacBook-Pro.local.32194.1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/PracticePytorch/runs/efficientnet_b0_pizza_steak_sushi/events.out.tfevents.1686966251.Sherlocks-MacBook-Pro.local.32194.1 -------------------------------------------------------------------------------- /Python&Probability&Statistics/BasicPython/Numpy_Exercise.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true, 8 | "ExecuteTime": { 9 | "end_time": "2023-06-30T20:46:19.620108Z", 10 | "start_time": "2023-06-30T20:46:19.543782Z" 11 | } 12 | }, 13 | "outputs": [ 14 | { 15 | "data": { 16 | "text/plain": "(array([1., 2., 3.], dtype=float32), 4)" 17 | }, 18 | "execution_count": 1, 19 | "metadata": {}, 20 | "output_type": "execute_result" 21 | } 22 | ], 23 | "source": [ 24 | "import numpy as np\n", 25 | "\n", 26 | "x = np.array([1, 2, 3], dtype = np.float32) # 1 byte = 8 bits, 4 bytes = 32 bits\n", 27 | "\n", 28 | "x, x.itemsize" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 2, 34 | "outputs": [ 35 | { 36 | "data": { 37 | "text/plain": "(array([0.841471 , 0.9092974, 0.14112 ], dtype=float32),\n array([0.7615942, 0.9640276, 0.9950548], dtype=float32))" 38 | }, 39 | "execution_count": 2, 40 | "metadata": {}, 41 | "output_type": "execute_result" 42 | } 43 | ], 44 | "source": [ 45 | "np.sin(x), np.tanh(x)" 46 | ], 47 | "metadata": { 48 | "collapsed": false, 49 | "ExecuteTime": { 50 | "end_time": "2023-06-30T20:48:43.672557Z", 51 | "start_time": "2023-06-30T20:48:43.668485Z" 52 | } 53 | } 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 6, 58 | "outputs": [ 59 | { 60 | "data": { 61 | "text/plain": "(array([[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.]]),\n array([[1., 1.],\n [1., 9.]]))" 62 | }, 63 | "execution_count": 6, 64 | "metadata": {}, 65 | "output_type": "execute_result" 66 | } 67 | ], 68 | "source": [ 69 | "x = np.ones((3, 3))\n", 70 | "# add one dim\n", 71 | "y = x[:, [0, 1, 2, 2]] # then y has independent memory area\n", 72 | "\n", 73 | "# however, if z is generated by slicing x\n", 74 | "z = x[:2, :2] # then z is just a view of x, so change the elements in x also change the elements in z\n", 75 | "\n", 76 | "x[1, 1] = 9\n", 77 | "\n", 78 | "y, z" 79 | ], 80 | "metadata": { 81 | "collapsed": false, 82 | "ExecuteTime": { 83 | "end_time": "2023-06-30T23:25:25.796517Z", 84 | "start_time": "2023-06-30T23:25:25.793683Z" 85 | } 86 | } 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 13, 91 | "outputs": [ 92 | { 93 | "data": { 94 | "text/plain": "(array([[1., 1., 1.],\n [1., 9., 1.],\n [1., 1., 1.]]),\n array([[1., 1.],\n [1., 1.]]))" 95 | }, 96 | "execution_count": 13, 97 | "metadata": {}, 98 | "output_type": "execute_result" 99 | } 100 | ], 101 | "source": [ 102 | "# Explicit force a copy\n", 103 | "x = np.ones((3, 3))\n", 104 | "z = x[:2, :2].copy() # z becomes independent\n", 105 | "\n", 106 | "x[1, 1] = 9\n", 107 | "\n", 108 | "x, z" 109 | ], 110 | "metadata": { 111 | "collapsed": false, 112 | "ExecuteTime": { 113 | "end_time": "2023-07-01T00:15:32.455736Z", 114 | "start_time": "2023-07-01T00:15:32.452127Z" 115 | } 116 | } 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": 14, 121 | "outputs": [ 122 | { 123 | "data": { 124 | "text/plain": "( C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False,\n '\\n',\n C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False)" 125 | }, 126 | "execution_count": 14, 127 | "metadata": {}, 128 | "output_type": "execute_result" 129 | } 130 | ], 131 | "source": [ 132 | "x.flags, \"\\n\", z.flags # \"flags\" can help" 133 | ], 134 | "metadata": { 135 | "collapsed": false, 136 | "ExecuteTime": { 137 | "end_time": "2023-07-01T00:15:32.783013Z", 138 | "start_time": "2023-07-01T00:15:32.777025Z" 139 | } 140 | } 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "outputs": [], 146 | "source": [], 147 | "metadata": { 148 | "collapsed": false 149 | } 150 | } 151 | ], 152 | "metadata": { 153 | "kernelspec": { 154 | "display_name": "Python 3", 155 | "language": "python", 156 | "name": "python3" 157 | }, 158 | "language_info": { 159 | "codemirror_mode": { 160 | "name": "ipython", 161 | "version": 2 162 | }, 163 | "file_extension": ".py", 164 | "mimetype": "text/x-python", 165 | "name": "python", 166 | "nbconvert_exporter": "python", 167 | "pygments_lexer": "ipython2", 168 | "version": "2.7.6" 169 | } 170 | }, 171 | "nbformat": 4, 172 | "nbformat_minor": 0 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Paper Replication Repo 2 | - This repo includes detailed replications of popular computer vision papers with exhaustive 3 | annotations. 4 | - All the codes in this project is written by Pytorch. 5 | 6 | - New to Pytorch? [See Your First Pytorch Tutor](https://pytorch.org/tutorials/) 7 | - [The second best place to learn Pytorch](https://www.learnpytorch.io/) 8 | - Important architectures and mechanisms in Machine Learning and Deep Learning are included and 9 | well annotated. 10 | 11 | 12 | 13 | 14 | - [x] Last Update Time: June 19 2023 15 | - [ ] In Process: Swin Transformer from Scratch 16 | 17 | --- 18 | ## Content 19 | 20 | - [Self-Attention & Multi-Head Self-Attention Mechanism and Implementation from Scratch](https://github.com/PeiranLi0930/TorchProject/blob/main/PaperReplicate/Self_Attention_from_Scratch/Self-Attention%20and%20Multi-head%20Attention%20Mechanism%20036331bdfc7649238f86306bb44bed38.md) 21 | 22 | - [Implementation Notebook](https://github.com/PeiranLi0930/TorchProject/blob/main/PaperReplicate/Self_Attention_from_Scratch/self_attention_mechanism.ipynb) 23 | - [Functionalized Version](https://github.com/PeiranLi0930/TorchProject/blob/main/PaperReplicate/Self_Attention_from_Scratch/self_attention.py) 24 | 25 | 26 | 27 | --- 28 | ### Appreciations 29 | 30 | - The [Holy Land](https://www.wisc.edu/) giving me best working environments 31 | - My first Pytorch tutor: [Daniel Bourke](https://github.com/mrdbourke), the creator of [Zero to 32 | Mastery Learn PyTorch for Deep Learning](https://www.learnpytorch.io/) 33 | - Significant Guiders on my path to Machine Learning and Deep Learning: [Robert Nowak](https://nowak.ece.wisc.edu/) 34 | , [Andrew Ng](https://www.andrewng.org/), [Feifei Li](https://profiles.stanford.edu/fei-fei-li) 35 | , [Sharon Zhou](https://sharonzhou.me/), [Sebastian Raschka](https://sebastianraschka.com/) 36 | - I wish to express my boundless gratitude to Professor Vikas Singh. I appreciate him enduring my incessant ignorance, offering me ample patience and tolerance. He is a vital guide on my academic journey. 37 | 38 | 39 | 40 | © 2023 - Peiran in USA - All rights reserved 41 | 42 | --- -------------------------------------------------------------------------------- /Signal_Processing/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/.DS_Store -------------------------------------------------------------------------------- /Signal_Processing/Intro/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/Intro/.DS_Store -------------------------------------------------------------------------------- /Signal_Processing/Intro/glassDance.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/Intro/glassDance.mat -------------------------------------------------------------------------------- /Signal_Processing/Intro/sigprocMXC_filterGlass.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: Signal processing problems, solved in MATLAB and Python 3 | % SECTION: Introduction 4 | % VIDEO: Having fun with filtered Glass dance 5 | % Instructor: sincxpress.com 6 | % 7 | %% 8 | 9 | % load the file 10 | load glassDance.mat 11 | % this is a clip of Philip Glass, Dance VII (https://www.youtube.com/watch?v=LpewOlR-z_4) 12 | 13 | 14 | % play the music! 15 | soundsc(glassclip,srate) 16 | 17 | % some variables for convenience 18 | pnts = length(glassclip); 19 | timevec = (0:pnts-1)/srate; 20 | 21 | % draw the time-domain signals 22 | figure(1), clf 23 | subplot(511) 24 | plot(timevec,glassclip) 25 | xlabel('Time (s)') 26 | 27 | 28 | %% static power spectrum and pick a frequency range 29 | 30 | % inspect the power spectrum 31 | hz = linspace(0,srate/2,floor(length(glassclip)/2)+1); 32 | powr = abs(fft(glassclip(:,1))/pnts); 33 | 34 | subplot(512), cla 35 | plot(hz,powr(1:length(hz))) 36 | set(gca,'xlim',[100 2000],'ylim',[0 max(powr)]) 37 | xlabel('Frequency (Hz)'), ylabel('Amplitude') 38 | 39 | 40 | % pick frequencies to filter 41 | frange = [ 300 460 ]; 42 | frange = [ 1000 1100 ]; 43 | % frange = [ 1200 1450 ]; 44 | 45 | 46 | % design an FIR1 filter 47 | fkern = fir1(2001,frange/(srate/2),'bandpass'); 48 | 49 | % apply the filter to the signal 50 | filtglass(:,1) = filtfilt(fkern,1,glassclip(:,1)); 51 | filtglass(:,2) = filtfilt(fkern,1,glassclip(:,2)); 52 | 53 | % plot the filtered signal power spectrum 54 | hold on 55 | powr = abs(fft(filtglass(:,1))/pnts); 56 | plot(hz,powr(1:length(hz)),'r') 57 | 58 | 59 | % plot the time-frequency response 60 | subplot(5,1,3:5) 61 | spectrogram(glassclip(:,1),hann(round(srate/10)),[],[],srate,'yaxis'); 62 | hold on 63 | plot(timevec([1 1; end end]),frange([1 2; 1 2])/1000,'k:','linew',2) 64 | 65 | % NOTE: use the following line in Octave 66 | %[powspect,frex,time] = specgram(glassclip(:,1),1000,srate,hann(round(srate/10))); 67 | 68 | 69 | set(gca,'ylim',[0 2]) 70 | 71 | %% play the sound 72 | 73 | soundsc(filtglass,srate) 74 | 75 | %% done. 76 | 77 | -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/__pycache__/slective_search.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/__pycache__/slective_search.cpython-310.pyc -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/2012_001297.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/2012_001297.jpg -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/cats.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/cats.png -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/example_id1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/example_id1.JPG -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/example_id2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/example_id2.JPG -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/example_id3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/example_id3.JPG -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/example_id4.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/example_id4.JPG -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/image/example_image_easy.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/SelectiveSearch/image/example_image_easy.JPG -------------------------------------------------------------------------------- /Signal_Processing/SelectiveSearch/slective_search.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | 3 | import matplotlib.pyplot as plt 4 | import skimage 5 | import os 6 | import numpy as np 7 | import seaborn as sns 8 | import pandas as pd 9 | import scipy.misc 10 | import skimage.segmentation 11 | import skimage.feature 12 | from copy import copy 13 | import cv2 14 | 15 | def image_seg(img_8bit, scale = 1.0, sigma = 0.8, min_size = 50): 16 | """ 17 | Generate image segmentations and mask that to original image 18 | """ 19 | 20 | img_float = skimage.util.img_as_float(img_8bit) 21 | img_mask = skimage.segmentation.felzenszwalb(img_8bit, 22 | scale = scale, 23 | sigma = sigma, 24 | min_size = min_size) 25 | img = np.dstack([img_8bit, img_mask]) # the img[:, :, 3] is the segmentation mask 26 | 27 | return(img) 28 | 29 | def extract_region(img): 30 | """ 31 | For each segmented region, extract the smallest rectangle regions covering the smallest region. 32 | """ 33 | img_segment = img[:, :, 3] 34 | region = {} 35 | 36 | for y, i in enumerate(img_segment): 37 | for x, j in enumerate(i): 38 | 39 | if j not in region: 40 | region[j] = {"up_left_x" : np.Inf, 41 | "up_left_y" : np.Inf, 42 | "down_right_x" : 0, 43 | "down_right_y" : 0, 44 | "region" : j} 45 | 46 | if region[j]["up_left_x"] > x: 47 | region[j]["up_left_x"] = x 48 | if region[j]["up_left_y"] > y: 49 | region[j]["up_left_y"] = y 50 | if region[j]["down_right_x"] < x: 51 | region[j]["down_right_x"] = x 52 | if region[j]["down_right_y"] < y: 53 | region[j]["down_right_y"] = y 54 | 55 | copied_region_dict = copy(region) 56 | 57 | for key in region.keys(): 58 | if (region[key]["down_right_x"] == region[key]["up_left_x"] or 59 | region[key]["down_right_y"] == region[key]["up_left_y"]): 60 | del copied_region_dict[key] 61 | 62 | return copied_region_dict 63 | 64 | def plt_rectangle(plt, label, x1, y1, x2, y2, color = "yellow", alpha = 0.5): 65 | linewidth = 3 66 | if type(label) == list: 67 | linewidth = len(label) * 3 + 2 68 | label = "" 69 | 70 | plt.text(x1, y1, label, fontsize = 20, backgroundcolor = color, alpha = alpha) 71 | plt.plot([x1, x1], [y1, y2], linewidth = linewidth, color = color, alpha = alpha) 72 | plt.plot([x2, x2], [y1, y2], linewidth = linewidth, color = color, alpha = alpha) 73 | plt.plot([x1, x2], [y1, y1], linewidth = linewidth, color = color, alpha = alpha) 74 | plt.plot([x1, x2], [y2, y2], linewidth = linewidth, color = color, alpha = alpha) 75 | 76 | def calc_texture_gradient(img): 77 | """ 78 | Calculate texture gradient. 79 | The original Selective Search algo used Gaussian Derivative for 8 orientation. 80 | Here, we use LBP. 81 | """ 82 | ret = np.zeros(img.shape[:3]) 83 | for c in (0, 1, 2): 84 | ret[:, :, c] = skimage.feature.local_binary_pattern(img[:, :, c], 8, 1.0) 85 | 86 | return ret 87 | 88 | def to_hsv(img): 89 | """ 90 | IMG from RGB to HSV. (Hue, Saturation, Value) 91 | """ 92 | hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) 93 | return hsv 94 | 95 | def generate_hist(img, minhist = 0, maxhist = 1): 96 | """ 97 | calculate colour histogram for each region 98 | 99 | the size of output histogram will be BINS * COLOUR_CHANNELS(3) 100 | 101 | number of bins is 25 as same as [uijlings_ijcv2013_draft.pdf] 102 | 103 | extract HSV 104 | 105 | len(hist) = BINS * 3 106 | hist[:BINS] = [0, 10, 20, 0,...,0] meaning that 107 | there are 10 pixels that have values between (maxhist - minhist)/BINS*1 and (maxhist - minhist)/BINS*2 108 | there are 20 pixels that have values between (maxhist - minhist)/BINS*2 and (maxhist - minhist)/BINS*3 109 | 110 | """ 111 | 112 | BINS = 25 # length of unit hist 113 | hist = np.array([]) 114 | for channel in range(3): 115 | c = img[:, :, channel] 116 | # hist will return back a tuple (histogram, bin_edges) 117 | # e.g. (array([2037, 2002, 2016, 2041, 1972, 2023, 2022, 1994, 2010, 2047, 2073, 118 | # 1933, 2088, 1976, 2059, 1986, 1980, 2021, 2028, 1990, 1984, 1914, 119 | # 1936, 2077, 1967]), 120 | # array([0. , 0.04, 0.08, 0.12, 0.16, 0.2 , 0.24, 0.28, 0.32, 0.36, 0.4 , 121 | # 0.44, 0.48, 0.52, 0.56, 0.6 , 0.64, 0.68, 0.72, 0.76, 0.8 , 0.84, 122 | # 0.88, 0.92, 0.96, 1. ], dtype=float32)) 123 | hist = np.concatenate([hist] + [np.histogram(c, BINS, (minhist, maxhist))[0]]) 124 | 125 | hist = hist / len(img) # normalize 126 | return hist 127 | 128 | def augmented_regions_with_histogram_info(texture_grad, img, region_dict: dict, hsv, tex_trad): 129 | for k, v in list(region_dict.items()): 130 | masked_pixels = hsv[img[:, :, 3] == k] 131 | region_dict[k]["size"] = len(masked_pixels / 4) # 4 channels 132 | region_dict[k]["hist_channel"] = generate_hist(masked_pixels, minhist = 0, maxhist = 1) 133 | region_dict[k]["hist_texture"] = generate_hist(texture_grad[img[:, :, 3] == k], minhist = 134 | 0, maxhist = 2 ** 8 - 1) 135 | 136 | return region_dict 137 | 138 | def extract_neighbours(regions): 139 | def intersect(a, b) -> bool: 140 | """ 141 | Determine whether there are intersection between two windows 142 | """ 143 | if (a["up_left_x"] < b["up_left_x"] < a["down_right_x"] and a["up_left_y"] < b[ 144 | "up_left_y"] < a["down_right_y"]) or \ 145 | (a["up_left_x"] < b["down_right_x"] < a["down_right_x"] and a["up_left_y"] < b[ 146 | "up_left_y"] < a["down_right_y"]) or \ 147 | (a["up_left_x"] < b["down_right_x"] < a["down_right_x"] and a["up_left_y"] < b[ 148 | "down_right_y"] < a["down_right_y"]) or \ 149 | (a["up_left_x"] < b["up_left_x"] < a["down_right_x"] and a["up_left_y"] < b[ 150 | "down_right_y"] < a["down_right_y"]): 151 | return True 152 | return False 153 | 154 | region_dict_list = list(regions.items()) # [("": ), ("": ), ("": ), ...] 155 | neighbors = [] 156 | 157 | for current, a in enumerate(region_dict_list[:-1]): 158 | for b in region_dict_list[current + 1:]: 159 | if intersect(a[1], b[1]): 160 | neighbors.append((a, b)) 161 | 162 | return neighbors 163 | 164 | 165 | if __name__ == '__main__': 166 | img = cv2.imread(os.path.join("image", "example_id1.JPG"), cv2.IMREAD_COLOR) 167 | 168 | segmented_img = image_seg(img) 169 | R = extract_region(segmented_img) 170 | 171 | figsize = (20, 20) 172 | plt.figure(figsize = figsize) 173 | plt.imshow(img[:, :, :3]) 174 | for item, color in zip(R.values(), sns.xkcd_rgb.values()): 175 | x1 = item["up_left_x"] 176 | y1 = item["up_left_y"] 177 | x2 = item["down_right_x"] 178 | y2 = item["down_right_y"] 179 | label = item["region"] 180 | plt_rectangle(plt, label, x1, y1, x2, y2, color = color) 181 | plt.show() 182 | 183 | # plt.figure(figsize = figsize) 184 | # plt.imshow(img[:, :, 3]) 185 | # for item, color in zip(R.values(), sns.xkcd_rgb.values()): 186 | # x1 = item["min_x"] 187 | # y1 = item["min_y"] 188 | # x2 = item["max_x"] 189 | # y2 = item["max_y"] 190 | # label = item["labels"][0] 191 | # plt_rectangle(plt, label, x1, y1, x2, y2, color = color) 192 | # plt.show() 193 | 194 | 195 | # np.random.seed(4) 196 | # list_path = os.listdir("./image") 197 | # total_num = len(list_path) 198 | # rand_img_path = np.random.choice(list_path, 1) 199 | # img_8bit = cv2.imread(os.path.join("image", rand_img_path[0]), cv2.IMREAD_COLOR) 200 | # 201 | # plt.imshow(to_hsv(img_8bit)) 202 | # plt.show() 203 | 204 | # img = img_8bit[:, :, :3] 205 | # img = calc_texture_gradient(img) 206 | # plt.imshow(img) 207 | # plt.show() 208 | 209 | # for img in rand_img_path: 210 | # img_8bit = cv2.imread(os.path.join("image", img), cv2.IMREAD_COLOR) 211 | # seged_img = image_seg(img_8bit, *Config) 212 | # 213 | # fig = plt.figure(figsize = (15, 30)) 214 | # 215 | # ax = fig.add_subplot(1, 2, 1) 216 | # ax.imshow(img_8bit) 217 | # ax.set_title("original image") 218 | # ax = fig.add_subplot(1, 2, 2) 219 | # ax.imshow(seged_img[:, :, 3]) # the segmentation output 220 | # ax.set_title("skimage.segmentation.felzenszwalb, N unique region = {}".format( 221 | # len(np.unique(seged_img[:, :, 3])))) 222 | # 223 | # plt.show() 224 | 225 | # Region Extraction 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/TimeSeriesDenoising/.DS_Store -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/denoising_codeChallenge.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/TimeSeriesDenoising/denoising_codeChallenge.mat -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/emg4TKEO.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/TimeSeriesDenoising/emg4TKEO.mat -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/eyedat.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/TimeSeriesDenoising/eyedat.mat -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/read_data.py: -------------------------------------------------------------------------------- 1 | # 导入所需的库 2 | import scipy.io as sio 3 | 4 | # 使用loadmat函数读取.mat文件 5 | data = sio.loadmat('Signal_Processing/TimeSeriesDenoising/templateProjection.mat') 6 | 7 | -------------------------------------------------------------------------------- /Signal_Processing/TimeSeriesDenoising/templateProjection.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/Signal_Processing/TimeSeriesDenoising/templateProjection.mat -------------------------------------------------------------------------------- /__pycache__/data_setup.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/data_setup.cpython-310.pyc -------------------------------------------------------------------------------- /__pycache__/data_setup.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/data_setup.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/helper_functions.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/helper_functions.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/helper_functions.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/helper_functions.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/module.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/module.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/utils.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/utils.cpython-310.pyc -------------------------------------------------------------------------------- /__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeiranLi0930/TorchProject/d376d4f8a78c4ca45315964ab89ab003d3b81378/__pycache__/utils.cpython-38.pyc --------------------------------------------------------------------------------