├── LICENSE ├── README.md ├── activation ├── sinActivation.m ├── smoothRelU.m └── tanhActivation.m ├── classification ├── classObjFun.m ├── examples │ ├── EClass_Ellipses.m │ ├── EClass_Peaks.m │ ├── EClass_motivateEntropy.m │ ├── EClass_unsupervised.m │ ├── EELM_MNIST.m │ └── EELM_Peaks.m ├── logRegression.m └── softMax.m ├── conv ├── EConv_Conv1DFFT.m ├── conv1D.m ├── conv2D.m ├── convCoupled2D.m ├── convFFT.m ├── convMCN.m └── examples │ ├── EConv_BatchNorm.m │ ├── EConv_CoarseToFine.m │ ├── EConv_CoarseToFineGalerkin.m │ ├── EConv_ConvFFT2D.m │ ├── EConv_InstanceNorm.m │ └── EConv_deriveConvFFT.m ├── data ├── loadMNISTImages.m ├── loadMNISTLabels.m ├── setupCIFAR10.m ├── setupEllipses.m ├── setupMNIST.m └── setupPeaks.m ├── notes └── E_polyfit.m ├── optimization ├── cgls.m ├── newtoncg.m ├── sgd.m └── steepestDescent.m ├── regularization ├── genTikhonov.m └── getLaplacian.m ├── resnet ├── ResNetForward.m ├── ResNetObjFun.m ├── ResNetVarProObjFun.m ├── dResNetMatVec.m ├── dResNetMatVecT.m ├── examples │ ├── EResNet_Forward.m │ ├── EResNet_PeaksNewtonCG.m │ ├── EResNet_PeaksSGD.m │ ├── EResNet_PeaksVarPro.m │ ├── EResNet_Stability.m │ ├── EResNet_TestDerivative.m │ ├── EResNet_TestObjective.m │ └── EReseNet_vs_NeuralNet.m └── vec2cellResNet.m ├── singleLayer ├── examples │ ├── ESingleLayer_PeaksNewtonCG.m │ ├── ESingleLayer_PeaksSGD.m │ ├── ESingleLayer_PeaksVarPro.m │ └── ESingleLayer_PlotObjective.m ├── singleConvLayer.m ├── singleLayer.m ├── singleLayerAdvObjFun.m ├── singleLayerNNObjFun.m └── singleLayerNNVarProObjFun.m ├── startupNumDLToolbox.m ├── test ├── Rosenbrock.m ├── quadObjFun.m ├── testGenTikhonov.m ├── testLogRegression.m ├── testSingleLayer.m ├── testSingleLayerNNObjFun.m └── testSoftMax.m ├── utils ├── LinearOperator.m ├── cell2vec.m ├── opEye.m ├── opKron.m ├── opZero.m ├── vec.m └── vec2cell.m └── viewers └── montageArray.m /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NumDL-MATLAB 2 | 3 | These MATLAB codes can be used to reproduce and extend the examples in the [Numerical Methods for Deep Learning](https://github.com/IPAIopen/NumDL-CourseNotes) class. 4 | 5 | These materials was first developed by [Lars Ruthotto](http://www.mathcs.emory.edu/~lruthot/) at [Emory University](http://www.emory.edu) and [Eldad Haber](https://sites.google.com/site/ehaberubc/home) at [University of British Columbia](https://www.ubc.ca/) in the Spring and Summer of 2018. 6 | 7 | ## Scope 8 | 9 | The MATLAB files here aim at implementing of neural networks and numerical methods for their training in the simplest possible way. This is critical here, in order to involve students and researchers from a variety of backgrounds. It is more important to us than speed in this case. In fact, many functions here can be optimized for runtime but often at the cost of less readability. 10 | 11 | ## Acknowledgements 12 | Development of this material is in part supported by the National Science Foundation under Grant Numbers 1522599 and 1751636. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation. -------------------------------------------------------------------------------- /activation/sinActivation.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [A,dA] = sinActivation(Y,varargin) 8 | % 9 | % activation function A = sin(Y) 10 | % 11 | % Input: 12 | % 13 | % Y - array of features 14 | % 15 | % Optional Input: 16 | % 17 | % doDerivative - flag for computing derivative, set via varargin 18 | % Ex: sinActivation(Y,'doDerivative',0); 19 | % 20 | % Output: 21 | % 22 | % A - activation 23 | % dA - derivatives 24 | 25 | function [A,dA] = sinActivation(Y,varargin) 26 | 27 | 28 | if nargin==0 29 | runMinimalExample; 30 | return 31 | end 32 | 33 | doDerivative = nargout==2; 34 | for k=1:2:length(varargin) % overwrites default parameter 35 | eval([varargin{k},'=varargin{',int2str(k+1),'};']); 36 | end; 37 | 38 | 39 | dA = []; 40 | 41 | A = sin(Y); 42 | 43 | if doDerivative 44 | dA = cos(Y); 45 | end 46 | 47 | 48 | 49 | function runMinimalExample 50 | Y = linspace(-3,3,101); 51 | [A,dA] = feval(mfilename,Y); 52 | 53 | fig = figure(100);clf; 54 | fig.Name = mfilename; 55 | plot(Y,A,'linewidth',3); 56 | hold on; 57 | plot(Y,dA,'linewidth',3); 58 | xlabel('y') 59 | legend('sin(y)','cos(y)') -------------------------------------------------------------------------------- /activation/smoothRelU.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [A,dA] = smoothReluActivation(Y,varargin) 8 | % 9 | % smoothed relu activation function A = smoothReluActivation(Y). The idea 10 | % is to use a quadratic model close to the origin to ensure 11 | % differentiability: 12 | % 13 | % | y, if y>eta 14 | % sigma(y) = | 0, if y0; 67 | hvalid = Svalid>0; 68 | 69 | trainErr = 100*nnz(abs(CTrain-htrain))/2/nnz(CTrain); 70 | valErr = 100*nnz(abs(CValid-hvalid))/2/nnz(CValid); 71 | %% 72 | x = linspace(min(Y(1,:)),max(Y(1,:)),201); 73 | y = linspace(min(Y(2,:)),max(Y(2,:)),101); 74 | [Xg,Yg] = ndgrid(x,y); 75 | S = WOpt * padarray([vec(Xg)'; vec(Yg)'],[1,0],1,'post'); 76 | posInd = (S>0); 77 | negInd = (S <= 0); 78 | P = 0*S; 79 | P(posInd) = 1./(1+exp(-S(posInd))); 80 | P(negInd) = exp(S(negInd))./(1+exp(S(negInd))); 81 | Cpred = P > 0.5; 82 | img = reshape(Cpred,size(Xg)); 83 | %% 84 | figure(2);clf; 85 | ih = imagesc(x,y,img') 86 | ih.AlphaData = .5 87 | colormap([col2;col1]); 88 | colorbar 89 | hold on; 90 | p1 = plot(YTrain(1,CTrain==1),YTrain(2,CTrain==1),'.','MarkerSize',10); 91 | p1.Color=col1; 92 | % plot(YTrain(1,Cpred==1),YTrain(2,Cpred==1),'o','MarkerSize',10); 93 | 94 | p2 = plot(YTrain(1,CTrain==0),YTrain(2,CTrain==0),'.','MarkerSize',10); 95 | p2.Color=col2; 96 | axis equal tight 97 | title(sprintf('train error %1.2f%% val error %1.2f%%',trainErr,valErr)); 98 | set(gca,'FontSize',20) 99 | 100 | 101 | -------------------------------------------------------------------------------- /classification/examples/EClass_Peaks.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Multinomial regression for the peaks example. Here we see that a nonlinear 8 | % transformation of the feature space is required. 9 | % 10 | close all; clear all; clc; 11 | 12 | %% get peaks data 13 | np = 8000; % num of points sampled 14 | nc = 5; % num of classes 15 | ns = 256; % length of grid 16 | 17 | [Y, C] = setupPeaks(np, nc, ns); 18 | 19 | numTrain = size(Y, 2)*0.80; 20 | idx = randperm(numTrain); 21 | idxTrain = idx(1:numTrain); 22 | idxValid = idx(numTrain+1:end); 23 | 24 | YTrain = Y(:,idxTrain); 25 | CTrain = C(:,idxTrain); 26 | 27 | YValid = Y(:,idxValid); 28 | CValid = C(:,idxValid); 29 | 30 | [YTest, CTest] = setupPeaks(2000, nc, ns); 31 | 32 | nf = size(Y,1); 33 | nc = size(C,1); 34 | %% optimize 35 | % m = 640/20; 36 | W0 = randn(nc,3); 37 | 38 | paramRegW = struct('L',speye(numel(W0)),'lambda',1e-3); 39 | fctn = @(x,varargin) classObjFun(x,YTrain,CTrain,paramRegW); 40 | param = struct('maxIter',30,'maxStep',1,'tolCG',1e-3,'maxIterCG',100); 41 | WOpt = newtoncg(fctn,W0(:),param); 42 | %% 43 | WOpt = reshape(WOpt,nc,[]); 44 | Strain = WOpt*padarray(YTrain,[1,0],1,'post'); 45 | S = WOpt*padarray(YTest,[1,0],1,'post'); 46 | htrain = exp(Strain)./sum(exp(Strain),1); 47 | h = exp(S)./sum(exp(S),1); 48 | 49 | % Find the largesr entry at each row 50 | [~,ind] = max(h,[],1); 51 | Cv = zeros(size(CTest)); 52 | Ind = sub2ind(size(Cv),ind,1:size(Cv,2)); 53 | Cv(Ind) = 1; 54 | [~,ind] = max(htrain,[],1); 55 | Cpred = zeros(size(CTrain)); 56 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 57 | Cpred(Ind) = 1; 58 | 5 59 | trainErr = 100*nnz(abs(CTrain-Cpred))/2/nnz(CTrain); 60 | valErr = 100*nnz(abs(Cv-CTest))/2/nnz(Cv); 61 | %% 62 | x = linspace(-3,3,201); 63 | [Xg,Yg] = ndgrid(x); 64 | Z = WOpt * padarray([vec(Xg)'; vec(Yg)'],[1,0],1,'post'); 65 | h = exp(Z)./sum(exp(Z),1); 66 | 67 | [~,ind] = max(h,[],1); 68 | Cpred = zeros(5,numel(Xg)); 69 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 70 | Cpred(Ind) = 1; 71 | img = reshape((1:5)*Cpred,size(Xg)); 72 | %% 73 | figure(1); 74 | imagesc(x,x,img') 75 | title(sprintf('train %1.2f%% val %1.2f%%',trainErr,valErr)); 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /classification/examples/EClass_motivateEntropy.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % This basic example illustrates the convexity of the entropy function 8 | % 9 | nex = 100; 10 | nf = 2; 11 | 12 | Y = randn(nex,nf); 13 | C1 = sum(Y,2)>0; 14 | C = [C1 1-C1]; 15 | 16 | [W1,W2] = meshgrid(linspace(-7,7,201)); 17 | 18 | F = zeros(101,101); 19 | F2 = F; 20 | for i=1:size(W1,1) 21 | for j=1:size(W1,1) 22 | Hp = 1./(1+exp(Y*[W1(i,j);W2(i,j)])); 23 | Hp= [Hp 1-Hp]; 24 | Cp = Hp./(sum(Hp,2)); 25 | F(i,j) = 0.5*norm(Cp-C)^2/nex; 26 | 27 | F2(i,j) = -sum(sum(C.*log(Cp)))/nex; 28 | end 29 | end 30 | 31 | fig = figure(1);clf; 32 | fig.Name = 'Frobenius' 33 | % subplot(1,2,1) 34 | contour(W1,W2,F,50,'linewidth',2) 35 | % hold on; 36 | % [mx,idx] = min(F(:)); 37 | % plot(W1(idx),W2(idx),'.r','MarkerSize',60) 38 | title('Frobenius Norm') 39 | % colorbar 40 | axis equal tight 41 | 42 | fig = figure(2);clf; 43 | fig.Name = 'CrossEntropy' 44 | % subplot(1,2,2) 45 | contour(W1,W2,F2,50,'linewidth',2) 46 | % hold on; 47 | % [mx,idx] = min(F2(:)); 48 | % plot(W1(idx),W2(idx),'.r','MarkerSize',60) 49 | title('cross entropy') 50 | axis equal tight 51 | % colorbar; 52 | 53 | figDir = '/Users/lruthot/Dropbox/Projects/NumDL-CourseNotes/images/' 54 | 55 | for k=1:2 56 | fig = figure(k) 57 | title([]) 58 | axis equal tight off 59 | set(gca,'FontSize',20) 60 | printFigure(gcf,fullfile(figDir,['Class_' fig.Name '.png'])) 61 | end 62 | 63 | -------------------------------------------------------------------------------- /classification/examples/EClass_unsupervised.m: -------------------------------------------------------------------------------- 1 | close all; clear all; 2 | 3 | r = [0 2 4]; 4 | 5 | fig1 = figure(1); clf; 6 | fig1.Name = 'data'; 7 | hold on; 8 | 9 | fig3 = figure(3); clf; 10 | fig3.Name = 'semi'; 11 | hold on; 12 | 13 | fig2 = figure(2); clf; 14 | fig2.Name = 'labeled' 15 | hold on; 16 | for k=1:numel(r) 17 | alpha = rand(1,300); 18 | rad = r(k)+rand(1,300); 19 | X = rad.*[cos(2*pi*alpha);sin(2*pi*alpha)]; 20 | figure(1); 21 | plot(X(1,:),X(2,:),'.k','MarkerSize',10) 22 | 23 | 24 | figure(2) 25 | plot(X(1,:),X(2,:),'.','MarkerSize',10) 26 | 27 | figure(3); 28 | p=plot(X(1,:),X(2,:),'.k','MarkerSize',10) 29 | plot(X(1,1:3),X(2,1:3),'.','MarkerSize',50) 30 | 31 | end 32 | 33 | figDir = '/Users/lruthot/Dropbox/Projects/NumDL-CourseNotes/images/' 34 | 35 | for k=1:3 36 | fig = figure(k) 37 | axis equal tight off 38 | set(gca,'FontSize',20) 39 | printFigure(gcf,fullfile(figDir,['unsupervised_' fig.Name '.png'])) 40 | end 41 | -------------------------------------------------------------------------------- /classification/examples/EELM_MNIST.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Example: Extreme learning for MNIST 8 | % 9 | close all; clear all; clc; 10 | 11 | %% 12 | [Y,C,Yv,Cv] = setupMNIST(50000,10000); 13 | %% optimize 14 | m = 1530; 15 | nf = size(Y,1); 16 | nc = size(C,1); 17 | 18 | KOpt = randn(m,nf)/sqrt(nf*m); 19 | bOpt = randn(); 20 | WOpt = randn(nc,m+1)/sqrt(nc*m); 21 | 22 | W0 = WOpt; 23 | Z = singleLayer(KOpt,bOpt,Y); 24 | paramReg = struct('L',speye(numel(W0)),'lambda',1e-8); 25 | fctn = @(x,varargin) classObjFun(x,Z,C,paramReg); 26 | param = struct('maxIter',20,'maxStep',1,'maxIterCG',30,'tolCG',1e-2); 27 | WOpt = newtoncg(fctn,WOpt(:),param); 28 | %% 29 | WOpt = reshape(WOpt,nc,m+1); 30 | Strain = WOpt*padarray(Z,[1,0],1,'post'); 31 | S = WOpt*padarray(singleLayer(KOpt,bOpt,Yv),[1,0],1,'post'); 32 | % the probability function 33 | htrain = exp(Strain)./sum(exp(Strain),1); 34 | h = exp(S)./sum(exp(S),1); 35 | 36 | % Find the largesr entry at each row 37 | [~,ind] = max(h,[],1); 38 | Cvpred = zeros(size(Cv)); 39 | Ind = sub2ind(size(Cv),ind,1:size(Cv,2)); 40 | Cvpred(Ind) = 1; 41 | [~,ind] = max(htrain,[],1); 42 | Cpred = zeros(size(C)); 43 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 44 | Cpred(Ind) = 1; 45 | 46 | trainErr = 100*nnz(abs(C-Cpred))/2/nnz(C); 47 | valErr = 100*nnz(abs(Cv-Cvpred))/2/nnz(Cv); 48 | fprintf('Testing Error %3.2f%%\n',trainErr); 49 | fprintf('Validation Error %3.2f%%\n',valErr); -------------------------------------------------------------------------------- /classification/examples/EELM_Peaks.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Example: Extreme learning for Peaks example 8 | % 9 | close all; clear all; clc; 10 | rng(42) 11 | %% get peaks data 12 | np = 8000; % num of points sampled 13 | nc = 5; % num of classes 14 | ns = 256; % length of grid 15 | 16 | [Y, C] = setupPeaks(np, nc, ns); 17 | 18 | numTrain = size(Y, 2)*0.80; 19 | idx = randperm(size(Y,2)); 20 | idxTrain = idx(1:numTrain); 21 | idxValid = idx(numTrain+1:end); 22 | 23 | YTrain = Y(:,idxTrain); 24 | CTrain = C(:,idxTrain); 25 | 26 | YValid = Y(:,idxValid); 27 | CValid = C(:,idxValid); 28 | 29 | [YTest, CTest] = setupPeaks(2000, nc, ns); 30 | 31 | nf = size(Y,1); 32 | nc = size(C,1); 33 | %% optimize 34 | % m = 640/20; 35 | m = 200; 36 | KOpt = randn(m,nf); 37 | bOpt = randn(1); 38 | W0 = randn(nc,m+1); 39 | 40 | %% compare nonlinearities 41 | figure(1); clf; 42 | subplot(2,2,1); 43 | Z1 = sin(KOpt*Y+bOpt); 44 | Z2 = tanh(KOpt*Y+bOpt); 45 | Z3 = max(0,KOpt*Y+bOpt); 46 | semilogy(svd(Z1),'linewidth',3); 47 | hold on; 48 | semilogy(svd(Z2),'linewidth',3); 49 | semilogy(svd(Z3),'linewidth',3); 50 | legend('sin','tanh','relu'); 51 | title('singular values') 52 | set(gca,'FontSize',20) 53 | %% optimize 54 | relu = @(x) max(x,0); 55 | acts = {@sin,@tanh,relu}; 56 | 57 | for k=1:numel(acts) 58 | act = acts{k}; 59 | Z = act(KOpt*Y+bOpt); 60 | paramRegW = struct('L',speye(numel(W0)),'lambda',1e-3); 61 | fctn = @(x,varargin) classObjFun(x,Z,C,paramRegW); 62 | param = struct('maxIter',30,'maxStep',1,'tolCG',1e-3,'maxIterCG',100); 63 | WOpt = newtoncg(fctn,W0(:),param); 64 | %% 65 | WOpt = reshape(WOpt,nc,m+1); 66 | Strain = WOpt*padarray(Z,[1,0],1,'post'); 67 | S = WOpt*padarray(act(KOpt*YTest+bOpt),[1,0],1,'post'); 68 | htrain = exp(Strain)./sum(exp(Strain),1); 69 | h = exp(S)./sum(exp(S),1); 70 | 71 | % Find the largesr entry at each row 72 | [~,ind] = max(h,[],1); 73 | Cv = zeros(size(CTest)); 74 | Ind = sub2ind(size(Cv),ind,1:size(Cv,2)); 75 | Cv(Ind) = 1; 76 | [~,ind] = max(htrain,[],1); 77 | Cpred = zeros(size(C)); 78 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 79 | Cpred(Ind) = 1; 80 | 81 | trainErr = 100*nnz(abs(C-Cpred))/2/nnz(C); 82 | valErr = 100*nnz(abs(Cv-CTest))/2/nnz(Cv); 83 | %% 84 | x = linspace(-3,3,201); 85 | [Xg,Yg] = ndgrid(x); 86 | Z = WOpt * padarray(act(KOpt*[vec(Xg)'; vec(Yg)']+bOpt),[1,0],1,'post'); 87 | h = exp(Z)./sum(exp(Z),1); 88 | 89 | [~,ind] = max(h,[],1); 90 | Cpred = zeros(5,numel(Xg)); 91 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 92 | Cpred(Ind) = 1; 93 | img = reshape((1:5)*Cpred,size(Xg)); 94 | %% 95 | figure(1); 96 | subplot(2,2,1+k) 97 | imagesc(x,x,img') 98 | title(sprintf('%s - train %1.2f%% val %1.2f%%',func2str(act),trainErr,valErr)); 99 | end 100 | %% 101 | for k=1:4 102 | subplot(2,2,k) 103 | set(gca,'FontSize',20) 104 | end 105 | 106 | 107 | -------------------------------------------------------------------------------- /classification/logRegression.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[E,dEW,d2EW,dEY,d2EY] = logRegression(W,Y,C) 8 | % 9 | % Evaluates cross-entropy loss function for logistic regression 10 | % 11 | % Inputs: 12 | % 13 | % W - current weights of classifier 14 | % Y - features 15 | % C - labels 16 | % 17 | % Outputs: 18 | % 19 | % E - cross-entropy 20 | % dEW - gradient w.r.t. W 21 | % d2W - function handle for matvec with Hessian w.r.t. W 22 | % dEY - gradient w.r.t. Y 23 | % d2Y - function handle for matvec with Hessian w.r.t. Y 24 | 25 | function[E,dEW,d2EW,dEY,d2EY] = logRegression(W,Y,C) 26 | 27 | if nargin == 0 28 | runMinExample; 29 | return 30 | end 31 | if size(C,1) ~= 1 32 | error('logRegression can only handle binary classification.') 33 | end 34 | W = reshape(W,1,[]); addBias = false; 35 | if size(W,2)==size(Y,1)+1 36 | addBias = true; 37 | Y = [Y; ones(1,size(Y,2))]; 38 | end 39 | n = size(Y,2); 40 | nc = size(C,1); 41 | 42 | % the linear model 43 | S = W*Y; 44 | 45 | 46 | 47 | % The cross entropy 48 | posInd = (S>0); 49 | negInd = (S<=0); 50 | E = -sum(C(negInd).*S(negInd) - log(1+exp(S(negInd))) ) - ... 51 | sum(C(posInd).*S(posInd) - log(exp(-S(posInd))+1) - S(posInd)); 52 | E = E/n; 53 | 54 | if nargout > 1 55 | dES = (C- 1./(1+exp(-S))); 56 | dEW = -dES*(Y'/n); 57 | dEW = dEW(:); 58 | end 59 | 60 | if nargout>2 61 | matW = @(v) reshape(v,nc,[]); % reshape vector into same size of W 62 | vec = @(V) V(:); 63 | 64 | d2E = @(U) U./(2*cosh(S/2)).^2; 65 | d2EW = @(v) vec(d2E(matW(v)*Y)*Y')/n + 1e-5*v; 66 | end 67 | 68 | if addBias 69 | W = W(:,1:end-1); 70 | end 71 | if nargout > 3 72 | dEY = -(W'*dES)/n; 73 | dEY = dEY(:); 74 | end 75 | 76 | if nargout>4 77 | matY = @(v) reshape(v,[],n); 78 | 79 | d2EY = @(v) vec(W'*d2E(W*matY(v)))/n + 1e-5*vec(v); 80 | end 81 | 82 | end 83 | 84 | function runMinExample 85 | 86 | vec = @(x) x(:); 87 | nex = 100; 88 | Y = randn(2,nex); 89 | C = Y(1,:) > 0; 90 | b = 0; 91 | W = [1;1]; 92 | E = logRegression(W,Y,C); 93 | [E,dE,d2E] = logRegression(W,Y,C); 94 | 95 | h = 1; 96 | err = zeros(3,20); 97 | dW = randn(size(W)); 98 | for i=1:size(err,2) 99 | E1 = logRegression(W+h*dW,Y,C); 100 | t = abs(E1-E); 101 | t1 = abs(E1-E-h*dE(:)'*dW(:)); 102 | t2 = abs(E1-E-h*dE(:)'*dW(:) - h^2/2 * dW(:)'*vec(d2E(dW(:)))); 103 | 104 | fprintf('%3.2e %3.2e %3.2e\n',t,t1,t2) 105 | 106 | err(i,1) = abs(E1-E); 107 | err(i,2) = abs(E1-E-h*dE(:)'*dW(:)); 108 | err(i,3) = t2; 109 | h = h/2; 110 | end 111 | end -------------------------------------------------------------------------------- /classification/softMax.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[E,dEW,d2EW,dEY,d2EY] = softMax(W,Y,C) 8 | % 9 | % Evaluates cross-entropy loss function for multinomial classification 10 | % 11 | % Inputs: 12 | % 13 | % W - current weights of classifier 14 | % Y - features 15 | % C - labels 16 | % 17 | % Outputs: 18 | % 19 | % E - cross-entropy 20 | % dEW - gradient w.r.t. W 21 | % d2W - function handle for matvec with Hessian w.r.t. W 22 | % dEY - gradient w.r.t. Y 23 | % d2Y - function handle for matvec with Hessian w.r.t. Y 24 | 25 | function[E,dEW,d2EW,dEY,d2EY] = softMax(W,Y,C) 26 | 27 | 28 | if nargin == 0 29 | runMinExample; 30 | return 31 | end 32 | W = reshape(W,size(C,1),[]); addBias = false; 33 | if size(W,2)==size(Y,1)+1 34 | addBias = true; 35 | Y = [Y; ones(1,size(Y,2))]; 36 | end 37 | n = size(Y,2); 38 | nc = size(C,1); 39 | 40 | % the linear model 41 | S = W*Y; 42 | 43 | % make sure that the largest number in every row is 0 44 | s = max(S,[],1); 45 | S = S-s; 46 | 47 | 48 | % The cross entropy 49 | expS = exp(S); 50 | sS = sum(expS,1); 51 | 52 | E = -C(:)'*S(:) + sum(log(sS)); 53 | E = E/n; 54 | 55 | if nargout > 1 56 | dES = -C + expS .* 1./sS; 57 | dEW = dES*(Y'/n); 58 | dEW = dEW(:); 59 | end 60 | 61 | if nargout>2 62 | matW = @(v) reshape(v,nc,[]); % reshape vector into same size of W 63 | vec = @(V) V(:); 64 | 65 | d2E = @(U) (U.*expS)./sS - expS.*(sum(expS.*U,1)./sS.^2); 66 | d2EW = @(v) vec(d2E(matW(v)*Y)*Y')/n + 1e-5*v; 67 | end 68 | 69 | if addBias 70 | W = W(:,1:end-1); 71 | end 72 | if nargout > 3 73 | dEY = (W'*dES)/n; 74 | dEY = dEY(:); 75 | end 76 | 77 | if nargout>4 78 | matY = @(v) reshape(v,[],n); 79 | 80 | d2EY = @(v) vec(W'*d2E(W*matY(v)))/n + 1e-5*vec(v); 81 | end 82 | 83 | end 84 | 85 | function runMinExample 86 | 87 | vec = @(x) x(:); 88 | nex = 100; 89 | Y = hilb(500)*255; 90 | Y = Y(:,1:nex); 91 | C = ones(3,nex); 92 | C = C./sum(C,1); 93 | b = 0; 94 | W = hilb(501); 95 | W = W(1:3,:); 96 | E = softMax(W,Y,C); 97 | [E,dE,d2E] = softMax(W,Y,C); 98 | 99 | h = 1; 100 | rho = zeros(3,20); 101 | dW = randn(size(W)); 102 | for i=1:20 103 | E1 = softMax(W+h*dW,Y,C); 104 | t = abs(E1-E); 105 | t1 = abs(E1-E-h*dE(:)'*dW(:)); 106 | t2 = abs(E1-E-h*dE(:)'*dW(:) - h^2/2 * dW(:)'*vec(d2E(dW(:)))); 107 | 108 | fprintf('%3.2e %3.2e %3.2e\n',t,t1,t2) 109 | 110 | rho(i,1) = abs(E1-E); 111 | rho(i,2) = abs(E1-E-h*dE(:)'*dW(:)); 112 | rho(i,3) = t2; 113 | h = h/2; 114 | end 115 | end -------------------------------------------------------------------------------- /conv/EConv_Conv1DFFT.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Example for 1D convolution with FFTs 8 | 9 | close all; clear all; clc; 10 | 11 | % stencil 12 | n = 16; 13 | theta = rand(3,1); 14 | K = full(spdiags(ones(n,1)*flipud(theta)',-1:1,n,n)); 15 | K(1,end) = theta(3); 16 | K(end,1) = theta(1) 17 | 18 | %% compute eigenvalues using FFT 19 | eigK = eig(K); 20 | eigKt = fft(K(:,1)); 21 | figure(1); clf 22 | plot(real(eigK),imag(eigK),'or'); 23 | hold on; 24 | plot(real(eigKt),imag(eigKt),'.b'); 25 | xlabel('real') 26 | ylabel('imag'); 27 | set(gca,'FontSize',20); 28 | 29 | %% 30 | x = linspace(0,1,n)'; 31 | y = cos(2*pi*x); 32 | 33 | z1 = K*y; 34 | z2 = real(ifft(eigKt.*fft(y))); 35 | 36 | figure(2); clf; 37 | subplot(1,3,1) 38 | plot(x,y,'linewidth',2); 39 | subplot(1,3,2); 40 | plot(x,z1,'linewidth',2); 41 | hold on; 42 | plot(x,z2,'linewidth',2); 43 | legend('z=K*y','z=ifft(fft(y).*lam)') 44 | subplot(1,3,3); 45 | semilogy(x,abs(z1-z2),'linewidth',2); 46 | title('error') 47 | for k=1:3; subplot(1,3,k); set(gca,'FontSize',20); end; 48 | 49 | %% 50 | z1 = K'*y; 51 | z2 = real(fft(eigKt.*ifft(y))); 52 | norm(z1-z2) 53 | 54 | %% check derivatives 55 | y = randn(n,1); 56 | th0 = randn(3,1); 57 | 58 | 59 | %% code for generating first column 60 | sK = numel(theta); center = (sK-1)/2+1; 61 | Ku = zeros(16,1); Ku(1:center) = theta(center:end); 62 | Ku(end-(center-2):end) = theta(1:center-1); 63 | %% using circshift 64 | Kt = zeros(16,1); Kt(1:sK)=theta; circshift(Kt,1-center) 65 | 66 | -------------------------------------------------------------------------------- /conv/conv1D.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [KYmv,KtYmv,Jmv,Jtmv] = conv1D(nnImgf,theta,Y) 8 | % 9 | % computes 1D convolutions using FFT 10 | % 11 | % Z = K(theta)* Y, 12 | % 13 | % where size(Y)=nImg x n and size(K)= nImg x nf. 14 | % 15 | % Input: 16 | % nImg - number of grid point (i.e., number of features) 17 | % theta - stencil (assumed to be odd number of elements) 18 | % Y - features (needed only for Jacobians) 19 | % 20 | % Output 21 | % KYmv - function handle for Y -> K(theta)*Y 22 | % KtYmv - function handle for Y -> K(theta)'*Y 23 | % Jmv - function handle for v -> J(K(theta)*Y) * v 24 | % Jtmv - function handle for w -> J(K(theta)*Y)'* w 25 | 26 | function [KYmv,KtYmv,Jmv,Jtmv] = conv1D(nImg,theta,Y) 27 | 28 | if nargin==0 29 | testThisMethod 30 | return; 31 | end 32 | lam = fft(getK1(theta,nImg)); 33 | sdiag = @(v) spdiags(v(:),0,numel(v),numel(v)); 34 | KYmv = @(Y) real(ifft(sdiag(lam)*fft(Y))); 35 | KtYmv = @(Y) real(fft(sdiag(lam)*ifft(Y))); 36 | 37 | % Jacobians 38 | if nargout>2 39 | iFy = fft(Y); 40 | q = getK1(1:numel(theta),nImg); 41 | I = find(q); 42 | J = q(I); 43 | Q = sparse(I,J,ones(numel(theta),1),nImg,numel(theta)); 44 | 45 | Jmv = @(v) real(ifft(sdiag(fft(Q*v))*iFy)); 46 | Jtmv = @(w) real(Q'*fft(sum(iFy.*ifft(w),2))); 47 | end 48 | 49 | 50 | % ---- helper functions ---- 51 | function K1 = getK1(theta,m) 52 | % builds first column of convolution operator K(theta) 53 | center = (numel(theta)+1)/2; 54 | K1 = circshift([theta(:);zeros(m-numel(theta),1)],1-center); 55 | 56 | % ----- test function ----- 57 | function testThisMethod 58 | nf = 16; 59 | n = 10; 60 | theta = randn(3,1); 61 | K = full(spdiags(ones(nf,1)*flipud(theta)',-1:1,nf,nf)); 62 | K(1,end) = theta(3); 63 | K(end,1) = theta(1); 64 | Y = randn(nf,n); 65 | 66 | [KYmv,KYtmv,Jmv,Jtmv] = feval(mfilename,nf,theta,Y); 67 | 68 | T1 = K*Y; 69 | T2 = KYmv(Y); 70 | fprintf('error for K*Y: %1.2e\n',norm(T1-T2)) 71 | 72 | T1 = K'*Y; 73 | T2 = KYtmv(Y); 74 | fprintf('error for K''*Y: %1.2e\n',norm(T1-T2)) 75 | 76 | % derivative check 77 | dth = randn(size(theta)); 78 | KYmv2 = feval(mfilename,nf,theta+dth,Y); 79 | T1 = KYmv2(Y); 80 | T2 = KYmv(Y) + Jmv(dth); 81 | fprintf('error for J*v: %1.2e\n',norm(T1-T2)); 82 | 83 | % adjoint check 84 | dZ = randn(size(Y)); 85 | T1 = sum(sum(dZ.*Jmv(dth))); 86 | T2 = sum(sum(dth.*Jtmv(dZ))); 87 | fprintf('adjoint error: %1.2e\n',norm(T1-T2)); 88 | 89 | -------------------------------------------------------------------------------- /conv/conv2D.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [KYmv,KYtmv,Jmv,Jtmv] = conv2D(nImg,sTheta,theta,Y) 8 | % 9 | % computes 2D convolutions using FFT 10 | % 11 | % Input: 12 | % nImg - dimension of image data 13 | % sTheta - stencil size 14 | % theta - stencil 15 | % Y - images 16 | % 17 | % Output: 18 | % KYmv - function handle for Y -> K(theta)*Y 19 | % KtYmv - function handle for Y -> K(theta)'*Y 20 | % Jmv - function handle for v -> J(K(theta)*Y) * v 21 | % Jtmv - function handle for w -> J(K(theta)*Y)'* w 22 | function [KYmv,KYtmv,Jmv,Jtmv] = conv2D(nImg,sTheta,theta,Y) 23 | 24 | if nargin==0 25 | runMinimalExample 26 | return 27 | end 28 | 29 | rshp3D = @(Y) reshape(Y',nImg(1),nImg(2),[]); 30 | rshp2D = @(Y) reshape(Y,prod(nImg),[]); 31 | vec = @(V) V(:); 32 | 33 | lam = fft2(getK1(theta,nImg,sTheta)); 34 | KYmv = @(Y) rshp2D(real(ifft2(lam.*fft2(rshp3D(Y))))); 35 | KYtmv = @(Y) rshp2D(real(fft2(lam.*ifft2(rshp3D(Y))))); 36 | 37 | if nargout>2 38 | Fy = fft2(rshp3D(Y)); 39 | q = getK1(1:numel(theta),nImg,sTheta); 40 | I = find(q); 41 | J = q(I); 42 | Q = sparse(I,J,ones(numel(theta),1),prod(nImg),numel(theta)); 43 | 44 | Jmv = @(v) rshp2D(real(ifft2(fft2(getK1(v,nImg,sTheta)).*Fy))); 45 | Jtmv = @(w) real(Q'*vec(fft2(sum(Fy.*ifft2(rshp3D(w)),3)))); 46 | end 47 | 48 | function K1 = getK1(theta,nImg,sTheta) 49 | theta = reshape(theta,sTheta); 50 | K1 = zeros(nImg,'like',theta); 51 | K1(1:sTheta(1), 1:sTheta(2)) = theta; 52 | center = (sTheta+1)/2; 53 | K1 = circshift(K1,1-center); 54 | 55 | function runMinimalExample 56 | nImg = [16 16]; 57 | xa = linspace(0,1,nImg(1)); 58 | ya = linspace(0,1,nImg(2)); 59 | [X,Y] = ndgrid(xa,ya); 60 | theta = [-1 0 1; -1 0 1; -1 0 1]; 61 | y = X(:)+Y(:); 62 | 63 | [KYmv,KYtmv,Jmv,Jtmv] = feval(mfilename,nImg,size(theta),theta,y); 64 | 65 | T2 = KYmv(y); 66 | figure(1); clf; 67 | subplot(1,3,1); 68 | imagesc(reshape(y,nImg)); 69 | subplot(1,3,2); 70 | imagesc(reshape(T2,nImg)); 71 | 72 | 73 | T2 = KYtmv(y); 74 | subplot(1,3,3); 75 | imagesc(reshape(T2,nImg)); 76 | 77 | % derivative check 78 | dth = randn(size(theta)); 79 | KYmv2 = feval(mfilename,nImg,size(theta),theta+dth,y); 80 | T1 = KYmv2(y); 81 | T2 = KYmv(y) + Jmv(dth); 82 | fprintf('error in Jacobian: %1.2e\n',norm(T1-T2)) 83 | 84 | % adjoint check 85 | dZ = randn(size(y)); 86 | dth = randn(size(dth)); 87 | T1 = sum(sum(dZ.*Jmv(dth))); 88 | T2 = sum(sum(dth(:)'*Jtmv(dZ))); 89 | fprintf('adjoint error: %1.2e\n',norm(T1-T2)) 90 | 91 | -------------------------------------------------------------------------------- /conv/convCoupled2D.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [YKmv,YKtmv,Jmv,Jtmv] = convCoupled2D(nImg,sTheta,theta,Y) 8 | % 9 | % computes the coupled convolution of multi-channel images Y. 10 | % 11 | % 12 | % Input: 13 | % nImg - number of pixels, e.g., nImg = [16,16]; 14 | % sTheta - size of kernel, e.g., sTheta = [3,3,4,6] for 3x3 convolutions 15 | % applied to 4 input channels giving 6 output channels 16 | % theta - weights 17 | % Y - feature matrix, only needed for derivative computation 18 | % 19 | % Output: 20 | % YKmv - function handle for computing Y -> K(theta)*Y 21 | % YKtmv - function handle for computing Y -> K(theta)'*Y 22 | % Jmv - function handle for computing v -> Jac*v 23 | % Jtmv - function handle for computing w -> Jac'*w 24 | function [KYmv,KYtmv,Jmv,Jtmv] = convCoupled2D(nImg,sTheta,theta,Y) 25 | 26 | 27 | if nargin==0 28 | testThisMethod; 29 | return 30 | end 31 | 32 | KYmv = @(Y) Amv(nImg,sTheta,theta,Y); 33 | KYtmv = @(Y) Atmv(nImg,sTheta,theta,Y); 34 | if nargout>2 35 | Jmv = @(v) Amv(nImg,sTheta,v,Y); 36 | Jtmv = @(Z) JthetaTmv(nImg,sTheta,Y,Z); 37 | end 38 | 39 | 40 | function Z = Amv(nImg,sTheta,theta,Y) 41 | % compute convolution 42 | nex = size(Y,4); 43 | 44 | Z = zeros([nImg sTheta(4) nex],'like',Y); 45 | S = reshape(fft2(getK1(theta,nImg,sTheta)),[nImg sTheta(3:4)]); 46 | Yh = fft2(Y); 47 | for k=1:sTheta(4) 48 | T = S(:,:,:,k) .* Yh; 49 | Z(:,:,k,:) = sum(T,3); 50 | end 51 | Z = real(ifft2(Z)); 52 | 53 | function Y = Atmv(nImg,sTheta,theta,Z) 54 | % compute transpose of convolution 55 | 56 | nex = size(Z,4); 57 | Y = zeros([nImg sTheta(3) nex],'like',Z); 58 | S = reshape(fft2(getK1(theta,nImg,sTheta)),[nImg sTheta(3:4)]); 59 | 60 | Zh = ifft2(Z); 61 | for k=1:sTheta(3) 62 | Sk = squeeze(S(:,:,k,:)); 63 | Y(:,:,k,:) = sum(Sk.*Zh,3); 64 | end 65 | Y = real(fft2(Y)); 66 | 67 | 68 | function dtheta = JthetaTmv(nImg,sTheta,Y,Z) 69 | % compute Jac'*Z 70 | 71 | dth1 = zeros(prod(sTheta(1:3)),sTheta(4),'like',Y); 72 | Yh = permute(fft2(Y),[1 2 4 3]); 73 | Zh = ifft2(Z); 74 | 75 | % get q vector for a given row in the block matrix 76 | v = vec(1:prod(sTheta(1:3))); 77 | q = getK1(v,nImg,sTheta); 78 | 79 | I = find(q(:)); 80 | for k=1:sTheta(4) 81 | Zk = squeeze(Zh(:,:,k,:)); 82 | tt = squeeze(sum(Zk.*Yh,3)); 83 | tt = real(fft2(tt)); 84 | dth1(q(I),k) = tt(I); 85 | end 86 | dtheta = dth1(:); 87 | 88 | function K1 = getK1(theta,nImg,sTheta) 89 | % compute first row of convolution matrix 90 | theta = reshape(theta,sTheta(1),sTheta(2),[]); 91 | center = (sTheta(1:2)+1)/2; 92 | 93 | K1 = zeros([nImg size(theta,3)],'like',theta); 94 | K1(1:sTheta(1),1:sTheta(2),:) = theta; 95 | K1 = circshift(K1,1-center); 96 | 97 | function testThisMethod 98 | 99 | nImg = [16 16]; 100 | sTheta = [3 3 4 6]; 101 | n = 1; 102 | theta = ones(prod(sTheta),1); 103 | Y = randn([nImg sTheta(3) n]); 104 | 105 | 106 | [KYmv,KYtmv,Jmv,Jtmv] = feval(mfilename,nImg,sTheta,theta,Y); 107 | YK = KYmv(Y); 108 | Z = randn(size(YK),'like',YK); 109 | YKtZ = KYtmv(Z); 110 | t1 = sum(vec(YK.*Z)); 111 | t2 = sum(vec(YKtZ.*Y)); 112 | fprintf('adjoint error: %1.2e\n',norm(t1-t2)) 113 | 114 | 115 | % derivative check 116 | dth = randn(size(theta),'like',theta); 117 | Kmv2 = feval(mfilename,nImg,sTheta,theta+dth,Y); 118 | T1 = Kmv2(Y); 119 | T2 = KYmv(Y) + Jmv(dth); 120 | fprintf('error in Jacobian: %1.2e\n',norm(vec(T1-T2))) 121 | 122 | % adjoint check 123 | dZ = randn(size(T2),'like',theta); 124 | dth = randn(size(dth),'like',theta); 125 | T1 = sum(vec(dZ.*Jmv(dth))); 126 | T2 = sum(vec(dth(:)'*Jtmv(dZ))); 127 | fprintf('adjoint Jacobian error: %1.2e\n',norm(T1-T2)) 128 | 129 | -------------------------------------------------------------------------------- /conv/convFFT.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classdef convFFT 8 | % 9 | % 2D convolution using FFTs 10 | % 11 | % Transforms feature using affine linear mapping 12 | % 13 | % Y(theta,Y0) K(theta) * Y0 14 | % 15 | % where 16 | % 17 | % K - convolution matrix 18 | 19 | classdef convFFT 20 | 21 | properties 22 | nImg % image size 23 | sK % kernel size: [nxfilter,nyfilter,nInputChannels,nOutputChannels] 24 | Q % linear transformation applied to stencil elements, default Q = eye 25 | end 26 | 27 | methods 28 | function this = convFFT(nImg, sK,varargin) 29 | 30 | if nargout==0 && nargin==0 31 | this.runMinimalExample; 32 | return; 33 | end 34 | nImg = nImg(1:2); 35 | Q = opEye(prod(sK)); 36 | for k=1:2:length(varargin) % overwrites default parameter 37 | eval([ varargin{k},'=varargin{',int2str(k+1),'};']); 38 | end 39 | 40 | this.nImg = nImg; 41 | this.sK = sK; 42 | this.Q = Q; 43 | end 44 | 45 | function A = getOp(this,K) 46 | % constructs operator for current weight, K 47 | n = nFeatIn(this); 48 | m = nFeatOut(this); 49 | Af = @(Y) this.Amv(K,Y); 50 | ATf = @(Y) this.ATmv(K,Y); 51 | A = LinearOperator(m,n,Af,ATf); 52 | end 53 | 54 | 55 | function runMinimalExample(~) 56 | nImg = [16 18]; 57 | sK = [3 3,1,2]; 58 | kernel = feval(mfilename,nImg,sK,'stride',2); 59 | theta = rand(sK); 60 | theta(:,1,:) = -1; theta(:,3,:) = 1; 61 | 62 | I = rand(nImgIn(kernel)); I(4:12,4:12,:) = 2; 63 | Ik = Amv(kernel,theta,I); 64 | Ik2 = ATmv(kernel,theta,Ik); 65 | figure(1); clf; 66 | subplot(1,2,1); 67 | imagesc(I); 68 | title('input'); 69 | 70 | subplot(1,2,2); 71 | imagesc(Ik(:,:,1)); 72 | title('output'); 73 | end 74 | 75 | function [Z,tmp] = Amv(this,theta,Y) 76 | tmp = []; % no need to store any intermediates 77 | nex = size(Y,4); 78 | 79 | Z = zeros([this.nImg this.sK(4) nex],'like',Y); 80 | S = reshape(fft2(getK1(this,theta)),[this.nImg this.sK(3:4)]); 81 | Yh = fft2(Y); 82 | for k=1:this.sK(4) 83 | T = S(:,:,:,k) .* Yh; 84 | Z(:,:,k,:) = sum(T,3); 85 | end 86 | Z = real(ifft2(Z)); 87 | end 88 | 89 | function dY = Jthetamv(this,dtheta,~,Y,~) 90 | dY = getOp(this,this.Q*dtheta(:))*Y; 91 | end 92 | 93 | 94 | function dtheta = JthetaTmv(this,Z,~,Y,~) 95 | % derivative of Z*(A(theta)*Y) w.r.t. theta 96 | nex = size(Y,4); 97 | 98 | dth1 = zeros(prod(this.sK(1:3)),this.sK(4),'like',Y); 99 | Yh = permute(fft2(Y),[1 2 4 3]); 100 | Zh = ifft2(reshape(Z,[this.nImg this.sK(4) nex])); 101 | 102 | % get q vector for a given row in the block matrix 103 | v = vec(1:prod(this.sK(1:3))); 104 | q = getK1(this,v); 105 | 106 | I = find(q(:)); 107 | for k=1:this.sK(4) 108 | Zk = squeeze(Zh(:,:,k,:)); 109 | tt = squeeze(sum(Zk.*Yh,3)); 110 | tt = real(fft2(tt)); 111 | dth1(q(I),k) = tt(I); 112 | end 113 | dtheta = dth1(:); 114 | end 115 | 116 | function Y = ATmv(this,theta,Z) 117 | 118 | nex = size(Z,4); 119 | Y = zeros([this.nImg this.sK(3) nex],'like',Z); 120 | S = reshape(fft2(getK1(this,theta)),[this.nImg this.sK(3:4)]); 121 | 122 | Zh = ifft2(Z); 123 | for k=1:this.sK(3) 124 | Sk = squeeze(S(:,:,k,:)); 125 | Y(:,:,k,:) = sum(Sk.*Zh,3); 126 | end 127 | Y = real(fft2(Y)); 128 | end 129 | function n = nFeatIn(this) 130 | n = prod(nImgIn(this)); 131 | end 132 | function n = nFeatOut(this) 133 | n = prod(nImgOut(this)); 134 | end 135 | 136 | function n = nImgIn(this) 137 | n = [this.nImg(1:2) this.sK(3)]; 138 | end 139 | 140 | function K1 = getK1(this,theta) 141 | % compute first row of convolution matrix 142 | theta = reshape(theta,this.sK(1),this.sK(2),[]); 143 | center = (this.sK(1:2)+1)/2; 144 | 145 | K1 = zeros([this.nImg size(theta,3)],'like',theta); 146 | K1(1:this.sK(1),1:this.sK(2),:) = theta; 147 | K1 = circshift(K1,1-center); 148 | end 149 | function n = nImgOut(this) 150 | n = [this.nImg(1:2) this.sK(4)]; 151 | end 152 | 153 | function theta = initTheta(this) 154 | sd= 0.1; 155 | theta = sd*randn(this.sK); 156 | id1 = find(theta>2*sd); 157 | theta(id1(:)) = randn(numel(id1),1); 158 | 159 | id2 = find(theta< -2*sd); 160 | theta(id2(:)) = randn(numel(id2),1); 161 | 162 | theta = max(min(2*sd, theta),-2*sd); 163 | theta = theta - mean(theta) 164 | 165 | end 166 | 167 | end 168 | end 169 | 170 | -------------------------------------------------------------------------------- /conv/convMCN.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classdef convMCN 8 | % 9 | % 2D convolution using MatConvNet 10 | % 11 | % Transforms feature using affine linear mapping 12 | % 13 | % Y(theta,Y0) K(theta) * Y0 14 | % 15 | % !! needs compiled binaries from MatConvNet; see http://www.vlfeat.org/matconvnet/ !! 16 | % 17 | % where 18 | % 19 | % K - convolution matrix 20 | classdef convMCN 21 | 22 | 23 | properties 24 | nImg % image size 25 | sK % kernel size: [nxfilter,nyfilter,nInputChannels,nOutputChannels] 26 | Q 27 | stride 28 | pad 29 | end 30 | 31 | methods 32 | function this = convMCN(nImg, sK,varargin) 33 | 34 | if nargout==0 && nargin==0 35 | this.runMinimalExample; 36 | return; 37 | end 38 | nImg = nImg(1:2); 39 | stride = 1; 40 | Q = opEye(prod(sK)); 41 | for k=1:2:length(varargin) % overwrites default parameter 42 | eval([ varargin{k},'=varargin{',int2str(k+1),'};']); 43 | end 44 | 45 | this.nImg = nImg; 46 | this.sK = sK; 47 | this.stride = stride; 48 | this.Q = Q; 49 | this.pad = floor((this.sK(1)-1)/2); 50 | end 51 | 52 | function A = getOp(this,K) 53 | n = nFeatIn(this); 54 | m = nFeatOut(this); 55 | Af = @(Y) this.Amv(K,Y); 56 | ATf = @(Y) this.ATmv(K,Y); 57 | A = LinearOperator(m,n,Af,ATf); 58 | end 59 | 60 | 61 | function runMinimalExample(~) 62 | nImg = [16 18]; 63 | sK = [3 3,1,2]; 64 | kernel = feval(mfilename,nImg,sK,'stride',2); 65 | theta = rand(sK); 66 | theta(:,1,:) = -1; theta(:,3,:) = 1; 67 | 68 | I = rand(nImgIn(kernel)); I(4:12,4:12) = 2; 69 | Ik = Amv(kernel,theta,I); 70 | Ik2 = ATmv(kernel,theta,Ik); 71 | Ik = reshape(Ik,kernel.nImgOut()); 72 | figure(1); clf; 73 | subplot(1,2,1); 74 | imagesc(I); 75 | title('input'); 76 | 77 | subplot(1,2,2); 78 | imagesc(Ik(:,:,1)); 79 | title('output'); 80 | end 81 | 82 | function [Y,tmp] = Amv(this,theta,Y) 83 | tmp = []; % no need to store any intermediates 84 | 85 | K = reshape(this.Q*theta(:),this.sK); 86 | Y = vl_nnconv(Y,K,[],'pad',this.pad,'stride',this.stride); 87 | end 88 | 89 | function dY = Jthetamv(this,dtheta,~,Y,~) 90 | dY = getOp(this,this.Q*dtheta(:))*Y; 91 | end 92 | 93 | 94 | function dtheta = JthetaTmv(this,Z,~,Y,~) 95 | % derivative of Z*(A(theta)*Y) w.r.t. theta 96 | % get derivative w.r.t. convolution kernels 97 | [~,dtheta] = vl_nnconv(Y,zeros(this.sK,'like',Y), [],Z,'pad',this.pad,'stride',this.stride); 98 | dtheta = this.Q'*dtheta(:); 99 | end 100 | 101 | function dY = ATmv(this,theta,Z) 102 | 103 | theta = reshape(this.Q*theta(:),this.sK); 104 | 105 | crop = this.pad; 106 | if this.stride==2 && this.sK(1)==3 107 | crop=this.pad*[1,0,1,0]; 108 | elseif this.stride==2 && this.sK(1)==2 109 | crop=0*crop; 110 | end 111 | dY = vl_nnconvt(Z,theta,[],'crop',crop,'upsample',this.stride); 112 | if this.stride==2 && this.sK(1)==1 113 | dY = padarray(dY,[1 1],0,'post'); 114 | end 115 | end 116 | function n = nFeatIn(this) 117 | n = prod(nImgIn(this)); 118 | end 119 | function n = nFeatOut(this) 120 | n = prod(nImgOut(this)); 121 | end 122 | 123 | function n = nImgIn(this) 124 | n = [this.nImg(1:2) this.sK(3)]; 125 | end 126 | 127 | function n = nImgOut(this) 128 | n = [this.nImg(1:2)./this.stride this.sK(4)]; 129 | end 130 | 131 | function theta = initTheta(this) 132 | sd= 0.1; 133 | theta = sd*randn(this.sK); 134 | id1 = find(theta>2*sd); 135 | theta(id1(:)) = randn(numel(id1),1); 136 | 137 | id2 = find(theta< -2*sd); 138 | theta(id2(:)) = randn(numel(id2),1); 139 | 140 | theta = max(min(2*sd, theta),-2*sd); 141 | theta = theta - mean(theta); 142 | 143 | end 144 | 145 | end 146 | end 147 | 148 | -------------------------------------------------------------------------------- /conv/examples/EConv_BatchNorm.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demo for batchnorm 8 | % 9 | close all; clear all; 10 | 11 | nex = 8; 12 | [Y,C] = setupMNIST(nex,1); 13 | Y = reshape(Y,28,28,[]); 14 | %% 15 | param.dir = 3; 16 | param.epsilon = 1e-5; 17 | Yn = normLayer(Y,param); 18 | 19 | %% 20 | figure(1); clf; 21 | subplot(2,1,1) 22 | montageArray(Y,nex); 23 | axis equal tight 24 | colorbar 25 | 26 | subplot(2,1,2) 27 | montageArray(Yn,nex); 28 | axis equal tight 29 | colorbar 30 | 31 | 32 | %% 33 | figure(2); clf; 34 | subplot(1,2,1) 35 | montageArray(reshape(Y(:,:,1),28,28,[])); 36 | axis equal tight 37 | colorbar 38 | set(gca,'FontSize',20) 39 | title('original'); 40 | 41 | subplot(1,2,2) 42 | montageArray(reshape(Yn(:,:,1),28,28,[])); 43 | axis equal tight 44 | title('after batch norm') 45 | set(gca,'FontSize',20) 46 | colorbar 47 | % caxis([-. .1])close all; clear all; 48 | 49 | %% 50 | [Y,C] = setupMNIST(16); 51 | Y = reshape(Y,28,28,[]); 52 | 53 | %% 54 | param.dir = 3; 55 | param.epsilon = 1e-5; 56 | Yn = normLayer(Y,param); 57 | 58 | %% 59 | figure(1); clf; 60 | subplot(2,1,1) 61 | montageArray(Y,16); 62 | axis equal tight 63 | colorbar 64 | 65 | subplot(2,1,2) 66 | montageArray(Yn,16); 67 | axis equal tight 68 | colorbar 69 | 70 | 71 | %% 72 | figure(2); clf; 73 | subplot(1,2,1) 74 | montageArray(Y(:,:,1)) 75 | axis equal tight 76 | colorbar 77 | set(gca,'FontSize',20) 78 | title('original'); 79 | 80 | subplot(1,2,2) 81 | montageArray(Yn(:,:,1)) 82 | axis equal tight 83 | title('after batch norm') 84 | set(gca,'FontSize',20) 85 | colorbar 86 | % caxis([-. .1]) -------------------------------------------------------------------------------- /conv/examples/EConv_CoarseToFine.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demo for prolongation of 1D convolution operators 8 | % 9 | clc; close all; 10 | 11 | % number of discretization points 12 | nc = 16; 13 | nf = 2*nc; 14 | hc = 1/nc; 15 | hf = 1/nf; 16 | 17 | % grids 18 | x = linspace(0,1,101); 19 | xc = linspace(0,1,nc); 20 | xf = linspace(0,1,nf); 21 | 22 | %% get A(hc) and A(hf) 23 | thc = [-67; 129; -59]; 24 | fprintf('theta(coarse):\t[%1.3f,%1.3f,%1.3f]\n',thc); 25 | Ac = [1 -1 -1; 1 0 2; 1 1 -1] * diag([1/4;1/(2*hc);1/hc^2]); 26 | beta = Ac\thc; 27 | fprintf('beta: \t[%1.3f,%1.3f,%1.3f]\n',beta); 28 | Af = [1 -1 -1; 1 0 2; 1 1 -1] * diag([1/4;1/(2*hf);1/hf^2]); 29 | thf = Af*beta; 30 | fprintf('theta(fine): \t[%1.3f,%1.3f,%1.3f]\n',thf); 31 | %% 32 | f = @(x) (cos(2*pi*x.^4))+x-.8*(x-.5).^2; 33 | df = @(x) x - (4*(x - 1/2).^2)/5 - 8*x.^3.*pi.*sin(2*pi*x.^4); 34 | d2f = @(x) 9/5 - 24*x.^2.*pi.*sin(2*pi*x.^4) - 64*x.^6.*pi^2.*cos(2*pi*x.^4) - (8*x)/5; 35 | 36 | z = @(x) beta(1)*f(x)+beta(2)*df(x)+beta(3)*d2f(x); 37 | 38 | fig = figure(1); clf; 39 | fig.Name = 'E15CoarseToFineConv1D'; 40 | subplot(2,2,1); 41 | plot(x,f(x),'-b','LineWidth',2); 42 | set(gca,'FontSize',20) 43 | title('function,f') 44 | 45 | subplot(2,2,2) 46 | fig.Name = 'z'; 47 | plot(x,z(x),'-r','LineWidth',2); 48 | set(gca,'FontSize',20) 49 | hold on; 50 | plot(xc,conv(f(xc),-thc,'same'),'.-k','MarkerSize',30,'LineWidth',2); 51 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xc),thc)','location','SouthWest') 52 | title('coarse conv') 53 | 54 | %% 55 | subplot(2,2,3) 56 | fig.Name = 'z'; 57 | plot(x,z(x),'-r','LineWidth',2); 58 | set(gca,'FontSize',20) 59 | hold on; 60 | plot(xf,conv(f(xf),-thc,'same'),'.-k','MarkerSize',30,'LineWidth',2); 61 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xf),thc)','location','SouthWest') 62 | title('fine conv (coarse stencil)') 63 | %% 64 | subplot(2,2,4) 65 | fig.Name = 'z'; 66 | plot(x,z(x),'-r','LineWidth',2); 67 | set(gca,'FontSize',20) 68 | hold on; 69 | plot(xf,conv(f(xf),-thf,'same'),'.-k','MarkerSize',30,'LineWidth',2); 70 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xf),thf)','location','SouthWest') 71 | title('fine conv (prol. stencil)') 72 | 73 | 74 | -------------------------------------------------------------------------------- /conv/examples/EConv_CoarseToFineGalerkin.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demo for prolongation of 1D convolution operators 8 | % 9 | clc; close all; 10 | 11 | % number of discretization points 12 | nc = 16; 13 | nf = 2*nc; 14 | hc = 1/nc; 15 | hf = 1/nf; 16 | 17 | % grids 18 | x = linspace(0,1,101); 19 | xc = linspace(0,1,nc); 20 | xf = linspace(0,1,nf); 21 | 22 | % setup restriction 23 | R = spdiags(ones(nf,1)*[1 1]/2,0:1,nf,nf); 24 | R = R(1:2:end,:); 25 | 26 | % setup prolongation 27 | P = zeros(nf,nc); 28 | for i=2:nc-1 29 | P(2*i-2:2*i+1,i) = [1;3;3;1]; 30 | end 31 | P(1:3,1) = [4;3;1]; 32 | P(end-2:end,end) = [1;3;4]; 33 | P = 1/4*sparse(P); 34 | 35 | % build basis of convolution operators 36 | getKH = @(th) spdiags(ones(nc,1)*th',-1:1,nc,nc); 37 | getKh = @(th) spdiags(ones(nf,1)*th',-1:1,nf,nf); 38 | A = zeros(3,3); 39 | for k=1:3 40 | t = zeros(3,1); t(k)=1; 41 | KH = R*getKh(t)*P; 42 | A(:,k) = KH(1:3,2); 43 | end 44 | 45 | %% get A(hc) and A(hf) 46 | thc = [-67; 129; -59]; 47 | fprintf('theta(coarse):\t[%1.3f,%1.3f,%1.3f]\n',thc); 48 | Ac = [1 -1 -1; 1 0 2; 1 1 -1] * diag([1/4;1/(2*hc);1/hc^2]); 49 | beta = Ac\thc; 50 | fprintf('beta: \t[%1.3f,%1.3f,%1.3f]\n',beta); 51 | Af = [1 -1 -1; 1 0 2; 1 1 -1] * diag([1/4;1/(2*hf);1/hf^2]); 52 | thf = Af*beta; 53 | fprintf('theta(fine): \t[%1.3f,%1.3f,%1.3f]\n',thf); 54 | thf = A\thc; 55 | fprintf('theta(Galerkin): \t[%1.3f,%1.3f,%1.3f]\n',thf); 56 | %% 57 | f = @(x) (cos(2*pi*x.^4))+x-.8*(x-.5).^2; 58 | df = @(x) x - (4*(x - 1/2).^2)/5 - 8*x.^3.*pi.*sin(2*pi*x.^4); 59 | d2f = @(x) 9/5 - 24*x.^2.*pi.*sin(2*pi*x.^4) - 64*x.^6.*pi^2.*cos(2*pi*x.^4) - (8*x)/5; 60 | 61 | z = @(x) beta(1)*f(x)+beta(2)*df(x)+beta(3)*d2f(x); 62 | 63 | fig = figure(2); clf; 64 | fig.Name = 'E15CoarseToFineConv1D'; 65 | subplot(2,2,1); 66 | plot(x,f(x),'-b','LineWidth',2); 67 | set(gca,'FontSize',20) 68 | title('function,f') 69 | 70 | subplot(2,2,2) 71 | fig.Name = 'z'; 72 | plot(x,z(x),'-r','LineWidth',2); 73 | set(gca,'FontSize',20) 74 | hold on; 75 | plot(xc,conv(f(xc),-thc,'same'),'.-k','MarkerSize',30,'LineWidth',2); 76 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xc),thc)','location','SouthWest') 77 | title('coarse conv') 78 | 79 | %% 80 | subplot(2,2,3) 81 | fig.Name = 'z'; 82 | plot(x,z(x),'-r','LineWidth',2); 83 | set(gca,'FontSize',20) 84 | hold on; 85 | plot(xf,conv(f(xf),-thc,'same'),'.-k','MarkerSize',30,'LineWidth',2); 86 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xf),thc)','location','SouthWest') 87 | title('fine conv (coarse stencil)') 88 | %% 89 | subplot(2,2,4) 90 | fig.Name = 'z'; 91 | plot(x,z(x),'-r','LineWidth',2); 92 | set(gca,'FontSize',20) 93 | hold on; 94 | plot(xf,conv(f(xf),-thf,'same'),'.-k','MarkerSize',30,'LineWidth',2); 95 | legend('\beta(1)f+\beta(2)f'' + \beta(3) f''''','conv(f(xf),thf)','location','SouthWest') 96 | title('fine conv (prol. stencil)') 97 | 98 | 99 | -------------------------------------------------------------------------------- /conv/examples/EConv_ConvFFT2D.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demo for 2D convolution 8 | close all; clear all; 9 | 10 | [Y,C] = setupMNIST(1); 11 | Y = Y - mean(Y(:)); 12 | nImg = [28 28]; % size of image 13 | sTheta = [5 5]; % size of convolution stencil 14 | theta = randn(sTheta); 15 | theta = theta - mean(theta(:)); 16 | 17 | %% 18 | K = conv2D(nImg,sTheta,theta,Y); 19 | Z = K(Y); 20 | 21 | %% 22 | fig = figure(1); clf; 23 | fig.Name = sprintf('%s',mfilename); 24 | subplot(1,3,1); 25 | imagesc(reshape(Y,nImg)); 26 | axis square off; 27 | colormap(flipud(colormap('gray'))) 28 | title('input image'); 29 | 30 | 31 | subplot(1,3,2); 32 | imagesc(theta); 33 | axis square off; 34 | colormap('gray') 35 | title('convolution kernel'); 36 | 37 | 38 | subplot(1,3,3); 39 | imagesc(reshape(Z,nImg)); 40 | axis square off; 41 | colormap(flipud(colormap('gray'))) 42 | title('output image'); 43 | -------------------------------------------------------------------------------- /conv/examples/EConv_InstanceNorm.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demo for instancenorm 8 | % 9 | close all; clear all; 10 | 11 | nex = 8; 12 | [Y,C] = setupMNIST(nex,1); 13 | 14 | %% 15 | param.dir = 1; 16 | param.epsilon = 1e-5; 17 | Yn = normLayer(Y,param); 18 | 19 | %% 20 | fig = figure; clf; 21 | fig.Name = [mfilename ': batch']; 22 | subplot(2,1,1) 23 | montageArray(reshape(Y,28,28,[]),nex); 24 | axis equal tight 25 | colorbar 26 | 27 | subplot(2,1,2) 28 | montageArray(reshape(Yn,28,28,[]),nex); 29 | axis equal tight 30 | colorbar 31 | 32 | 33 | %% 34 | fig = figure; clf; 35 | fig.Name = [mfilename ': first image']; 36 | subplot(1,2,1) 37 | montageArray(reshape(Y(:,1),28,28,[])); 38 | axis equal tight 39 | colorbar 40 | set(gca,'FontSize',20) 41 | title('original'); 42 | 43 | subplot(1,2,2) 44 | montageArray(reshape(Yn(:,1),28,28,[])); 45 | axis equal tight 46 | title('after instance norm') 47 | set(gca,'FontSize',20) 48 | colorbar -------------------------------------------------------------------------------- /conv/examples/EConv_deriveConvFFT.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Here, we derive a matrix-free implementation of a 1D convolution with 8 | % FFTs 9 | % 10 | 11 | clc; clear; 12 | m = 6; % number of cells in grid 13 | theta = [1 2 3]'; % stencil 14 | 15 | % build convolution operator 16 | K = spdiags(ones(m,1)*flipud(theta)',-1:1,m,m); 17 | % periodic boundary conditions 18 | K(1,end) = theta(3); 19 | K(end,1) = theta(1); 20 | K = full(K) 21 | 22 | %% verify that eigenvalues can be obtained by using fft (up to ordering) 23 | lam = fft(K(:,1)); 24 | lamt = eig(K) 25 | 26 | [lam lamt] 27 | 28 | %% verify that convolution can be computed as F^{-1)(lam .* F(y)) 29 | y = randn(m,1); 30 | errKy = norm(K*y - ifft(lam.*fft(y))) 31 | %% verify equation for transpose of convolution operator 32 | errKTy = norm(K'*y - ifft(conj(lam).*fft(y))) 33 | 34 | %% verify that first column of K can be computed using circshift 35 | theta = [1;2;3;]; 36 | center = (numel(theta)+1)/2; 37 | Ku = circshift([theta;zeros(m-numel(theta),1)],1-center); 38 | errKu = norm(K(:,1)-Ku) -------------------------------------------------------------------------------- /data/loadMNISTImages.m: -------------------------------------------------------------------------------- 1 | function images = loadMNISTImages(filename) 2 | %loadMNISTImages returns a 28x28x[number of MNIST images] matrix containing 3 | %the raw MNIST images 4 | 5 | fp = fopen(filename, 'rb'); 6 | assert(fp ~= -1, ['Could not open ', filename, '']); 7 | 8 | magic = fread(fp, 1, 'int32', 0, 'ieee-be'); 9 | assert(magic == 2051, ['Bad magic number in ', filename, '']); 10 | 11 | numImages = fread(fp, 1, 'int32', 0, 'ieee-be'); 12 | numRows = fread(fp, 1, 'int32', 0, 'ieee-be'); 13 | numCols = fread(fp, 1, 'int32', 0, 'ieee-be'); 14 | 15 | images = fread(fp, inf, 'unsigned char'); 16 | images = reshape(images, numCols, numRows, numImages); 17 | images = permute(images,[2 1 3]); 18 | 19 | fclose(fp); 20 | 21 | % Reshape to #pixels x #examples 22 | images = reshape(images, size(images, 1) * size(images, 2), size(images, 3)); 23 | % Convert to double and rescale to [0,1] 24 | images = double(images) / 255; 25 | 26 | end -------------------------------------------------------------------------------- /data/loadMNISTLabels.m: -------------------------------------------------------------------------------- 1 | function labels = loadMNISTLabels(filename) 2 | %loadMNISTLabels returns a [number of MNIST images]x1 matrix containing 3 | %the labels for the MNIST images 4 | 5 | fp = fopen(filename, 'rb'); 6 | assert(fp ~= -1, ['Could not open ', filename, '']); 7 | 8 | magic = fread(fp, 1, 'int32', 0, 'ieee-be'); 9 | assert(magic == 2049, ['Bad magic number in ', filename, '']); 10 | 11 | numLabels = fread(fp, 1, 'int32', 0, 'ieee-be'); 12 | 13 | labels = fread(fp, inf, 'unsigned char'); 14 | 15 | assert(size(labels,1) == numLabels, 'Mismatch in label count'); 16 | 17 | fclose(fp); 18 | 19 | end -------------------------------------------------------------------------------- /data/setupCIFAR10.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ytrain,Ctrain,Yval,Cval] = setupCIFAR10(nTrain,nVal,option) 8 | % 9 | function[Ytrain,Ctrain,Yval,Cval] = setupCIFAR10(nTrain,nVal,option) 10 | 11 | if nargin==0 12 | runMinimalExample; 13 | return; 14 | end 15 | 16 | if not(exist('nTrain','var')) || isempty(nTrain) 17 | nTrain = 50000; 18 | end 19 | 20 | if not(exist('nVal','var')) || isempty(nVal) 21 | nVal = ceil(nTrain/5); 22 | end 23 | 24 | if not(exist('option','var')) || isempty(option) 25 | option = 1; 26 | end 27 | 28 | if not(exist('data_batch_1.mat','file')) || ... 29 | not(exist('data_batch_2.mat','file')) || ... 30 | not(exist('data_batch_3.mat','file')) || ... 31 | not(exist('data_batch_4.mat','file')) || ... 32 | not(exist('data_batch_5.mat','file')) 33 | 34 | warning('CIFAR10 data cannot be found in MATLAB path') 35 | 36 | dataDir = [fileparts(which('startupNumDLToolbox.m')) filesep 'data']; 37 | cifarDir = [dataDir filesep 'CIFAR']; 38 | doDownload = input(sprintf('Do you want to download https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz (around 175 MB) to %s? Y/N [Y]: ',dataDir),'s'); 39 | if isempty(doDownload) || strcmp(doDownload,'Y') 40 | if not(exist(dataDir,'dir')) 41 | mkdir(dataDir); 42 | end 43 | imtz = fullfile(dataDir,'cifar-10-matlab.tar.gz'); 44 | if not(exist(imtz,'file')) 45 | websave(fullfile(dataDir,'cifar-10-matlab.tar.gz'),'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz'); 46 | end 47 | im = untar(imtz,dataDir); 48 | movefile([dataDir filesep 'cifar-10-batches-mat'],cifarDir); 49 | delete(imtz) 50 | addpath(cifarDir); 51 | else 52 | error('CIFAR10 data not available. Please make sure it is in the current path'); 53 | end 54 | end 55 | 56 | % Reading in the data 57 | 58 | load data_batch_1.mat 59 | data1 = double(data); 60 | labels1 = labels; 61 | 62 | load data_batch_2.mat 63 | data2 = double(data); 64 | labels2 = labels; 65 | 66 | load data_batch_3.mat 67 | data3 = double(data); 68 | labels3 = labels; 69 | 70 | load data_batch_4.mat 71 | data4 = double(data); 72 | labels4 = labels; 73 | 74 | load data_batch_5.mat 75 | data5 = double(data); 76 | labels5 = labels; 77 | 78 | data = [data1; data2; data3; data4; data5]; 79 | labels = [labels1; labels2; labels3; labels4; labels5]; 80 | nex = size(data,1); 81 | 82 | 83 | 84 | if nTrain2 94 | load test_batch.mat 95 | dataTest = double(data); 96 | labelsTest = labels; 97 | nex = size(dataTest,1); 98 | if nVal2 72 | Yval = I(:,idVal); 73 | Cval = C(:,idVal); 74 | Yval = Yval/max(abs(Yval(:))) - 0.5; 75 | [~,k] = sort((1:10)*Cval); 76 | Yval = Yval(:,k); 77 | Cval = Cval(:,k); 78 | end 79 | 80 | function runMinimalExample 81 | [Yt,Ct,Yv,Cv] = feval(mfilename,50,10); 82 | figure(1);clf; 83 | subplot(2,1,1); 84 | montageArray(reshape(Yt,28,28,[]),10); 85 | axis equal tight 86 | colormap(flipud(colormap('gray'))) 87 | title('training images'); 88 | 89 | 90 | subplot(2,1,2); 91 | montageArray(reshape(Yv,28,28,[]),10); 92 | axis equal tight 93 | colormap(flipud(colormap('gray'))) 94 | title('validation images'); 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /data/setupPeaks.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Y,C] = setupPeaks(np, nc, ns) 8 | % 9 | % setup data for peaks example 10 | % 11 | function[Y,C] = setupPeaks(np, nc, ns) 12 | % generates PEAKs example 13 | if not(exist('np','var')) || isempty(np) 14 | np = 8000; 15 | end 16 | 17 | if not(exist('nc','var')) || isempty(nc) 18 | nc = 5; 19 | end 20 | 21 | if not(exist('ns','var')) || isempty(ns) 22 | ns = 256; 23 | end 24 | 25 | 26 | [xx,yy,cc] = peaks(ns); 27 | t1 = linspace(min(xx(:)),max(xx(:)),ns); 28 | t2 = linspace(min(yy(:)),max(yy(:)),ns); 29 | 30 | % Binarize it 31 | mxcc = max(cc(:)); mncc = min(cc(:)); 32 | hc = (mxcc - mncc)/(nc); 33 | ccb = zeros(size(cc)); 34 | for i=1:nc 35 | ii = find( (mncc + (i-1)*hc)< cc & cc <= (mncc+i*hc)); 36 | ccb(ii) = i-1; 37 | end 38 | 39 | figure(1); clf; 40 | imagesc(t1,t2,reshape(ccb,ns,ns)) 41 | % rng('default'); 42 | % rng(2) 43 | 44 | % draw same number of points per class 45 | Y = []; 46 | npc = ceil(np/nc); 47 | for k=0:nc-1 48 | xk = [xx(ccb==k) yy(ccb==k)]; 49 | inds = randi(size(xk,1),npc,1); 50 | 51 | Y = [Y; xk(inds,:)]; 52 | end 53 | 54 | C = kron(eye(nc),ones(npc,1)); 55 | Y = Y'; 56 | C = C'; 57 | -------------------------------------------------------------------------------- /notes/E_polyfit.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % This driver generates example connecting generalization to overfitting in 8 | % polynomial interpolation. 9 | % 10 | close all; clear all; 11 | 12 | 13 | xf = linspace(0,1,101); 14 | xt = linspace(0,1,10); 15 | ft = sin(pi*xt.^2)+5e-2*randn(1,10); 16 | 17 | xv = 0.97; 18 | fv = sin(pi*xv.^2); 19 | 20 | fig1 = figure(1); clf; 21 | fig1.Name ='data' 22 | p1 = plot(xt,ft,'.','MarkerSize',30) 23 | hold on; 24 | plot(xv,fv,'.','MarkerSize',30) 25 | l = legend('training data','validation data'); 26 | l.Location = 'NorthWest'; 27 | 28 | fig2 = figure(2); clf; 29 | fig2.Name ='overfit' 30 | p = polyfit(xt,ft,numel(xt)+1); 31 | pf = polyval(p,xf); 32 | plot(xt,ft,'.','MarkerSize',40) 33 | hold on; 34 | plot(xv,fv,'.','MarkerSize',40) 35 | plot(xf,pf,'-','LineWidth',2,'Color',p1.Color) 36 | l = legend('training data','validation data','model'); 37 | l.Location = 'NorthWest'; 38 | 39 | fig3 = figure(3); clf; 40 | fig3.Name ='underfit' 41 | p = polyfit(xt,ft,2); 42 | pf = polyval(p,xf); 43 | plot(xt,ft,'.','MarkerSize',40) 44 | hold on; 45 | plot(xv,fv,'.','MarkerSize',40) 46 | plot(xf,pf,'-','LineWidth',2,'Color',p1.Color) 47 | 48 | l = legend('training data','validation data','model'); 49 | l.Location = 'NorthWest'; 50 | 51 | return; 52 | figDir = '/Users/lruthot/Dropbox/Projects/NumDL-CourseNotes/images/' 53 | 54 | for k=1:3 55 | fig = figure(k) 56 | axis([0 1 -.3 1.4]) 57 | axis square 58 | set(gca,'FontSize',30) 59 | printFigure(gcf,fullfile(figDir,['generalize_' fig.Name '.png'])) 60 | end 61 | 62 | -------------------------------------------------------------------------------- /optimization/cgls.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[w,rho,eta,W] = cgls(Y,c,tol,maxIter,w,out) 8 | % 9 | % conjugate gradient method for solving the least-squares problem 10 | % 11 | % min_w 0.5 |Y*w - c|^2 12 | % 13 | % Input: 14 | % Y - matrix, e.g., features 15 | % c - right hand side, e.g., labels 16 | % tol - tolerance, (default: 1e-2) 17 | % maxIter - maximum number of iterations, (default: min(size(Y,2),10)) 18 | % w - starting guess (default: zeros(size(Y,2))) 19 | % out - flag for controling output (default: 1--> print iter) 20 | % 21 | % Output: 22 | % w - last iterate 23 | % rho - vector of relative residuals 24 | % eta - vector of norms of current iterates 25 | % W - history of all iterates 26 | function [w,rho,eta,W] = cgls(Y,c,tol,maxIter,w,out) 27 | 28 | 29 | if nargin==0 30 | runMinimalExample 31 | return 32 | end 33 | 34 | n = size(Y,2); 35 | 36 | % set optional parameter 37 | if not(exist('tol','var')) || isempty(tol); tol = 1e-2; end 38 | if not(exist('maxIter','var')) || isempty(maxIter); maxIter = min(size(Y,2),10); end 39 | if not(exist('w','var')) || isempty(w); w = zeros(n,1); end 40 | if not(exist('out','var')) || isempty(out); out=1; end 41 | 42 | if nargout>3, W = w; end 43 | r = c-Y*w; 44 | d = Y'*r; 45 | normr2 = d'*d; 46 | rho = zeros(maxIter,1); eta = zeros(maxIter,1); 47 | 48 | if out 49 | fprintf('=== %s (tol: %1.1e, maxIter: %d) ===\n',mfilename,tol,maxIter); 50 | fprintf('iter\trelres\tnorm(w)\n'); 51 | end 52 | 53 | for j=1:maxIter 54 | Ad = Y*d; 55 | alpha = normr2/(Ad'*Ad); 56 | w = w + alpha*d; 57 | r = r - alpha*Ad; 58 | s = Y'*r; 59 | normr2New = s'*s; 60 | if normr2New3, W = [W w]; end 69 | if out, fprintf('%3d\t%3.1e\t%3.1e\n',j,norm(r)/norm(c),norm(w)); end 70 | end 71 | 72 | function runMinimalExample 73 | Y = randn(10,2); 74 | wtrue = [1;1]; 75 | c = Y*wtrue; 76 | 77 | [w,rho,eta,W] = feval(mfilename,Y,c); 78 | fprintf('true w = [%1.2f,%1.2f]\n',wtrue); 79 | fprintf('est. w = [%1.2f,%1.2f]\n',w); 80 | 81 | 82 | -------------------------------------------------------------------------------- /optimization/newtoncg.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [x,his,xAll] = newtoncg(fun,x0,param) 8 | % 9 | % Newton-CG method with Armijo linesearch 10 | % 11 | % Inputs: 12 | % fun - objective function, e.g., fun = @(x,varargin) Rosenbrock(x) 13 | % x0 - starting guess 14 | % param - parameters for algorithm. Supported fields 15 | % maxIter - maximum number of iterations 16 | % tolCG - tolerance for PCG solver (default: 1e-2) 17 | % maxIterCG - maximum number of CG iterations (default: 10) 18 | % out - flag controlling output (default: 1) 19 | % 20 | % Outputs: 21 | % x - last iterate 22 | % his - iteration history 23 | % xAll - all iterates 24 | 25 | function [x,his,xAll] = newtoncg(fun,x0,param) 26 | 27 | if nargin==0 28 | E = @(x,varargin) Rosenbrock(x); 29 | W = [4;2]; 30 | param = struct('maxIter',30,'maxStep',10); 31 | [W,his,xAll] = feval(mfilename,E,W,param); 32 | fprintf('numerical solution: W = [%1.4f, %1.4f]\n',W); 33 | return 34 | end 35 | 36 | x = x0; xAll = []; 37 | [obj,dobj,H] = fun(x); 38 | 39 | % get paramters 40 | if isfield(param,'tolCG'); 41 | tolCG = param.tolCG; 42 | else 43 | tolCG = 1e-2; 44 | end 45 | if isfield(param,'maxIterCG') 46 | maxIterCG = param.maxIterCG; 47 | else 48 | maxIterCG = 10; 49 | end 50 | 51 | if isfield(param,'out') 52 | out=param.out; 53 | else 54 | out=1; 55 | end 56 | 57 | mu = 1; 58 | his = zeros(param.maxIter,2); 59 | if out==1 60 | fprintf('=== %s (maxIter: %d) ===\n',mfilename,param.maxIter); 61 | fprintf('iter\t obj func\tnorm(grad)\n'); 62 | end 63 | 64 | for j=1:param.maxIter 65 | 66 | his(j,:) = [obj,norm(dobj)]; 67 | 68 | if nargout>2; xAll = [xAll x]; end; 69 | 70 | if out==1; fprintf('%3d.0\t%3.2e\t%3.2e\n',j,his(j,:)); end 71 | [s,FLAG,RELRES,ITER,RESVEC] = pcg(H,-dobj,tolCG,maxIterCG); 72 | 73 | % resort to steepest descent if pcg fails 74 | if norm(s)==0 75 | s = -dobj/norm(dobj); 76 | end 77 | 78 | % test if s is a descent direction 79 | if s(:)'*dobj(:) > 0 80 | s = -dobj; 81 | end 82 | % Armijo line search 83 | cnt = 1; 84 | while 1 85 | xtry = x + mu*s; 86 | [objtry,dobj,H] = fun(xtry,param); 87 | if out==1; fprintf('%3d.%d\t%3.2e\t%3.2e\n',j,cnt,objtry,norm(dobj)); end 88 | 89 | if objtry< obj 90 | break 91 | end 92 | mu = mu/2; 93 | cnt = cnt+1; 94 | if cnt > 20 95 | warning('Line search break'); 96 | return; 97 | end 98 | end 99 | if cnt == 1 100 | mu = min(mu*1.5,1); 101 | end 102 | x = xtry; 103 | obj = objtry; 104 | end -------------------------------------------------------------------------------- /optimization/sgd.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[xc,his,xAll] = sgd(fctn,xc,param) 8 | % 9 | % Simple implementation of a Stochastic Gradient Descent method with 10 | % momentum. 11 | % 12 | % Inputs: 13 | % fctn - objective function (accepts two arguments: the current iterate 14 | % and indices of data points to use in current step) 15 | % xc - starting guess 16 | % param - struct, algorithmic paramter. Supported parameters are 17 | % lr - vector, learning rate for each epoch 18 | % n - number of data points overall 19 | % batchSize - number of examples per batch 20 | % momentum - momentum parameter 21 | % out - flag controlling output (default: out=1) 22 | % 23 | % Outputs: 24 | % xc - last iterate 25 | % his - iteration history 26 | % xAll - iterates after each epoch 27 | function [xc,his,xAll] = sgd(fctn,xc,param) 28 | 29 | 30 | if nargin==0 31 | A = hilb(10); A = A(:,1:2); 32 | x = ones(2,1); 33 | b = A*x; 34 | 35 | fctn = @(xc,S) quadObjFun(A,b,xc,S); 36 | param.lr = 1e-1*ones(100,1); 37 | param.n = numel(b); 38 | param.batchSize = 1; 39 | param.momentum=0.9; 40 | xc = 0*x; 41 | [xOpt,xAll,his] = feval(mfilename,fctn,xc,param); 42 | xOpt 43 | 44 | return 45 | end 46 | 47 | xAll = []; 48 | % read parameters 49 | lr = param.lr; 50 | n = param.n; 51 | batchSize = param.batchSize; 52 | momentum = param.momentum; 53 | if isfield(param,'out') 54 | out = param.out; 55 | else 56 | out = 1; 57 | end 58 | 59 | nb = n/batchSize; % number of batches 60 | 61 | dF = 0*xc; 62 | his = zeros(numel(lr),2); 63 | 64 | if out 65 | fprintf('=== %s (epochs: %d, batchSize: %d, momentum: %1.2e) ===\n',... 66 | mfilename, numel(lr),batchSize,momentum); 67 | fprintf('epoch\tobj fun\t\tnorm step\n'); 68 | end 69 | 70 | 71 | for epoch=1:numel(lr) 72 | % re-shuffle 73 | xOld = xc; 74 | S = reshape(randperm(n),[],nb); 75 | for batch=1:nb 76 | Sk = S(:,batch); 77 | [Fk,dFk] = fctn(xc,Sk); 78 | dF = momentum*dF + lr(epoch)*dFk; 79 | xc = xc - dF; 80 | end 81 | %evaluate full objective 82 | [Fc] = fctn(xc,1:min(n,5000)); 83 | his(epoch,:) = [Fc norm(xc-xOld)]; 84 | fprintf('%3d\t%1.2e\t%1.2e\n',epoch,his(epoch,:)) 85 | 86 | if nargout>2; xAll = [xAll xc]; end; 87 | 88 | end -------------------------------------------------------------------------------- /optimization/steepestDescent.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[x,his,xAll] = steepestDescent(fun,x0,param) 8 | % 9 | % Steepest Descent method with Armijo linesearch 10 | % 11 | % Inputs: 12 | % fun - objective function, e.g., fun = @(x,varargin) Rosenbrock(x) 13 | % x0 - starting guess 14 | % param - parameters for algorithm. Supported fields 15 | % maxIter - maximum number of iterations 16 | % maxStep - maximum step size 17 | % P - projection onto feasible set (default: @(x) x) 18 | % out - flag controlling output (default: 1) 19 | % 20 | % Outputs: 21 | % x - last iterate 22 | % his - iteration history 23 | % xAll - all iterates 24 | function [x,his,xAll] = steepestDescent(fun,x,param) 25 | 26 | if nargin==0 27 | fun = @Rosenbrock; 28 | x = [4;2]; 29 | param = struct('maxIter',10000,'maxStep',1); 30 | x = feval(mfilename,fun,x,param); 31 | fprintf('numerical solution: W = [%1.4f, %1.4f]\n',x); 32 | return 33 | end 34 | xAll = []; 35 | mu = param.maxStep; % max step size 36 | maxIter = param.maxIter; % max number of iterations 37 | if isfield(param,'P') 38 | P = param.P; 39 | else 40 | P = @(x) x; 41 | end 42 | if isfield(param,'out') 43 | out=param.out; 44 | else 45 | out=1; 46 | end 47 | muLS = 1.0; 48 | 49 | if out==1 50 | fprintf('=== %s (maxIter: %d) ===\n',mfilename,maxIter); 51 | fprintf('iter\t obj func\t\tnorm(grad)\n'); 52 | end 53 | his = zeros(maxIter,2); 54 | 55 | x = P(x); 56 | for i=1:maxIter 57 | [Ec,dE] = fun(x); 58 | his(i,:) = [Ec,norm(dE)]; 59 | if out==1; fprintf('%3d.0\t%3.2e\t%3.2e\n',i,his(i,:)); end 60 | if norm(dE)>mu, dE = mu*dE/norm(dE); end; 61 | 62 | for LSiter=1:10 63 | xt = P(x-muLS*dE); 64 | Et = fun(xt); 65 | if out==1; fprintf('%3d.%d\t%3.2e\n',i,LSiter,Et); end 66 | if Et= Ec 75 | warning('LSB') 76 | return 77 | end 78 | x = xt; 79 | if nargout>2; xAll = [xAll x]; end 80 | end 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /regularization/genTikhonov.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | %[R,dR,d2R] = genTikhonov(W,param) 8 | % 9 | % R(W) = 0.5*lambda*|L*W|^2 10 | % 11 | % where size(W)=size(L,2)*nc. 12 | % 13 | % Input: 14 | % W - weights, will be reshaped internally 15 | % param - struct with additional parameters. Required fields: 16 | % L - regularization operator 17 | % lambda - regularization parameter 18 | % 19 | % Output: 20 | % Rc - value of regularizer 21 | % dR - gradient 22 | % d2R - Hessian, as function handle 23 | 24 | function[R,dR,d2R] = genTikhonov(W,param) 25 | 26 | if nargin==0 27 | help(mfilename); 28 | return 29 | end 30 | if not(isfield(param,'lambda')); param.lambda = 1; end 31 | 32 | L = param.L; 33 | lambda = param.lambda; 34 | W = reshape(W,size(L,2),[]); 35 | 36 | LW = L*W; 37 | R = 0.5* lambda * (LW(:)'*LW(:)); 38 | dR = lambda * L'*LW; 39 | dR = dR(:); 40 | 41 | mat = @(X) reshape(X,size(W)); 42 | vec = @(X) X(:); 43 | d2Rmat = lambda*(L'*L); 44 | d2R = @(X) vec(d2Rmat*mat(X)); -------------------------------------------------------------------------------- /regularization/getLaplacian.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [L] = getLaplacian(nImg,h) 8 | % 9 | % generates a discrete Laplacian 10 | % 11 | % Inputs: 12 | % nImg - number of pixels in each dimension 13 | % h - pixel size 14 | % 15 | % Output: 16 | % L - discrete Laplacian, sparse matrix 17 | 18 | function[L] = getLaplacian(nImg,h) 19 | 20 | 21 | if nargin==0 22 | runMinimalExample; 23 | return 24 | end 25 | 26 | dim = ndims(nImg); 27 | 28 | d2dx = @(n,h) 1/h^2*spdiags(ones(n,1)*[1 -2 1],-1:1,n,n); 29 | 30 | switch dim 31 | case 1 32 | d2dx = d2dx(nImg,h); 33 | case 2 34 | d2dx1 = d2dx(nImg(1),h(1)); 35 | d2dx2 = d2dx(nImg(2),h(2)); 36 | 37 | L = kron(speye(nImg(2)),d2dx1) + kron(d2dx2,speye(nImg(1))); 38 | case 3 39 | d2dx1 = d2dx(nImg(1),h(1)); 40 | d2dx2 = d2dx(nImg(2),h(2)); 41 | d2dx3 = d2dx(nImg(3),h(3)); 42 | 43 | L = kron(speye(nImg(3)),kron(speye(nImg(2)),d2dx1)) +... 44 | kron(speye(nImg(3)),kron(d2dx2,speye(nImg(1)))) +... 45 | kron(d2dx3 ,kron(speye(nImg(2)),speye(nImg(1)))); 46 | 47 | end 48 | 49 | function runMinimalExample 50 | n = [32 32]; 51 | h = [1 1]./n; 52 | x = h/2:h:1; 53 | [X,Y] = ndgrid(x); 54 | 55 | u = cos(pi*X(:).*Y(:)); 56 | Lapu = -pi^2*(X(:).^2+Y(:).^2).*u; 57 | 58 | Lap = feval(mfilename,n,h); 59 | Laput = Lap*u; 60 | 61 | figure(1); clf; 62 | subplot(1,3,1); 63 | imagesc(reshape(Lapu,n)); 64 | cax = caxis; 65 | axis equal tight 66 | title('Lap*u, true') 67 | 68 | subplot(1,3,2); 69 | imagesc(reshape(Laput,n)); 70 | caxis(cax); 71 | axis equal tight 72 | title('Lap*u, approx') 73 | 74 | subplot(1,3,3); 75 | imagesc(reshape(Laput-Lapu,n)); 76 | axis equal tight 77 | title('error') 78 | 79 | for k=1:3; subplot(1,3,k); set(gca,'FontSize',20); end; -------------------------------------------------------------------------------- /resnet/ResNetForward.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Y,Yall,dA] = ResNetForward(Kb,Y,param) 8 | % 9 | % Forward propagation through ResNet 10 | % 11 | % Y{j+1} = P{j}*Y{j} + h*act(K{j}'*Y{j} + b{j}) 12 | % 13 | % where P{j} are given and K,b are the weights to be learned 14 | % 15 | % Inputs: 16 | % 17 | % Kb - vector of weights, parsed by vec2cellResNet 18 | % Y - input features 19 | % param - struct describing the networks. Required fields 20 | % h - time step size 21 | % P - cell, P = opEye for ReseNet, P = opZeros for NeuralNet 22 | % n - 2xnt matrix, dimensions of K for each layer 23 | % 24 | % Outputs: 25 | % 26 | % Y - output features 27 | % Yall - features at hidden layers 28 | % dA - cell, derivatives of activations at hidden layers 29 | % (needed for derivative computation) 30 | function [Y,Yall,dA] = ResNetForward(Kb,Y,param) 31 | 32 | [K,b] = vec2cellResNet(Kb,param.n); 33 | 34 | h = param.h; 35 | P = param.P; 36 | N = numel(param.P); 37 | act = param.act; 38 | 39 | % store intermediates 40 | [Yall,dA] = deal(cell(N+1,1)); 41 | if nargout>1 42 | Yall{1} = Y; 43 | end 44 | 45 | % do the forward propagation 46 | for j=1:N 47 | [Aj,dAj] = act(K{j}*Y + b{j}); 48 | Y = P{j}*Y + h*Aj; 49 | 50 | if nargout>1; Yall{j+1} = Y; end 51 | if nargout>2; dA{j}= dAj; end 52 | end -------------------------------------------------------------------------------- /resnet/ResNetObjFun.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ec,dE,H] = ResNetObjFun(x,Y,C,m) 8 | % 9 | % evaluates resnet and computes cross entropy, gradient and approx. Hessian 10 | % 11 | % Let x = [K(:);b(:);W(:)], we compute 12 | % 13 | % E(x) = E(W*Z,C), where Z = ResNetForward(Kb,Y0) 14 | % 15 | % Inputs: 16 | % 17 | % x - current iterate, x=[K(:);b(:);W(:)] 18 | % Y - input features 19 | % C - class probabilities 20 | % nKb - number of network parameters 21 | % paramResnet- param type for ResNet 22 | % paramReg - struct, parameter describing regularizer 23 | % 24 | % Output: 25 | % 26 | % Ec - current value of loss function 27 | % dE - gradient w.r.t. K,b,W, vector 28 | % H - approximate Hessian, H=J'*d2ES*J, function_handle 29 | function [Ec,dE,H] = ResNetObjFun(x,Y,C,nKb,paramResnet,paramReg) 30 | 31 | 32 | if nargin==0 33 | exResNet_Peaks 34 | return; 35 | end 36 | 37 | [nf,nex] = size(Y); 38 | nc = size(C,1); 39 | 40 | % split x into K,b,W 41 | x = x(:); 42 | Kb = x(1:nKb); 43 | W = reshape(x(nKb+1:end),[],nc); 44 | 45 | % evaluate layer 46 | [Z,Yall,dA] = ResNetForward(Kb,Y,paramResnet); 47 | 48 | % call cross entropy 49 | [Ec,dEW,d2EW,dEZ,d2EZ] = softMax(W,Z,C); 50 | 51 | % add regularizer 52 | if not(exist('paramReg','var')) || not(isstruct(paramReg)) 53 | dS = 0; d2S = @(x) 0; 54 | else 55 | [Sc,dS,d2S] = genTikhonov(x,paramReg); 56 | Ec = Ec + Sc; 57 | end 58 | 59 | if nargout>1 60 | [dEK,dEb] = dResNetMatVecT(reshape(dEZ,[],nex),Kb,Yall,dA,paramResnet); 61 | dE = [cell2vec(dEK); cell2vec(dEb(:)); dEW(:)] + dS; 62 | end 63 | 64 | H = []; 65 | if nargout>2 66 | H = @(x) HessMat(x,nKb,Yall,dA,Y,d2EW,d2EZ,Kb,d2S,paramResnet); 67 | end 68 | 69 | function Hx = HessMat(x,nKb,Yall,dA,Y,d2EW,d2EZ,Kb,d2S,param) 70 | x = x(:); 71 | dKb = x(1:nKb); 72 | dW = x(nKb+1:end); 73 | 74 | 75 | % compute Jac*x 76 | JKbx = dResNetMatVec(dKb,0*Y,Kb,Yall,dA,param); 77 | tt = d2EZ(JKbx); 78 | [J1,J2] = dResNetMatVecT(reshape(tt,size(JKbx)),Kb,Yall,dA,param); 79 | Hx1 = [cell2vec(J1);cell2vec(J2)]; 80 | 81 | Hx2 = d2EW(dW); 82 | 83 | % stack result 84 | Hx = [Hx1(:); Hx2(:)] + d2S(x); 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /resnet/ResNetVarProObjFun.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ec,dE,H] = ResNetVarProObjFun(x,Y,C,m) 8 | % 9 | % evaluates resnet, solves classification problem, and computes cross entropy, 10 | % gradient and approx. Hessian 11 | % 12 | % Let x = [K(:);b(:)], we compute 13 | % 14 | % E(x) = E(W(x)*Z,C), where Z = ResNetForward(Y0,Kb) 15 | % 16 | % Inputs: 17 | % 18 | % x - current iterate, x=[K(:);b(:);W(:)] 19 | % Y - input features 20 | % C - class probabilities 21 | % nKb - number of network parameters 22 | % paramCl - struct, paramters for newtoncg used to classify 23 | % paramResnet - struct, parameter describing resnet 24 | % paramRegKb - struct, parameter describing regularizer for K and b 25 | % paramRegW - struct, parameter describing regularizer for W 26 | % 27 | % Output: 28 | % 29 | % Ec - current value of loss function 30 | % dE - gradient w.r.t. K,b,W, vector 31 | % H - approximate Hessian, H=J'*d2ES*J, function_handle 32 | function [Ec,dE,H] = ResNetVarProObjFun(x,Y,C,nKb,paramCl,paramResnet,paramRegKb,paramRegW) 33 | if nargin==0 34 | exResNet_PeaksVarPro 35 | return; 36 | end 37 | 38 | [nf,nex] = size(Y); 39 | nc = size(C,1); 40 | 41 | % split x into K,b,W 42 | x = x(:); 43 | Kb = x(1:nKb); 44 | 45 | % evaluate Resnet 46 | [Z,Yall,dA] = ResNetForward(Kb,Y,paramResnet); 47 | 48 | % solve classification problem 49 | if exist('paramRegW','var') 50 | fctn = @(W,varargin) classObjFun(W,Z,C,paramRegW); 51 | else 52 | fctn = @(W,varargin) softMax(W,Z,C); 53 | end 54 | WOpt = newtoncg(fctn,zeros(nc*(size(Z,1)+1),1),paramCl); 55 | 56 | 57 | % call cross entropy 58 | [Ec,dEW,d2EW,dEZ,d2EZ] = softMax(WOpt,Z,C); 59 | 60 | % add regularizer 61 | if not(exist('paramRegKb','var')) || not(isstruct(paramRegKb)) 62 | dS = 0; d2S = @(x) 0; 63 | else 64 | [Sc,dS,d2S] = genTikhonov(x,paramRegKb); 65 | Ec = Ec + Sc; 66 | end 67 | if nargout>1 68 | [dEK,dEb] = dResNetMatVecT(reshape(dEZ,[],nex),Kb,Yall,dA,paramResnet); 69 | dE = [cell2vec(dEK); cell2vec(dEb(:))] + dS; 70 | end 71 | 72 | H = []; 73 | if nargout>2 74 | H = @(x) HessMat(x,nKb,Yall,dA,Y,d2EZ,Kb,d2S,paramResnet); 75 | end 76 | 77 | function Hx = HessMat(x,nKb,Yall,dA,Y,d2EZ,Kb,d2S,param) 78 | x = x(:); 79 | dKb = x(1:nKb); 80 | 81 | 82 | % compute Jac*x 83 | JKbx = dResNetMatVec(dKb,0*Y,Kb,Yall,dA,param); 84 | tt = d2EZ(JKbx); 85 | [J1,J2] = dResNetMatVecT(reshape(tt,size(JKbx)),Kb,Yall,dA,param); 86 | Hx1 = [cell2vec(J1);cell2vec(J2)]; 87 | 88 | 89 | % stack result 90 | Hx = Hx1(:) + d2S(x); 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /resnet/dResNetMatVec.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % dY = dResNetMatVec(dKb,dY,Kb,Yall,dA,param) 8 | % 9 | % computes matrix vector product with Jacobian of ResNet 10 | % 11 | % Inputs: 12 | % 13 | % dKb - vector, perturbation of weights 14 | % dY - matrix, perturbation of input features 15 | % Kb - vector, current weights 16 | % Yall - cell, hidden features 17 | % dA - cell, derivative of activations at all layers 18 | % param - struct, description of ResNet 19 | % 20 | % Outputs: 21 | % 22 | % dY - JKb*dKb + JY*dY 23 | % 24 | % for forward propagation, see ResNetForward.m 25 | 26 | function dY = dResNetMatVec(dKb,dY,Kb,Yall,dA,param) 27 | 28 | 29 | 30 | [K,~] = vec2cellResNet(Kb,param.n); 31 | [dK,db] = vec2cellResNet(dKb,param.n); 32 | 33 | h = param.h; 34 | P = param.P; 35 | N = numel(param.P); 36 | 37 | for j=1:N 38 | dY = P{j}*dY + h*dA{j}.*(dK{j}*Yall{j} + K{j}*dY +db{j}); 39 | end -------------------------------------------------------------------------------- /resnet/dResNetMatVecT.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % dY = dResNetMatVec(dKb,dY,Kb,Yall,dA,param) 8 | % 9 | % computes matrix vector product with Jacobian of ResNet 10 | % 11 | % Inputs: 12 | % 13 | % dY - perturbation of output features 14 | % Kb - current weights 15 | % Yall - hidden features 16 | % dA - derivative of activations at all layers 17 | % param - struct, description of ResNet 18 | % 19 | % Outputs: 20 | % 21 | % dK - cell, derivatives w.r.t. K 22 | % db - cell, derivatives w.r.t. b 23 | % dY - matrix, derivatives w.r.t. input features 24 | % 25 | % for forward propagation, see ResNetForward.m 26 | 27 | function[dK,db,dY] = dResNetMatVecT(dY,Kb,Yall,dA,param) 28 | 29 | 30 | 31 | [K,~] = vec2cellResNet(Kb,param.n); 32 | h = param.h; 33 | P = param.P; 34 | N = numel(param.P); 35 | [dK,db] = deal(cell(N,1)); 36 | 37 | for j=N:-1:1 38 | % get derivatives w.r.t. Kj and bj 39 | dK{j} = h*(dA{j}.*dY) * Yall{j}'; 40 | db{j} = sum(h*(dA{j}.*dY),2); 41 | 42 | % integrate backwards in time 43 | dY = P{j}'*dY + h*K{j}'*(dA{j}.*dY); 44 | end 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_Forward.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Example for forward propagation through a ResNet 8 | % 9 | 10 | clear 11 | param.act = @tanhActivation; 12 | 13 | % Width of each block (including initial conditions) 14 | n = [2;2]*ones(1,1000); 15 | 16 | a = -.001; 17 | for i=1:size(n,2) 18 | if n(1,i) ~= n(2,i) 19 | P{i} = opZero(n(2,i),n(1,i)); 20 | else 21 | P{i} = opEye(n(1,i)); 22 | end 23 | K{i} = [a -.2; .2 a]; 24 | b{i} = zeros(n(2,i),1); 25 | end 26 | N = length(P); 27 | param.P = P; 28 | Y0 = [1;1]; 29 | param.h = 1e-1; 30 | param.n = n; 31 | 32 | Kb = [cell2vec(K); cell2vec(b)]; 33 | 34 | %% Run the NN forward 35 | [Y,Yall] = ResNetForward(Kb,Y0,param); 36 | [Y2,Yall2] = ResNetForward(Kb,-Y0,param); 37 | %% 38 | ya = reshape(cell2vec(Yall),2,[]); 39 | ya2 = reshape(cell2vec(Yall2),2,[]); 40 | figure(1);clf 41 | plot(ya(1,1),ya(2,1),'-or','MarkerSize',20) 42 | hold on 43 | 44 | plot(ya(1,:),ya(2,:),'-r','LineWidth',3) 45 | set(gca,'FontSize',20) 46 | 47 | plot(ya2(1,1),ya2(2,1),'-ob','MarkerSize',20) 48 | hold on 49 | 50 | plot(ya2(1,:),ya2(2,:),'-b','LineWidth',3) 51 | set(gca,'FontSize',20) -------------------------------------------------------------------------------- /resnet/examples/EResNet_PeaksNewtonCG.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Training a ResNet for solving the Peaks example 8 | % 9 | 10 | clear all; 11 | rng(2) 12 | [Y,C] = setupPeaks(1000); 13 | fig = figure(1); 14 | fig.Name = 'exResNet_Peaks: True function'; 15 | 16 | %% choose an activation function 17 | paramResnet.act = @sinActivation; 18 | % param.act = @tanhActivation; 19 | % param.act = @reluActivation; 20 | 21 | %% parameters for the ResNet 22 | nc = 8; % width of the ResNet 23 | T = 4; % final time of the ResNet 24 | nt = 16; % number of layers 25 | 26 | %% set this flag to true to initialize the ResNet with an 27 | % anti-symmetric weight matrix for which forward Euler is uncoditionally 28 | % unstable. 29 | startUnstable = false; 30 | 31 | %% build the description of the ResNet (i.e., specify P for each layer) and 32 | % initialize the weights (i.e., K and b) 33 | n = nc*ones(2,nt); 34 | n(1)=2; 35 | for i=1:size(n,2) 36 | if i<3 37 | Ki = randn(n(2,i),n(1,i))/sqrt(prod(n(:,i))); 38 | end 39 | if i>1 && startUnstable 40 | Ki = Ki-Ki'; 41 | end 42 | K{i} = Ki; 43 | if n(1,i) ~= n(2,i) 44 | P{i} = opZero(n(2,i),n(1,i)); 45 | else 46 | P{i} = opEye(n(1,i)); 47 | end 48 | b{i} = zeros(n(2,i),1); 49 | end 50 | N = length(P); 51 | paramResnet.P = P; 52 | paramResnet.h= T/nt; 53 | paramResnet.n = n; 54 | 55 | %% train the network 56 | Kb = [cell2vec(K); cell2vec(b)]; 57 | W = randn((n(end,end)+1)*size(C,1),1); 58 | x0 = [Kb;W]; 59 | 60 | %% specify regularizer 61 | LKb = speye(numel(Kb)); 62 | LW = speye(numel(W)); 63 | paramReg.L = blkdiag(LKb,LW); 64 | paramReg.lambda = 1e-5; 65 | 66 | fctn = @(x,varargin) ResNetObjFun(x,Y,C,numel(Kb),paramResnet,paramReg); 67 | 68 | paramOpt = struct('maxIter',50,'maxStep',.1); 69 | xsol = newtoncg(fctn,x0,paramOpt); 70 | 71 | %% show results 72 | x = linspace(-3,3,201); 73 | [Xg,Yg] = ndgrid(x); 74 | 75 | KbOpt = xsol(1:numel(Kb)); 76 | WOpt = reshape(xsol(numel(Kb)+1:end),size(C,1),[]); 77 | [Yo,~,Yall] = ResNetForward(KbOpt,[Xg(:)';Yg(:)'],paramResnet); 78 | Z = WOpt*padarray(Yo,[1 0],1,'post'); 79 | h = exp(Z)./sum(exp(Z),1); 80 | 81 | [~,ind] = max(h,[],1); 82 | Cpred = zeros(5,numel(Xg)); 83 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 84 | Cpred(Ind) = 1; 85 | img = reshape((1:5)*Cpred,size(Xg)); 86 | 87 | fig= figure(2); clf 88 | fig.Name = 'exResNet_Peaks: Results'; 89 | imagesc(x,x,img') 90 | 91 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_PeaksSGD.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Training a ResNet for solving the Peaks example 8 | % 9 | 10 | clear all; 11 | rng(2) 12 | [Y,C] = setupPeaks(1000); 13 | fig = figure(1); 14 | fig.Name = 'exResNet_Peaks: True function'; 15 | 16 | %% choose an activation function 17 | paramResnet.act = @sinActivation; 18 | % param.act = @tanhActivation; 19 | % param.act = @reluActivation; 20 | 21 | %% parameters for the ResNet 22 | nc = 8; % width of the ResNet 23 | T = 4; % final time of the ResNet 24 | nt = 16; % number of layers 25 | 26 | %% set this flag to true to initialize the ResNet with an 27 | % anti-symmetric weight matrix for which forward Euler is uncoditionally 28 | % unstable. 29 | startUnstable = false; 30 | 31 | %% build the description of the ResNet (i.e., specify P for each layer) and 32 | % initialize the weights (i.e., K and b) 33 | n = nc*ones(2,nt); 34 | n(1)=2; 35 | for i=1:size(n,2) 36 | if i<3 37 | Ki = randn(n(2,i),n(1,i))/sqrt(prod(n(:,i))); 38 | end 39 | if i>1 && startUnstable 40 | Ki = Ki-Ki'; 41 | end 42 | K{i} = Ki; 43 | if n(1,i) ~= n(2,i) 44 | P{i} = opZero(n(2,i),n(1,i)); 45 | else 46 | P{i} = opEye(n(1,i)); 47 | end 48 | b{i} = zeros(n(2,i),1); 49 | end 50 | N = length(P); 51 | paramResnet.P = P; 52 | paramResnet.h= T/nt; 53 | paramResnet.n = n; 54 | 55 | %% train the network 56 | Kb = [cell2vec(K); cell2vec(b)]; 57 | W = randn((n(end,end)+1)*size(C,1),1); 58 | x0 = [Kb;W]; 59 | 60 | %% specify regularizer 61 | LKb = speye(numel(Kb)); 62 | LW = speye(numel(W)); 63 | paramReg.L = blkdiag(LKb,LW); 64 | paramReg.lambda = 1e-5; 65 | 66 | fctn = @(x,varargin) ResNetObjFun(x,Y,C,numel(Kb),paramResnet,paramReg); 67 | 68 | 69 | param.lr = 1e-1*ones(50,1); 70 | param.n = size(Y,2); 71 | param.batchSize = 40; 72 | param.momentum=0.0; 73 | 74 | xsol = sgd(fctn,x0,param); 75 | %% show results 76 | x = linspace(-3,3,201); 77 | [Xg,Yg] = ndgrid(x); 78 | 79 | KbOpt = xsol(1:numel(Kb)); 80 | WOpt = reshape(xsol(numel(Kb)+1:end),size(C,1),[]); 81 | [Yo,~,Yall] = ResNetForward(KbOpt,[Xg(:)';Yg(:)'],paramResnet); 82 | Z = WOpt*padarray(Yo,[1 0],1,'post'); 83 | h = exp(Z)./sum(exp(Z),1); 84 | 85 | [~,ind] = max(h,[],1); 86 | Cpred = zeros(5,numel(Xg)); 87 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 88 | Cpred(Ind) = 1; 89 | img = reshape((1:5)*Cpred,size(Xg)); 90 | 91 | fig= figure(2); clf 92 | fig.Name = 'exResNet_Peaks: Results'; 93 | imagesc(x,x,img') 94 | 95 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_PeaksVarPro.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Training a ResNet for solving the Peaks example 8 | % 9 | 10 | clear all; 11 | rng(2) 12 | [Y,C] = setupPeaks(1000); 13 | fig = figure(1); 14 | fig.Name = 'exResNet_Peaks: True function'; 15 | 16 | %% choose an activation function 17 | paramResnet.act = @sinActivation; 18 | % param.act = @tanhActivation; 19 | % param.act = @reluActivation; 20 | 21 | %% parameters for the ResNet 22 | nc = 8; % width of the ResNet 23 | T = 4; % final time of the ResNet 24 | nt = 16; % number of layers 25 | 26 | %% set this flag to true to initialize the ResNet with an 27 | % anti-symmetric weight matrix for which forward Euler is uncoditionally 28 | % unstable. 29 | startUnstable = false; 30 | 31 | %% build the description of the ResNet (i.e., specify P for each layer) and 32 | % initialize the weights (i.e., K and b) 33 | n = nc*ones(2,nt); 34 | n(1)=2; 35 | for i=1:size(n,2) 36 | if i<3 37 | Ki = randn(n(2,i),n(1,i))/sqrt(prod(n(:,i))); 38 | end 39 | if i>1 && startUnstable 40 | Ki = Ki-Ki'; 41 | end 42 | K{i} = Ki; 43 | if n(1,i) ~= n(2,i) 44 | P{i} = opZero(n(2,i),n(1,i)); 45 | else 46 | P{i} = opEye(n(1,i)); 47 | end 48 | b{i} = zeros(n(2,i),1); 49 | end 50 | N = length(P); 51 | paramResnet.P = P; 52 | paramResnet.h= T/nt; 53 | paramResnet.n = n; 54 | 55 | %% train the network 56 | Kb = [cell2vec(K); cell2vec(b)]; 57 | W = randn((n(end,end)+1)*size(C,1),1); 58 | x0 = Kb; 59 | 60 | %% specify regularizer 61 | LKb = speye(numel(Kb)); 62 | LW = speye(numel(W)); 63 | paramRegKb = struct('L',LKb,'lambda',1e-5); 64 | paramRegW = struct('L',LW,'lambda',1e-3); 65 | paramCl = struct('maxIter',5,'maxStep',.1,'out',0); 66 | 67 | fctn = @(x,varargin) ResNetVarProObjFun(x,Y,C,numel(Kb),paramCl,paramResnet,paramRegKb,paramRegW); 68 | 69 | paramOpt = struct('maxIter',50,'maxStep',.1); 70 | KbOpt = newtoncg(fctn,x0,paramOpt); 71 | %% 72 | YN = ResNetForward(KbOpt,Y,paramResnet); 73 | fctn = @(W,varargin) classObjFun(W,YN,C,paramRegW); 74 | WOpt = newtoncg(fctn,0*W,paramCl); 75 | 76 | %% show results 77 | x = linspace(-3,3,201); 78 | [Xg,Yg] = ndgrid(x); 79 | 80 | 81 | WOpt = reshape(WOpt,size(C,1),[]); 82 | [Yo,~,Yall] = ResNetForward(KbOpt,[Xg(:)';Yg(:)'],paramResnet); 83 | Z = WOpt*padarray(Yo,[1 0],1,'post'); 84 | h = exp(Z)./sum(exp(Z),1); 85 | 86 | [~,ind] = max(h,[],1); 87 | Cpred = zeros(5,numel(Xg)); 88 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 89 | Cpred(Ind) = 1; 90 | img = reshape((1:5)*Cpred,size(Xg)); 91 | 92 | fig= figure(2); clf 93 | fig.Name = 'exResNet_Peaks: Results'; 94 | imagesc(x,x,img') 95 | 96 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_Stability.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % demonstrating the importance of stability for a simple ResNet 8 | % 9 | 10 | close all; clear all; clc; 11 | 12 | model = 'M-matrix'; 13 | % activation = @(x) max(x,0); 14 | activation = @(x) tanh(x); 15 | 16 | switch model 17 | case 'M-matrix' 18 | getK = @(th) -eye(3)*sum(th)-[0 -th(1) -th(2); -th(2) 0 -th(1); -th(1) -th(2) 0]; 19 | end 20 | 21 | N = [5 100 200]; % number of time steps for coarse, fine, and true 22 | T = 10; 23 | h = T./N; 24 | nex = 20; 25 | Y0 = .1*randn(3,nex); % training 26 | Y0t = .1*randn(3,nex); % test 27 | nth = 101; % number of cells for objective functions 28 | %% get true labels 29 | K = getK([1;1]); 30 | C = Y0; Ct = Y0t; 31 | for j=1:N(3) 32 | C = C + h(3)*activation(K*C); 33 | Ct = Ct + h(3)*activation(K*Ct); 34 | end 35 | 36 | %% compute misfit with few time steps 37 | th = linspace(0.2,2,nth); 38 | Phic = zeros(nth,nth); 39 | Phict = zeros(nth,nth); 40 | for k1=1:nth 41 | for k2=1:nth 42 | Cpred = Y0; 43 | Cpredt = Y0t; 44 | K = getK([th(k1);th(k2)]); 45 | for j=1:N(1) 46 | Cpred = Cpred + h(1)*activation(K*Cpred); 47 | Cpredt = Cpredt + h(1)*activation(K*Cpredt); 48 | end 49 | Phic(k1,k2) = 0.5*norm(Cpred-C,'fro')^2; 50 | Phict(k1,k2) = 0.5*norm(Cpredt-Ct,'fro')^2; 51 | end 52 | end 53 | %% 54 | figure(1); clf; 55 | subplot(2,3,1); 56 | contour(th,th,Phic,100); 57 | hold on; 58 | plot(1,1,'.r','MarkerSize',20); 59 | title(sprintf('objective, h=%1.2f',h(1))); 60 | ylabel('few time steps') 61 | subplot(2,3,2); 62 | contour(th,th,Phict,100); 63 | hold on; 64 | plot(1,1,'.r','MarkerSize',20); 65 | title(sprintf('objective (test), h=%1.2f',h(1))); 66 | subplot(2,3,3); 67 | imagesc(th,th,flipud(abs(Phic-Phict)')); 68 | title(sprintf('abs. diff, h=%1.2f',h(1))); 69 | colorbar 70 | 71 | %% compute misfit with many time steps 72 | Phif = zeros(nth,nth); 73 | Phift = zeros(nth,nth); 74 | for k1=1:nth 75 | for k2=1:nth 76 | Cpred = Y0; 77 | Cpredt = Y0t; 78 | K = getK([th(k1);th(k2)]); 79 | for j=1:N(2) 80 | Cpred = Cpred + h(2)*activation(K*Cpred); 81 | Cpredt = Cpredt + h(2)*activation(K*Cpredt); 82 | end 83 | Phif(k1,k2) = 0.5*norm(Cpred-C,'fro')^2; 84 | Phift(k1,k2) = 0.5*norm(Cpredt-Ct,'fro')^2; 85 | end 86 | end 87 | %% 88 | subplot(2,3,4); 89 | contour(th,th,Phif,100); 90 | hold on; 91 | plot(1,1,'.r','MarkerSize',20); 92 | title(sprintf('objective, h=%1.2f',h(2))); 93 | ylabel('many time steps') 94 | 95 | subplot(2,3,5); 96 | contour(th,th,Phift,100); 97 | hold on; 98 | plot(1,1,'.r','MarkerSize',20); 99 | title(sprintf('objective (test), h=%1.2f',h(2))); 100 | subplot(2,3,6); 101 | imagesc(th,th,flipud(abs(Phif-Phift)')); 102 | title(sprintf('abs. diff, h=%1.2f',h(2))); 103 | colorbar 104 | 105 | return 106 | %% for printing figures; 107 | fig = figure(10); clf; 108 | fig.Name = 'Phic'; 109 | contour(th,flipud(th),Phic,100,'LineWidth',2); 110 | hold on; 111 | plot(1,1,'.r','MarkerSize',40); 112 | 113 | fig = figure(11); clf; 114 | fig.Name = 'Phict'; 115 | contour(th,flipud(th),Phict,100,'LineWidth',2); 116 | hold on; 117 | plot(1,1,'.r','MarkerSize',40); 118 | 119 | fig = figure(12); clf; 120 | fig.Name = 'Phic-Phict'; 121 | diffc = abs(Phic-Phict); 122 | imagesc(th,th,(diffc')); 123 | axis xy 124 | cb = colorbar 125 | cb.Ticks = [min(diffc(:)) max(diffc(:))]; 126 | axis square 127 | cb.Position =[0.8405 0.1095 0.02 0.7155] 128 | 129 | fig = figure(13); clf; 130 | fig.Name = 'Phif'; 131 | contour(th,flipud(th),Phif,100,'LineWidth',2); 132 | hold on; 133 | plot(1,1,'.r','MarkerSize',40); 134 | 135 | fig = figure(14); clf; 136 | fig.Name = 'Phift'; 137 | contour(th,flipud(th),Phift,100,'LineWidth',2); 138 | hold on; 139 | plot(1,1,'.r','MarkerSize',40); 140 | 141 | fig = figure(15); clf; 142 | fig.Name = 'Phif-Phift'; 143 | difff = abs(Phif-Phift); 144 | imagesc(th,th,difff'); 145 | axis xy 146 | cb = colorbar 147 | cb.Ticks = [min(difff(:)) max(difff(:))]; 148 | axis square 149 | cb.Position =[0.8405 0.1095 0.02 0.7155] 150 | %% 151 | for k=10:15 152 | fig = figure(k); 153 | set(gca,'FontSize',30); 154 | axis square 155 | set(gca,'XTick',[min(th) max(th)],'YTick',[ min(th) max(th)]) 156 | printFigure(gcf,[fig.Name '.png'],'printOpts','-dpng','printFormat','.png'); 157 | end 158 | 159 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_TestDerivative.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % test derivative of ResNet forward propagation using Peaks example 8 | % 9 | 10 | clear 11 | param.act = @smoothRelU; 12 | 13 | % Width of each block (including initial conditions) 14 | n = [2 5 5 5 5 10; ... 15 | 5 5 5 5 10 3]; 16 | 17 | for i=1:size(n,2) 18 | if n(1,i) ~= n(2,i) 19 | P{i} = opZero(n(2,i),n(1,i)); 20 | else 21 | P{i} = opEye(n(1,i)); 22 | end 23 | K{i} = randn(n(2,i),n(1,i)); 24 | b{i} = randn(n(2,i),1); 25 | end 26 | N = length(P); 27 | param.P = P; 28 | param.h=1; 29 | param.n = n; 30 | Y0 = randn(2,100); 31 | Kb = [cell2vec(K); cell2vec(b)]; 32 | %% Run the NN forward 33 | [Y,Yall,dA] = ResNetForward(Kb,Y0,param); 34 | dY0 = randn(size(Y0)); 35 | dKb = randn(size(Kb)); 36 | dY = dResNetMatVec(dKb,dY0,Kb,Yall,dA,param); 37 | 38 | fprintf('=== Derivative test ========================\n') 39 | for k=1:10 40 | h = 10^(-k); 41 | 42 | Y1 = ResNetForward(Kb+h*dKb,Y0+h*dY0,param); 43 | 44 | 45 | fprintf('%3.2e %3.2e %3.2e\n',h,norm(Y1(:)-Y(:)), norm(Y1(:)-Y(:)-h*dY(:))) 46 | end 47 | %% 48 | 49 | fprintf('=== Adjoint test ========================\n') 50 | dZ = dResNetMatVec(dKb,dY0,Kb,Yall,dA,param); 51 | 52 | dW = randn(size(dZ)); 53 | t1 = dZ(:)'*dW(:); 54 | 55 | [dK1,db1,dY1] = dResNetMatVecT(dW,Kb,Yall,dA,param); 56 | 57 | tt = [cell2vec(dK1); cell2vec(db1)]; 58 | 59 | t2 = tt'*dKb + dot(dY1(:),dY0(:)) ; 60 | fprintf('%3.2e %3.2e\n',t1,t2) 61 | -------------------------------------------------------------------------------- /resnet/examples/EResNet_TestObjective.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % test derivative of ResNet objective function using Peaks example 8 | % 9 | 10 | clear all; 11 | [Y,C] = setupPeaks(); 12 | 13 | %% 14 | param.act = @smoothRelU; 15 | % Width of each block (including initial conditions) 16 | n = [2 5 5 5 5 10; ... 17 | 5 5 5 5 10 3]; 18 | 19 | for i=1:size(n,2) 20 | if n(1,i) ~= n(2,i) 21 | P{i} = opZero(n(2,i),n(1,i)); 22 | else 23 | P{i} = opEye(n(1,i)); 24 | end 25 | K{i} = randn(n(2,i),n(1,i)); 26 | b{i} = randn(n(2,i),1); 27 | end 28 | N = length(P); 29 | param.P = P; 30 | param.h=1; 31 | param.n = n; 32 | Y0 = randn(2,100); 33 | %% Run the NN forward 34 | Kb = [cell2vec(K); cell2vec(b)]; 35 | W = randn((n(end,end)+1)*size(C,1),1); 36 | x0 = [Kb;W]; 37 | [Ec,dE,H] = ResNetObjFun(x0,Y,C,numel(Kb),param); 38 | 39 | dx = randn(size(x0)); 40 | dEdx = dot(dE,dx); 41 | for k=1:10 42 | h = 10^(-k); 43 | Et = ResNetObjFun(x0+h*dx,Y,C,numel(Kb),param); 44 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\n',h,abs(Ec-Et),abs(Et-Ec-h*dEdx)); 45 | end 46 | -------------------------------------------------------------------------------- /resnet/examples/EReseNet_vs_NeuralNet.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Compare objective function and gradient for ResNet and Neural Net 8 | % 9 | clear 10 | rng(12) 11 | param.act = @tanhActivation; 12 | 13 | % Width of each block (including initial conditions) 14 | n = [5 5 5 5 5 5; ... 15 | 5 5 5 5 5 5]; 16 | n=n/5*4 17 | n(end)=1 18 | 19 | for i=1:size(n,2) 20 | P{i} = opZero(n(2,i),n(1,i)); 21 | K{i} = .2*randn(n(2,i),n(1,i)); 22 | Kt{i} = .2*randn(n(2,i),n(1,i)); 23 | if n(1,i) == n(2,i) 24 | % K{i} = K{i}-K{i}'; 25 | % Kt{i} = Kt{i}-Kt{i}'; 26 | end 27 | b{i} = 0*randn(n(2,i),1); 28 | end 29 | N = length(P); 30 | param.P = P; 31 | param.h=1; 32 | param.n = n; 33 | Y0 = randn(n(1),100); 34 | Kb = [cell2vec(K); cell2vec(b)]; 35 | Kbt = [cell2vec(Kt); cell2vec(b)]; 36 | %% Run the NN forward 37 | [Y,Yall,dA] = ResNetForward(Kb,Y0,param); 38 | 39 | 40 | C = ResNetForward(Kbt,Y0,param); 41 | 42 | res = Y-C; 43 | Jc = norm(Y-C,'fro')/norm(C,'fro'); 44 | [dJdK,dJdb,dJdY] = dResNetMatVecT(res,Kb,Yall,dA,param); 45 | 46 | dJ = [cell2vec(dJdK); ]; 47 | fig = figure(1);clf 48 | fig.Name = 'dJ-NN' 49 | % subplot(1,2,1) 50 | histogram(dJ/norm(C,'fro'),100) 51 | 52 | %% 53 | fig = figure(2);clf 54 | fig.Name = 'obj-NN' 55 | h = linspace(-.1,1,500); 56 | f1 = 0*h; 57 | for k=1:numel(h) 58 | [Yt,Yall,dA] = ResNetForward(h(k)*Kb+(1-h(k))*Kbt,Y0,param); 59 | rest = Yt-C; 60 | f1(k) = norm(rest,'fro')/norm(C,'fro'); 61 | end 62 | plot(h,f1,'linewidth',3) 63 | xlabel('t') 64 | 65 | %% 66 | for i=1:size(n,2) 67 | if n(1,i) ~= n(2,i) 68 | P{i} = opZero(n(2,i),n(1,i)); 69 | else 70 | P{i} = opEye(n(1,i)); 71 | end 72 | end 73 | param.P = P; 74 | 75 | [Y2,Yall2,dA2] = ResNetForward(Kb,Y0,param); 76 | 77 | C = ResNetForward(Kbt,Y0,param); 78 | 79 | res2 = Y2-C; 80 | Jc2 = norm(res2,'fro')/norm(C,'fro'); 81 | [dJdK,dJdb,dJdY] = dResNetMatVecT(res2,Kb,Yall2,dA2,param); 82 | 83 | fig = figure(3);clf 84 | fig.Name = 'dJ-Res' 85 | dJ2 = [cell2vec(dJdK);]; 86 | histogram(dJ2/norm(C,'fro'),100) 87 | %% 88 | fig = figure(4);clf 89 | fig.Name = 'obj-Res' 90 | h = linspace(-.1,1,500); 91 | f2 = 0*h; 92 | for k=1:numel(h) 93 | [Yt,Yall,dA] = ResNetForward(h(k)*Kb+(1-h(k))*Kbt,Y0,param); 94 | rest = Yt-C; 95 | f2(k) = norm(rest,'fro')/norm(C,'fro'); 96 | end 97 | plot(h,f2,'linewidth',3) 98 | xlabel('t') 99 | 100 | %% 101 | figDir = '/Users/lruthot/Dropbox/Projects/NumDL-CourseNotes/images/' 102 | for k=1:4 103 | fig=figure(k); 104 | set(gca,'FontSize',30) 105 | axis square 106 | xlabel([]) 107 | printFigure(gcf,fullfile(figDir,['NNvsResNN_' fig.Name '.png'])) 108 | 109 | end 110 | 111 | -------------------------------------------------------------------------------- /resnet/vec2cellResNet.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [K,b] = vec2cellResNet(v,n) 8 | % 9 | % splits vector v into cell arrays associated with K{j} and b{j} in 10 | % ResNetForward. 11 | % 12 | % Inputs: 13 | % 14 | % v - weight vector 15 | % n - descriptions of kernel size in each layer 16 | % 17 | % Outputs: 18 | % 19 | % K,b - cell arrays of weights. 20 | 21 | function [K,b] = vec2cellResNet(v,n) 22 | 23 | nt = size(n,2); 24 | cnt = 0; 25 | 26 | K = cell(nt,1); 27 | b = cell(nt,1); 28 | 29 | % first get the Ks 30 | for k=1:nt 31 | nk = prod(n(:,k)); 32 | K{k} = reshape( v(cnt+(1:nk)), n(2,k),n(1,k)); 33 | cnt = cnt + nk; 34 | end 35 | 36 | % now get the bs 37 | for k=1:nt 38 | nb = n(end,k); 39 | b{k} = v(cnt+(1:nb)); 40 | cnt = cnt + nb; 41 | end 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /singleLayer/examples/ESingleLayer_PeaksNewtonCG.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Training a single layer neural network for Peaks example 8 | % 9 | % Here we optimize the coupled objective function first with steepest 10 | % descent and then with newtoncg. Compare this example with 11 | % ESingleLayer_PeaksVarPro 12 | % 13 | clear; 14 | rng(2) 15 | 16 | %% get peaks data 17 | np = 1000; % num of points sampled 18 | nc = 5; % num of classes 19 | ns = 256; % length of grid 20 | 21 | [Y, C] = setupPeaks(np, nc, ns); 22 | [Yv, Cv] = setupPeaks(2000, nc, ns); 23 | 24 | nf = size(Y,1); 25 | nc = size(C,1); 26 | %% optimize 27 | m = 40; 28 | K0 = randn(m,nf); 29 | b0 = randn(1); 30 | W0 = randn(nc,m+1); 31 | 32 | 33 | %% optimize 34 | paramReg = struct('L',1,'lambda',1e-4,'nc',1); 35 | paramSL = struct('act',@sinActivation); 36 | fctn = @(x,varargin) singleLayerNNObjFun(x,Y,C,m,paramSL,paramReg); 37 | x0 = [K0(:); b0(:); W0(:)]; 38 | 39 | param = struct('maxIter',500,'maxStep',1); 40 | x0 = steepestDescent(fctn,x0,param); 41 | %% 42 | param = struct('maxIter',50,'maxStep',1,'tolCG',1e-6,'maxIterCG',200); 43 | xOpt = newtoncg(fctn,x0(:),param); 44 | %% 45 | 46 | KOpt = reshape(xOpt(1:m*nf),m,nf); 47 | bOpt = xOpt(m*nf+1); 48 | WOpt = reshape(xOpt(m*nf+2:end),nc,[]); 49 | %% 50 | 51 | St = WOpt*padarray(singleLayer(KOpt,bOpt,Y,paramSL),[1 0],1,'post'); 52 | Sv = WOpt*padarray(singleLayer(KOpt,bOpt,Yv,paramSL),[1 0],1,'post'); 53 | htrain = exp(St)./sum(exp(St),1); 54 | h = exp(Sv)./sum(exp(Sv),1); 55 | 56 | % Find the largesr entry at each row 57 | [~,ind] = max(h,[],1); 58 | Cvpred = zeros(size(Cv)); 59 | Ind = sub2ind(size(Cvpred),ind,1:size(Cvpred,2)); 60 | Cvpred(Ind) = 1; 61 | [~,ind] = max(htrain,[],1); 62 | Cpred = zeros(size(C)); 63 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 64 | Cpred(Ind) = 1; 65 | 66 | trainErr = 100*nnz(abs(C-Cpred))/2/nnz(C); 67 | valErr = 100*nnz(abs(Cv-Cvpred))/2/nnz(Cv); 68 | 69 | %% 70 | x = linspace(-3,3,201); 71 | [Xg,Yg] = ndgrid(x); 72 | Z = WOpt*[singleLayer(KOpt,bOpt,[Xg(:)';Yg(:)'],paramSL); ones(1,numel(Xg))]; 73 | h = exp(Z)./sum(exp(Z),1); 74 | 75 | [~,ind] = max(h,[],1); 76 | Cpred = zeros(5,numel(Xg)); 77 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 78 | Cpred(Ind) = 1; 79 | img = reshape((1:5)*Cpred,size(Xg)); 80 | %% 81 | figure(2);clf 82 | imagesc(x,x,img') 83 | title(sprintf('training error %1.2f%% validation error %1.2f%%',trainErr,valErr)); 84 | 85 | 86 | -------------------------------------------------------------------------------- /singleLayer/examples/ESingleLayer_PeaksSGD.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % Training a single layer neural network for Peaks example 8 | % 9 | % Here we optimize the coupled objective function first with steepest 10 | % descent and then with newtoncg. Compare this example with 11 | % ESingleLayer_PeaksVarPro 12 | % 13 | clear; 14 | rng(2) 15 | %% get peaks data 16 | np = 1000; % num of points sampled 17 | nc = 5; % num of classes 18 | ns = 256; % length of grid 19 | 20 | [Y, C] = setupPeaks(np, nc, ns); 21 | [Yv, Cv] = setupPeaks(2000, nc, ns); 22 | 23 | nf = size(Y,1); 24 | nc = size(C,1); 25 | %% optimize 26 | m = 40; 27 | K0 = randn(m,nf); 28 | b0 = randn(1); 29 | W0 = randn(nc,m+1); 30 | 31 | 32 | %% optimize 33 | paramReg = struct('L',1,'lambda',1e-4,'nc',1); 34 | paramSL = struct('act',@sinActivation); 35 | fctn = @(x,varargin) singleLayerNNObjFun(x,Y,C,m,paramSL,paramReg); 36 | x0 = [K0(:); b0(:); W0(:)]; 37 | 38 | param.lr = 1e0*ones(50,1); 39 | param.n = size(Y,2); 40 | param.batchSize = 2; 41 | param.momentum=0.0; 42 | 43 | xOpt = sgd(fctn,x0,param); 44 | %% 45 | %% 46 | 47 | KOpt = reshape(xOpt(1:m*nf),m,nf); 48 | bOpt = xOpt(m*nf+1); 49 | WOpt = reshape(xOpt(m*nf+2:end),nc,[]); 50 | %% 51 | 52 | St = WOpt*padarray(singleLayer(KOpt,bOpt,Y,paramSL),[1 0],1,'post'); 53 | Sv = WOpt*padarray(singleLayer(KOpt,bOpt,Yv,paramSL),[1 0],1,'post'); 54 | htrain = exp(St)./sum(exp(St),1); 55 | h = exp(Sv)./sum(exp(Sv),1); 56 | 57 | % Find the largesr entry at each row 58 | [~,ind] = max(h,[],1); 59 | Cvpred = zeros(size(Cv)); 60 | Ind = sub2ind(size(Cvpred),ind,1:size(Cvpred,2)); 61 | Cvpred(Ind) = 1; 62 | [~,ind] = max(htrain,[],1); 63 | Cpred = zeros(size(C)); 64 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 65 | Cpred(Ind) = 1; 66 | 67 | trainErr = 100*nnz(abs(C-Cpred))/2/nnz(C); 68 | valErr = 100*nnz(abs(Cv-Cvpred))/2/nnz(Cv); 69 | 70 | %% 71 | x = linspace(-3,3,201); 72 | [Xg,Yg] = ndgrid(x); 73 | Z = WOpt*[singleLayer(KOpt,bOpt,[Xg(:)';Yg(:)'],paramSL); ones(1,numel(Xg))]; 74 | h = exp(Z)./sum(exp(Z),1); 75 | 76 | [~,ind] = max(h,[],1); 77 | Cpred = zeros(5,numel(Xg)); 78 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 79 | Cpred(Ind) = 1; 80 | img = reshape((1:5)*Cpred,size(Xg)); 81 | %% 82 | figure(2);clf 83 | imagesc(x,x,img') 84 | title(sprintf('training error %1.2f%% validation error %1.2f%%',trainErr,valErr)); 85 | 86 | 87 | -------------------------------------------------------------------------------- /singleLayer/examples/ESingleLayer_PeaksVarPro.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classification example for peaks data using single layer neural network. 8 | % Here we use VarPro to solve the coupled optimization problem. Compare 9 | % this with ESingleLayer_PeaksNewtonCG 10 | 11 | clear; 12 | rng(2) 13 | 14 | %% get peaks data 15 | np = 1000; % num of points sampled 16 | nc = 5; % num of classes 17 | ns = 256; % length of grid 18 | 19 | [Y, C] = setupPeaks(np, nc, ns); 20 | [Yv, Cv] = setupPeaks(2000, nc, ns); 21 | [Yv, Cv] = setupPeaks(2000, nc, ns); 22 | 23 | 24 | nf = size(Y,1); 25 | nc = size(C,1); 26 | %% optimize 27 | % m = 640/20; 28 | m = 40; 29 | K0 = randn(m,nf); 30 | b0 = randn(1); 31 | act = @tanhActivation; 32 | 33 | 34 | %% optimize 35 | paramCl = struct('maxIter',20,'tolCG',1e-5,'maxIterCG',30,'out',-1); 36 | paramSL = struct('act',act); 37 | paramRegW = struct('L',1,'lambda',1e-10); 38 | fctn = @(x,varargin) singleLayerNNVarProObjFun(x,Y,C,m,paramCl,paramSL,[],paramRegW); 39 | x0 = [K0(:); b0(:);]; 40 | 41 | %% use steepest descent to get a starting guess 42 | param = struct('maxIter',10,'maxStep',1); 43 | x0 = steepestDescent(fctn,x0,param); 44 | %% switch to newtoncg 45 | param = struct('maxIter',20,'tolCG',1e-6,'maxIterCG',10); 46 | xOpt = newtoncg(fctn,x0(:),param); 47 | 48 | %% 49 | KOpt = reshape(xOpt(1:m*nf),m,nf); 50 | bOpt = xOpt(m*nf+1); 51 | Z = singleLayer(KOpt,bOpt,Y,paramSL); 52 | fcl = @(W,varargin) softMax(W,Z,C); 53 | WOpt = newtoncg(fcl,zeros(nc*(m+1),1),paramCl); 54 | WOpt = reshape(WOpt,nc,[]); 55 | %% 56 | 57 | St = WOpt*[Z; ones(1,np)]; 58 | Sv = WOpt*[singleLayer(KOpt,bOpt,Yv,paramSL); ones(1,size(Yv,2))]; 59 | htrain = exp(St)./sum(exp(St),1); 60 | h = exp(Sv)./sum(exp(Sv),1); 61 | 62 | % Find the largesr entry at each row 63 | [~,ind] = max(h,[],1); 64 | Cvpred = zeros(size(Cv)); 65 | Ind = sub2ind(size(Cvpred),ind,1:size(Cvpred,2)); 66 | Cvpred(Ind) = 1; 67 | [~,ind] = max(htrain,[],1); 68 | Cpred = zeros(size(C)); 69 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 70 | Cpred(Ind) = 1; 71 | 72 | trainErr = 100*nnz(abs(C-Cpred))/2/nnz(C); 73 | valErr = 100*nnz(abs(Cv-Cvpred))/2/nnz(Cv); 74 | 75 | %% 76 | x = linspace(-3,3,201); 77 | [Xg,Yg] = ndgrid(x); 78 | Z = WOpt*[singleLayer(KOpt,bOpt,[Xg(:)';Yg(:)'],paramSL); ones(1,numel(Xg))]; 79 | h = exp(Z)./sum(exp(Z),1); 80 | 81 | [~,ind] = max(h,[],1); 82 | Cpred = zeros(5,numel(Xg)); 83 | Ind = sub2ind(size(Cpred),ind,1:size(Cpred,2)); 84 | Cpred(Ind) = 1; 85 | img = reshape((1:5)*Cpred,size(Xg)); 86 | %% 87 | figure(2);clf 88 | imagesc(x,x,img') 89 | title(sprintf('train %1.2f%% val %1.2f%%',trainErr,valErr)); 90 | 91 | 92 | -------------------------------------------------------------------------------- /singleLayer/examples/ESingleLayer_PlotObjective.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % plot the loss landscape for the softmax loss and a single layer neural 8 | % network 9 | close all; clear all; clc; 10 | 11 | rng(2) 12 | n = 50; nf = 50; nc = 3; m = 40; 13 | Wtrue = randn(nc,m+1); 14 | Ktrue = randn(m,nf); 15 | btrue = .1; 16 | 17 | Y = randn(nf,n); 18 | Cobs = exp(Wtrue* padarray(singleLayer(Ktrue,btrue,Y),[1 0],1,'post')); 19 | Cobs = Cobs./sum(Cobs,1); 20 | 21 | %% 22 | dW = randn(nc,m+1); 23 | dK = randn(m,nf); 24 | 25 | [tW,tK] = ndgrid(linspace(-1,1,41)); 26 | E = 0*tW; 27 | for i=1:size(tW,1) 28 | for j=1:size(tW,2) 29 | Zt = singleLayer(Ktrue+tK(i,j)*dK,btrue,Y); 30 | E(i,j)=softMax(Wtrue+tW(i,j)*dW,Zt,Cobs); 31 | 32 | end 33 | end 34 | 35 | %% 36 | figure(1); clf; 37 | contour(tW,tK,E,'lineWidth',2) 38 | xlabel('W + tW*dW') 39 | ylabel('K + tK*dK') 40 | set(gca,'FontSize',20) 41 | 42 | %% 43 | figure(2); clf; 44 | surfc(tW,tK,E,'lineWidth',2) 45 | xlabel('W + tW*dW') 46 | ylabel('K + tK*dK') 47 | set(gca,'FontSize',20) -------------------------------------------------------------------------------- /singleLayer/singleConvLayer.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Z,Jthtmv,Jbtmv,JYtmv,Jthmv,Jbmv,JYmv] = singleConvLayer(theta,b,Y,param) 8 | % 9 | % Computes the Z = sigma(K*Y+b) and functions for computing J'*W and J*V 10 | % 11 | % Inputs: 12 | % K - theta, weights for convolution matrix 13 | % b - bias, scalar 14 | % Y - input features, n x nf 15 | % param - struct, description of activation and conv operator 16 | % 17 | % Output: 18 | % Z - transformed features 19 | % Jthtmv - function handle for (J_th Z)'*W 20 | % Jbtmv - function handle for (J_b Z)'*b 21 | % JYtmv - function handle for (J_Y Z)'*Y 22 | % Jthmv - function handle for (J_th Z)*V_K 23 | % Jbmv - function handle for (J_b Z)*V_b 24 | % JYmv - function handle for (J_Y Z)*V_Y 25 | function[Z,Jthtmv,Jbtmv,JYtmv,Jthmv,Jbmv,JYmv] = singleConvLayer(theta,b,Y,param) 26 | 27 | 28 | if nargin==0 29 | runMinimalExample; 30 | return; 31 | end 32 | 33 | if isfield(param,'act') 34 | act = param.act; 35 | else 36 | act = @tanhActivation; 37 | end 38 | kernel = param.kernel; 39 | K = getOp(kernel,theta); 40 | b = reshape(b,1,1,[]); 41 | 42 | 43 | [Z,dA] = act( K*Y+b); 44 | 45 | if nargout>1 46 | szZ = size(Z); 47 | Jthtmv = @(W) JthetaTmv(kernel,reshape(W,szZ).*dA,[],Y); 48 | Jbtmv = @(W) sum(sum(sum(reshape(W,size(dA)).*dA,4),2),1); 49 | JYtmv = @(W) K'*(reshape(W,size(dA)).*dA); 50 | 51 | Jthmv = @(VK) dA .* (reshape(Jmv(VK),m,nf)*Y); 52 | Jbmv = @(Vb) dA .* reshape(Vb,1,1,[]); 53 | szY = size(Y); 54 | JYmv = @(VY) dA .* (K*reshape(VY,szY)); 55 | end 56 | 57 | 58 | function runMinimalExample 59 | 60 | nImg = [18 16]; 61 | sK = [3 3 2 4]; 62 | n = 10; 63 | kernel = convFFT(nImg,sK); 64 | 65 | param = struct('kernel',kernel); 66 | 67 | theta = randn(sK); 68 | Y = randn([nImg sK(3) n]); 69 | b = randn(sK(4),1); 70 | Zt = feval(mfilename,theta,b,Y,param); 71 | 72 | dK = randn(sK); 73 | 74 | tt = linspace(-1,1,51); 75 | tb = linspace(-1,1,31); 76 | for k=1:numel(tt) 77 | for j=1:numel(tb) 78 | F(k,j) = norm(vec(Zt- feval(mfilename,theta+tt(k)*dK,b+tb(j),Y,param))); 79 | end 80 | end 81 | figure(1); clf; 82 | contour(F,'linewidth',2) 83 | xlabel('bias'); 84 | ylabel('kernel'); 85 | set(gca,'fontsize',20) 86 | -------------------------------------------------------------------------------- /singleLayer/singleLayer.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Z,JKtmv,Jbtmv,JYtmv,JKmv,Jbmv,JYmv] = singleLayer(K,b,Y,param) 8 | % 9 | % Computes the Z = sigma(K*Y+b) and functions for computing J'*W and J*V 10 | % 11 | % Inputs: 12 | % K - transformation matrix nf x m 13 | % b - bias, scalar 14 | % Y - input features, n x nf 15 | % 16 | % Output: 17 | % Z - transformed features 18 | % JKtmv - function handle for (J_K Z)'*W 19 | % Jbtmv - function handle for (J_b Z)'*b 20 | % JYtmv - function handle for (J_Y Z)'*Y 21 | % JKmv - function handle for (J_K Z)*V_K 22 | % Jbmv - function handle for (J_b Z)*V_b 23 | % JYmv - function handle for (J_Y Z)*V_Y 24 | 25 | function[Z,JKtmv,Jbtmv,JYtmv,JKmv,Jbmv,JYmv] = singleLayer(K,b,Y,param) 26 | 27 | if nargin==0 28 | runMinimalExample; 29 | return; 30 | end 31 | 32 | [nf,n] = size(Y); 33 | m = size(K,1); 34 | 35 | if exist('param','var') 36 | if isfield(param,'act') 37 | act = param.act; 38 | else 39 | act = param; 40 | end 41 | else 42 | act = @tanhActivation; 43 | end 44 | 45 | [Z,dA] = act( K*Y+b); 46 | 47 | JKtmv = @(W) (reshape(W,m,n).*dA)*Y'; 48 | Jbtmv = @(W) sum(sum(reshape(W,m,n).*dA)); 49 | JYtmv = @(W) K'*(reshape(W,m,n).*dA); 50 | 51 | JKmv = @(VK) dA .* (reshape(VK,m,nf)*Y); 52 | Jbmv = @(Vb) dA .* Vb; 53 | JYmv = @(VY) dA .* (K*reshape(VY,nf,n)); 54 | 55 | function runMinimalExample 56 | 57 | n = 10; 58 | nf = 7; 59 | m = 4; 60 | 61 | K = randn(m,nf); 62 | Y = randn(nf,n); 63 | b = randn(); 64 | Zt = feval(mfilename,K,b,Y); 65 | 66 | dK = randn(m,nf); 67 | 68 | tt = linspace(-1,1,51); 69 | tb = linspace(-1,1,31); 70 | for k=1:numel(tt) 71 | for j=1:numel(tb) 72 | F(k,j) = norm(Zt- feval(mfilename,K+tt(k)*dK,b+tb(j),Y)); 73 | end 74 | end 75 | figure(1); clf; 76 | contour(F,'linewidth',2) 77 | set(gca,'FontSize',20); 78 | xlabel('bias'); 79 | ylabel('kernel'); 80 | -------------------------------------------------------------------------------- /singleLayer/singleLayerAdvObjFun.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ec,dE,H] = singleLayerAdvObjFun(Y,K,b,W,C) 8 | % 9 | % objective function for adversarial training 10 | % 11 | % Inputs: 12 | % 13 | % Y - input features (to be optimized here) 14 | % K - parameters of transformation 15 | % b - weights of bias 16 | % W - weights of classifier 17 | % C - desired class 18 | % paramSL - struct, paramters for single layer 19 | % paramRegKb - struct, parameter describing regularizer for Kb 20 | % 21 | % Outputs: 22 | % 23 | % Ec - loss function 24 | % dE - gradient w.r.t. Y 25 | % H - approx Hessian 26 | function [Ec,dE,H] = singleLayerAdvObjFun(Y,K,b,W,C,paramSL,paramRegKb) 27 | 28 | if nargin==0 29 | runMinimalExample; 30 | return 31 | end 32 | 33 | if not(exist('paramSL','var')) || isempty(paramSL) 34 | paramSL = @tanhActivation; 35 | end 36 | 37 | n = size(C,2); 38 | nf = size(K,2); 39 | Y = reshape(Y,nf,n); 40 | 41 | % evaluate layer 42 | [Z,~,~,JYt,~,~,JY] = singleLayer(K,b,Y,paramSL); 43 | 44 | % compute cross entropy 45 | [Ec,~,~,dEZ,d2EY] = softMax(W,Z,C); 46 | 47 | % add regularizer 48 | if not(exist('paramRegKb','var')) || not(isstruct(paramRegKb)) 49 | dS = 0; d2S = @(x) 0; 50 | else 51 | [Sc,dS,d2S] = genTikhonov(Y,paramRegKb); 52 | Ec = Ec + Sc; 53 | end 54 | 55 | if nargout>1 56 | dEY = JYt(dEZ); 57 | dE = dEY(:) + dS; 58 | end 59 | 60 | if nargout>2 61 | mat = @(Y) reshape(Y,n,nf); 62 | vec = @(Y) Y(:); 63 | H = @(Y) vec( JYt(d2EY(JY(mat(Y)))) + d2R(x)); 64 | end 65 | 66 | function runMinimalExample 67 | n = 50; nf = 50; nc = 3; m = 40; 68 | Wtrue = randn(nc,m+1); 69 | Ktrue = randn(m,nf); 70 | btrue = .1; 71 | Ytrue = randn(nf,n); 72 | paramSL.act = @sinActivation; 73 | paramReg = struct('L', speye(numel(Ytrue)),'lambda',.1); 74 | 75 | Cobs = exp(Wtrue*padarray(singleLayer(Ktrue,btrue,Ytrue,paramSL),[1 0],1,'post')); 76 | Cobs = Cobs./sum(Cobs,1); 77 | 78 | Y0 = randn(nf*n,1); 79 | [E,dE] = feval(mfilename,Y0,Ktrue,btrue,Wtrue,Cobs,paramSL,paramReg); 80 | dY = randn(size(Y0)); 81 | for k=1:20 82 | h = 2^(-k); 83 | Et = feval(mfilename,Y0+h*dY,Ktrue,btrue,Wtrue,Cobs,paramSL,paramReg); 84 | 85 | err1 = norm(E-Et); 86 | err2 = norm(E+h*dE'*dY-Et); 87 | fprintf('%1.2e\t%1.2e\t%1.2e\n',h,err1,err2); 88 | end 89 | 90 | -------------------------------------------------------------------------------- /singleLayer/singleLayerNNObjFun.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ec,dE,H] = singleLayerNNObjFun(x,Y,C,m) 8 | % 9 | % evaluates single layer and computes cross entropy, gradient and approx. Hessian 10 | % 11 | % Let x = [K(:);b(:);W(:)], we compute 12 | % 13 | % E(x) = E(Z*W,C), where Z = activation(Y*K+b) 14 | % 15 | % Inputs: 16 | % 17 | % x - current iterate, x=[K(:);b(:);W(:)] 18 | % Y - input features 19 | % C - class probabilities 20 | % m - size(K,2), used to split x correctly 21 | % paramSL - struct, description of single layer. Fields: 22 | % act - activation function (default: @tanhActivation) 23 | % paramReg- struct, description of regularizer. See genTikhonov.m 24 | % 25 | % Output: 26 | % 27 | % Ec - current value of loss function 28 | % dE - gradient w.r.t. K,b,W, vector 29 | % H - approximate Hessian, H=J'*d2ES*J, function_handle 30 | function [Ec,dE,H] = singleLayerNNObjFun(x,Y,C,m,paramSL,paramReg) 31 | 32 | 33 | if nargin==0 34 | runMinimalExample 35 | return; 36 | end 37 | 38 | if not(exist('paramSL','var')) || isempty(paramSL) 39 | paramSL = @tanhActivation; 40 | end 41 | 42 | 43 | [nf,~] = size(Y); 44 | nc = size(C,1); 45 | 46 | % split x into K,b,W 47 | x = x(:); 48 | K = reshape(x(1:nf*m),m,nf); 49 | b = x(nf*m+1); 50 | W = reshape(x(nf*m+2:end),nc,[]); 51 | 52 | % evaluate layer 53 | [Z,JKt,Jbt,~,JK,Jb,~] = singleLayer(K,b,Y,paramSL); 54 | 55 | % compute cross entropy 56 | [Ec,dEW,d2EW,dEZ,d2EZ] = softMax(W,Z,C); 57 | 58 | % add regularizer 59 | if not(exist('paramReg','var')) || not(isstruct(paramReg)) 60 | dS = 0; d2S = @(x) 0; 61 | else 62 | [Sc,dS,d2S] = genTikhonov(x,paramReg); 63 | Ec = Ec + Sc; 64 | end 65 | 66 | if nargout>1 67 | dEK = JKt(dEZ); 68 | dEb = Jbt(dEZ); 69 | 70 | dE = [dEK(:); dEb(:); dEW(:)]; 71 | dE = dE + dS; 72 | end 73 | 74 | 75 | if nargout>2 76 | szK = [size(K,1) size(K,2)]; 77 | H = @(x) HessMat(x,szK,JK,Jb,JKt,Jbt,d2EW,d2EZ,d2S); 78 | end 79 | 80 | function Hx = HessMat(x,szK,JK,Jb,JKt,Jbt,d2EW,d2EY,d2S) 81 | nK = prod(szK); 82 | 83 | % split x 84 | xK = x(1:nK); 85 | xb = x(nK+1); 86 | xW = x(nK+2:end); 87 | 88 | % compute Jac*x 89 | JKbx = JK(reshape(xK,szK)) + Jb(xb); 90 | tt = d2EY(JKbx); 91 | Hx1 = [reshape(JKt(tt),[],1); Jbt(tt) ]; 92 | 93 | Hx2 = d2EW(xW); 94 | 95 | % stack result 96 | Hx = [Hx1(:); Hx2(:)] + d2S(x); 97 | 98 | 99 | function runMinimalExample 100 | n = 50; nf = 50; nc = 3; m = 40; 101 | Wtrue = randn(nc,m+1); 102 | Ktrue = randn(m,nf); 103 | btrue = .1; 104 | 105 | Y = randn(nf,n); 106 | Cobs = exp(Wtrue*padarray(singleLayer(Ktrue,btrue,Y),[1,0],1,'post')); 107 | Cobs = Cobs./sum(Cobs,1); 108 | 109 | x0 = [Ktrue(:);btrue; Wtrue(:)]; 110 | x0 = randn(size(x0)); 111 | [E,dE] = feval(mfilename,x0,Y,Cobs,m); 112 | dK = randn(nf*m,1); 113 | db = randn(); 114 | dW = randn((m+1)*nc,1); 115 | dx = [dK;db;dW]; 116 | for k=1:20 117 | h = 2^(-k); 118 | Et = feval(mfilename,x0+h*dx,Y,Cobs,m); 119 | 120 | err1 = norm(E-Et); 121 | err2 = norm(E+h*dE'*dx-Et); 122 | fprintf('%1.2e\t%1.2e\t%1.2e\n',h,err1,err2); 123 | end 124 | 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /singleLayer/singleLayerNNVarProObjFun.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % [Ec,dE,H] = singleLayerNNVarProObjFun(x,Y,C,m,paramCl,paramSL,paramRegKb,paramRegW) 8 | % 9 | % evaluates single layer and computes cross entropy, gradient and approx. Hessian 10 | % 11 | % Let x = [K(:);b(:);W(:)], we compute 12 | % 13 | % E(x) = E(Z*W,C), where Z = activation(Y*K+b) 14 | % 15 | % Inputs 16 | % 17 | % x - current iterate, x=[K(:);b(:);W(:)] 18 | % Y - input features 19 | % C - class probabilities 20 | % m - size(K,2), used to split x correctly 21 | % paramCl - struct, paramters for newtoncg used to classify 22 | % paramSL - struct, paramters for single layer 23 | % paramRegKb - struct, parameter describing regularizer for K and b 24 | % paramRegW - struct, parameter describing regularizer for W 25 | % 26 | % Output: 27 | % 28 | % Ec - current value of loss function 29 | % dE - gradient w.r.t. K,b,W, vector 30 | % H - approximate Hessian, H=J'*d2ES*J, function_handle 31 | function [Ec,dE,H] = singleLayerNNVarProObjFun(x,Y,C,m,paramCl,paramSL,paramRegKb,paramRegW) 32 | 33 | if nargin==0 34 | runMinimalExample; 35 | return; 36 | end 37 | 38 | if not(exist('paramSL','var')) || isempty(paramSL) 39 | paramSL = @tanhActivation; 40 | end 41 | 42 | [nf,n] = size(Y); 43 | nc = size(C,1); 44 | 45 | % split x into K,b 46 | x = x(:); 47 | K = reshape(x(1:nf*m),m,nf); 48 | b = x(nf*m+1); 49 | 50 | % evaluate layer 51 | [Z,JKt,Jbt,~,JK,Jb,~] = singleLayer(K,b,Y,paramSL); 52 | 53 | % solve classification problem 54 | if exist('paramRegW','var') 55 | fctn = @(W,varargin) classObjFun(W,Z,C,paramRegW); 56 | else 57 | fctn = @(W,varargin) softMax(W,Z,C); 58 | end 59 | WOpt = newtoncg(fctn,zeros(nc*(m+1),1),paramCl); 60 | 61 | % call cross entropy 62 | [Ec,~,~,dEZ,d2EZ] = softMax(WOpt,Z,C); 63 | 64 | % regularizer 65 | if not(exist('paramRegKb','var')) || not(isstruct(paramRegKb)) 66 | Sc = 0; dS = 0; d2S = @(x) 0; 67 | else 68 | [Sc,dS,d2S] = genTikhonov(x,paramRegKb); 69 | end 70 | 71 | Ec = Ec + Sc; 72 | if nargout>1 73 | dEK = JKt(dEZ); 74 | dEb = Jbt(dEZ); 75 | 76 | dE = [dEK(:); dEb(:);]; 77 | dE = dE + dS; 78 | end 79 | 80 | if nargout>2 81 | szK = [size(K,1) size(K,2)]; 82 | H = @(x) HessMat(x,szK,JK,Jb,JKt,Jbt,d2EZ,d2S); 83 | end 84 | 85 | function Hx = HessMat(x,szK,JK,Jb,JKt,Jbt,d2EY,d2S) 86 | nK = prod(szK); 87 | 88 | % split x 89 | xK = x(1:nK); 90 | xb = x(nK+1); 91 | 92 | % compute Jac*x 93 | JKbx = JK(reshape(xK,szK)) + Jb(xb); 94 | tt = d2EY(JKbx); 95 | Hx1 = [reshape(JKt(tt),[],1); Jbt(tt) ]; 96 | 97 | % stack result 98 | Hx = Hx1(:) + d2S(x); 99 | 100 | 101 | function runMinimalExample 102 | 103 | n = 50; nf = 50; nc = 3; m = 40; 104 | Wtrue = randn(nc,m+1); 105 | Ktrue = randn(m,nf); 106 | btrue = .1; 107 | 108 | Y = randn(nf,n); 109 | Cobs = exp(Wtrue*padarray(singleLayer(Ktrue,btrue,Y),[1 0],1,'post')); 110 | Cobs = Cobs./sum(Cobs,1); 111 | 112 | x0 = [Ktrue(:);btrue;]; 113 | x0 = randn(size(x0)); 114 | paramCl = struct('maxIter',100,'maxIterCG',100,'tolCG',1e-4,'out',0); 115 | paramRegW = struct('L',speye(numel(Wtrue)),'lambda',1e-2); 116 | [E,dE] = feval(mfilename,x0,Y,Cobs,m,paramCl); 117 | dK = randn(nf*m,1); 118 | db = randn(); 119 | dx = 100*[dK;db]; 120 | for k=1:20 121 | h = 2^(-k); 122 | Et = feval(mfilename,x0+h*dx,Y,Cobs,m,paramCl); 123 | 124 | err1 = norm(E-Et); 125 | err2 = norm(E+h*dE'*dx-Et); 126 | fprintf('%1.2e\t%1.2e\t%1.2e\n',h,err1,err2); 127 | end 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /startupNumDLToolbox.m: -------------------------------------------------------------------------------- 1 | 2 | addpath(genpath(pwd)) 3 | 4 | msg = fprintf('%s\n', '','Welcome to the MATLAB codes for the course Numerical Methods for Deep Learning',... 5 | '','For details see https://github.com/IPAIopen/NumDL-MATLAB',''); 6 | -------------------------------------------------------------------------------- /test/Rosenbrock.m: -------------------------------------------------------------------------------- 1 | function [f,df,d2f] = Rosenbrock(x) 2 | % [f,df,d2f] = Rosenbrock(x) 3 | % 4 | % Rosenbrock function. Useful to test optimization algorithms 5 | 6 | x = reshape(x,2,[]); 7 | f = (1-x(1,:)).^2 + 100*(x(2,:) - (x(1,:)).^2).^2; 8 | 9 | if nargout>1 && size(x,2)==1 10 | df = [2*(x(1)-1) - 400*x(1)*(x(2)-(x(1))^2); ... 11 | 200*(x(2) - (x(1))^2)]; 12 | end 13 | 14 | if nargout>2 && size(x,2)==1 15 | n= 2; 16 | d2f=zeros(n); 17 | d2f(1,1)=400*(3*x(1)^2-x(2))+2; d2f(1,2)=-400*x(1); 18 | for j=2:n-1 19 | d2f(j,j-1)=-400*x(j-1); 20 | d2f(j,j)=200+400*(3*x(j)^2-x(j+1))+2; 21 | d2f(j,j+1)=-400*x(j); 22 | end 23 | d2f(n,n-1)=-400*x(n-1); d2f(n,n)=200; 24 | end -------------------------------------------------------------------------------- /test/quadObjFun.m: -------------------------------------------------------------------------------- 1 | function [Fc,dF,d2F] = quadObjFun(A,b,xc,S) 2 | 3 | res = A(S,:)*xc - b(S); 4 | 5 | Fc = 0.5*res'*res; 6 | dF = A(S,:)'*res; 7 | d2F = A(S,:)'*A(S,:); 8 | 9 | -------------------------------------------------------------------------------- /test/testGenTikhonov.m: -------------------------------------------------------------------------------- 1 | nf = 10; 2 | nc = 1; 3 | L = randn(20,nf); 4 | param = struct('L',L,'nc',nc,'h',1); 5 | W = randn(nf*nc,1); 6 | %% check calls of genTikhonov 7 | [Rc,dR,d2R] = genTikhonov(W,param); 8 | assert(numel(Rc)==1,'first output argument of softMax must be a scalar'); 9 | assert(all(size(dR)==size(W)),'size of gradient and W must match'); 10 | 11 | if isnumeric(d2R) 12 | assert(all(size(d2R)==[numel(W),numel(W)]),'size of Hessian incorrect'); 13 | elseif isa(d2R,'function_handle') 14 | assert(all(size(d2R(W))==size(W)),'matrix free Hessian must preserve size'); 15 | else 16 | error('d2R must be either matrix or function'); 17 | end 18 | 19 | % check calls of genTikhonov 20 | param.lambda = 2; 21 | [R2] =genTikhonov(W,param); 22 | assert(norm(2*Rc-R2)<1e-10,'scaling incorrect!'); 23 | 24 | 25 | %% check derivatives and Hessian 26 | W0 = randn(size(W)); 27 | dW = randn(size(W)); 28 | param.h = rand(); 29 | 30 | [F,dF,d2F] = genTikhonov(W0,param); 31 | dFdW = dF'*dW; 32 | if isnumeric(d2F) 33 | d2FdW = dW'*d2F*dW; 34 | else 35 | d2FdW = dW'*d2F(dW); 36 | end 37 | err = zeros(10,4); 38 | for k=1:size(err,1) 39 | h = 2^(-k); 40 | Ft = genTikhonov(W0+h*dW,param); 41 | 42 | err(k,:) = [h, norm(F-Ft), norm(F+h*dFdW-Ft), norm(F+h*dFdW+h^2/2*d2FdW-Ft)]; 43 | 44 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\tE1=%1.2e\n',err(k,:)) 45 | end 46 | 47 | figure; clf; 48 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 49 | hold on; 50 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 51 | hold on; 52 | loglog(err(:,1), err(:,4),'-k','linewidth',3); 53 | legend('E0','E1','E2'); -------------------------------------------------------------------------------- /test/testLogRegression.m: -------------------------------------------------------------------------------- 1 | a = 3; 2 | b = 2; 3 | 4 | Y = randn(2,500); 5 | W = randn(3,1); 6 | 7 | C = (W(1:2)'*Y + W(3))>0; 8 | 9 | 10 | %% check calls of softmax 11 | [F1,dF1] = logRegression(W,Y,C); 12 | 13 | assert(numel(F1)==1,'first output argument of softMax must be a scalar') 14 | assert(all(size(dF1)==size(W)), 'size of gradient and W must match'); 15 | 16 | [F2,dF2] = logRegression(1e4*W,Y,C); 17 | assert( not(isinf(F2)) && not(isnan(F2)), 'Likely an overflow in softMax '); 18 | assert(abs(F2)<1e-9,'loss should be around zero'); 19 | 20 | 21 | %% check derivatives and Hessian 22 | W0 = randn(size(W)); 23 | dW = randn(size(W)); 24 | 25 | [F,dF,d2F] = logRegression(W0,Y,C); 26 | dFdW = dF'*dW; 27 | d2FdW = dW'*d2F(dW); 28 | % dF = dF + 1e-2*randn(size(dF)); 29 | err = zeros(30,4); 30 | for k=1:size(err,1) 31 | h = 2^(-k); 32 | Ft = logRegression(W0+h*dW,Y,C); 33 | 34 | err(k,:) = [h, norm(F-Ft), norm(F+h*dFdW-Ft), norm(F+h*dFdW+h^2/2*d2FdW-Ft)]; 35 | 36 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\tE1=%1.2e\n',err(k,:)) 37 | end 38 | 39 | figure; clf; 40 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 41 | hold on; 42 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 43 | hold on; 44 | loglog(err(:,1), err(:,4),'-k','linewidth',3); 45 | legend('E0','E1','E2'); 46 | 47 | %% check derivatives and Hessian 48 | Y0 = randn(size(Y)); 49 | dY = randn(size(Y)); 50 | 51 | [F,dF,d2F,dFY,d2FY] = logRegression(W,Y0,C); 52 | dFdY = dFY'*dY(:); 53 | d2FdY = dY(:)'*d2FY(dY); 54 | % dF = dF + 1e-2*randn(size(dF)); 55 | err = zeros(30,4); 56 | for k=1:size(err,1) 57 | h = 2^(-k); 58 | Ft = logRegression(W,Y0+h*dY,C); 59 | 60 | err(k,:) = [h, norm(F-Ft), norm(F+h*dFdY-Ft), norm(F+h*dFdY+h^2/2*d2FdY-Ft)]; 61 | 62 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\tE1=%1.2e\n',err(k,:)) 63 | end 64 | 65 | figure; clf; 66 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 67 | hold on; 68 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 69 | hold on; 70 | loglog(err(:,1), err(:,4),'-k','linewidth',3); 71 | legend('E0','E1','E2'); -------------------------------------------------------------------------------- /test/testSingleLayer.m: -------------------------------------------------------------------------------- 1 | close all; clear all; clc; 2 | 3 | n = 10; 4 | nf = 7; 5 | m = 4; 6 | 7 | K = randn(m,nf); 8 | Y = randn(nf,n); 9 | b = randn(); 10 | 11 | 12 | %% test single layer 13 | Z = singleLayer(K,b,Y); 14 | 15 | assert(all(size(Z)==[m,n]),'output sizes must be m x n'); 16 | 17 | %% derivative check for K 18 | dK = randn(m,nf); 19 | b = 0; 20 | [Z,JKt,~,~,JK] = singleLayer(K,b,Y); 21 | dZ = JK(dK); 22 | 23 | err = zeros(30,3); 24 | for k=1:size(err,1) 25 | h = 2^(-k); 26 | Zt = singleLayer(K+h*dK,b,Y); 27 | 28 | err(k,:) = [h, norm(Z-Zt,'fro'), norm(Z+h*dZ-Zt,'fro')]; 29 | 30 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\n',err(k,:)) 31 | end 32 | 33 | % test adjoint 34 | V = randn(m,nf); 35 | W = randn(m,n); 36 | t1 = sum(sum(W.*JK(V))); 37 | t2 = sum(sum(V.*JKt(W))); 38 | 39 | 40 | fig = figure; clf; 41 | fig.Name = 'checkDerivative for K'; 42 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 43 | hold on; 44 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 45 | legend('E0','E1'); 46 | adjErr = norm(t1-t2)/norm(t1); 47 | title(sprintf('adjoint error: %1.2e',adjErr)) 48 | 49 | if adjErr>1e-12 50 | error('check adjoint for K') 51 | end 52 | 53 | %% derivative check for b 54 | b = randn(); 55 | db = randn(); 56 | [Z,~,Jbt,~,~,Jb] = singleLayer(K,b,Y); 57 | dZ = Jb(db); 58 | 59 | err = zeros(30,3); 60 | for k=1:size(err,1) 61 | h = 2^(-k); 62 | Zt = singleLayer(K,b+h*db,Y); 63 | 64 | err(k,:) = [h, norm(Z-Zt,'fro'), norm(Z+h*dZ-Zt,'fro')]; 65 | 66 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\n',err(k,:)) 67 | end 68 | 69 | % test adjoint 70 | V = randn(); 71 | W = randn(m,n); 72 | t1 = sum(sum(W.*Jb(V))); 73 | t2 = sum(sum(V.*Jbt(W))); 74 | 75 | 76 | fig = figure; clf; 77 | fig.Name = 'checkDerivative for b'; 78 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 79 | hold on; 80 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 81 | legend('E0','E1'); 82 | adjErr = norm(t1-t2)/norm(t1); 83 | title(sprintf('adjoint error: %1.2e',adjErr)) 84 | 85 | if adjErr>1e-12 86 | error('check adjoint for b') 87 | end 88 | 89 | %% derivative check for Y 90 | Y = randn(nf,n); 91 | dY = randn(nf,n); 92 | [Z,~,~,JYt,~,~,JY] = singleLayer(K,b,Y); 93 | dZ = JY(dY); 94 | 95 | err = zeros(30,3); 96 | for k=1:size(err,1) 97 | h = 2^(-k); 98 | Zt = singleLayer(K,b,Y+h*dY); 99 | 100 | err(k,:) = [h, norm(Z-Zt,'fro'), norm(Z+h*dZ-Zt,'fro')]; 101 | 102 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\n',err(k,:)) 103 | end 104 | 105 | % test adjoint 106 | V = randn(nf,n); 107 | W = randn(m,n); 108 | t1 = sum(sum(W.*JY(V))); 109 | t2 = sum(sum(V.*JYt(W))); 110 | 111 | 112 | fig = figure; clf; 113 | fig.Name = 'checkDerivative for Y'; 114 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 115 | hold on; 116 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 117 | legend('E0','E1'); 118 | 119 | adjErr = norm(t1-t2)/norm(t1); 120 | title(sprintf('adjoint error: %1.2e',adjErr)) 121 | 122 | if adjErr>1e-12 123 | error('check adjoint for Y') 124 | end 125 | -------------------------------------------------------------------------------- /test/testSingleLayerNNObjFun.m: -------------------------------------------------------------------------------- 1 | close all; clear all; clc; 2 | 3 | rng(20) 4 | n = 500; nf = 50; nc = 10; m = 40; 5 | Wtrue = randn(nc,m); 6 | Ktrue = randn(m,nf); 7 | btrue = .1; 8 | 9 | Y = randn(nf,n); 10 | Cobs = exp(Wtrue*singleLayer(Ktrue,btrue,Y)); 11 | Cobs = Cobs./sum(Cobs,1); 12 | 13 | %% test single layer NN objective 14 | x0 = randn(numel(Ktrue)+numel(btrue)+numel(Wtrue),1); 15 | 16 | [Ec,dE] = singleLayerNNObjFun(x0,Y,Cobs,m); 17 | 18 | assert(isscalar(Ec),'objective function should return scalar'); 19 | assert(all(size(dE)==size(x0)),'gradient should be a column vector'); 20 | 21 | % check derivative 22 | dx = randn(size(x0)); 23 | 24 | [Ec,dE] = singleLayerNNObjFun(x0,Y,Cobs,m); 25 | dEdx = dE'*dx; 26 | 27 | % dF = dF + 1e-2*randn(size(dF)); 28 | err = zeros(30,3); 29 | for k=1:size(err,1) 30 | h = 2^(-k); 31 | Et = singleLayerNNObjFun(x0+h*dx,Y,Cobs,m); 32 | 33 | err(k,:) = [h, norm(Ec-Et), norm(Ec+h*dEdx-Et)]; 34 | 35 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\n',err(k,:)) 36 | end 37 | 38 | figure; clf; 39 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 40 | hold on; 41 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 42 | legend('E0','E1'); 43 | 44 | % run steepest descent 45 | F = @(x) singleLayerNNObjFun(x,Y,Cobs,m); 46 | param = struct('maxIter',2000,'maxStep',1); 47 | xSol = steepestDescent(F,x0,param); 48 | 49 | Ksol = reshape(xSol(1:nf*m),m,nf); 50 | bsol = xSol(nf*m+1); 51 | Wsol = reshape(xSol(nf*m+2:end),nc,m); 52 | % 53 | norm(Ktrue-Ksol)/norm(Ktrue) 54 | norm(bsol-btrue)/norm(btrue) 55 | norm(Wtrue-Wsol)/norm(Wtrue) 56 | % 57 | 58 | Cpred = exp(Wsol*singleLayer(Ksol,bsol,Y)); 59 | Cpred = Cpred./sum(Cpred,1); 60 | assert(norm(Cobs-Cpred)/norm(Cobs) < 0.01,'training accuracy too low'); -------------------------------------------------------------------------------- /test/testSoftMax.m: -------------------------------------------------------------------------------- 1 | a = 3; 2 | b = 2; 3 | 4 | Y = randn(2,500); 5 | C = a*Y(1,:) + b*Y(2,:) +2; 6 | C(C>0) = 1; C(C<0) = 0; 7 | C = [C; 1-C]; 8 | 9 | W = [eye(2) ones(2,1)]; 10 | W = W(:); 11 | 12 | %% check calls of softmax 13 | [F1,dF1] = softMax(W,C,C); 14 | 15 | assert(numel(F1)==1,'first output argument of softMax must be a scalar') 16 | assert(all(size(dF1)==size(W)), 'size of gradient and W must match'); 17 | 18 | [F2,dF2] = softMax(1e4*W,C,C); 19 | assert( not(isinf(F2)) && not(isnan(F2)), 'Likely an overflow in softMax '); 20 | assert(abs(F2)<1e-9,'loss should be around zero'); 21 | 22 | [F3,dF3] = softMax(W,[1e4*C [1; 0]],[C [1;0]]); 23 | assert(not(isinf(F3)) && not(isnan(F3)),'Likely an underflow in softMax ') 24 | 25 | %% check derivatives and Hessian 26 | W0 = randn(size(W)); 27 | dW = randn(size(W)); 28 | 29 | [F,dF,d2F] = softMax(W0,Y,C); 30 | dFdW = dF'*dW; 31 | d2FdW = dW'*d2F(dW); 32 | % dF = dF + 1e-2*randn(size(dF)); 33 | err = zeros(30,4); 34 | for k=1:size(err,1) 35 | h = 2^(-k); 36 | Ft = softMax(W0+h*dW,Y,C); 37 | 38 | err(k,:) = [h, norm(F-Ft), norm(F+h*dFdW-Ft), norm(F+h*dFdW+h^2/2*d2FdW-Ft)]; 39 | 40 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\tE1=%1.2e\n',err(k,:)) 41 | end 42 | 43 | figure; clf; 44 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 45 | hold on; 46 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 47 | hold on; 48 | loglog(err(:,1), err(:,4),'-k','linewidth',3); 49 | legend('E0','E1','E2'); 50 | 51 | %% check derivatives and Hessian 52 | Y0 = randn(size(Y)); 53 | dY = randn(size(Y)); 54 | 55 | [F,dF,d2F,dFY,d2FY] = softMax(W,Y0,C); 56 | dFdY = dFY'*dY(:); 57 | d2FdY = dY(:)'*d2FY(dY); 58 | % dF = dF + 1e-2*randn(size(dF)); 59 | err = zeros(30,4); 60 | for k=1:size(err,1) 61 | h = 2^(-k); 62 | Ft = softMax(W,Y0+h*dY,C); 63 | 64 | err(k,:) = [h, norm(F-Ft), norm(F+h*dFdY-Ft), norm(F+h*dFdY+h^2/2*d2FdY-Ft)]; 65 | 66 | fprintf('h=%1.2e\tE0=%1.2e\tE1=%1.2e\tE1=%1.2e\n',err(k,:)) 67 | end 68 | 69 | figure; clf; 70 | loglog(err(:,1),err(:,2),'-b','linewidth',3); 71 | hold on; 72 | loglog(err(:,1), err(:,3),'-r','linewidth',3); 73 | hold on; 74 | loglog(err(:,1), err(:,4),'-k','linewidth',3); 75 | legend('E0','E1','E2'); -------------------------------------------------------------------------------- /utils/LinearOperator.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classdef LinearOperator 8 | % 9 | % Allows one to define a matrix by its size and acting on a vector. This is 10 | % a basic implementation that overloads *, transpose, +, blkdiag, hcat, .. 11 | classdef LinearOperator 12 | 13 | properties 14 | m % number of columns 15 | n % number of rows 16 | Amv % mat-vec, function handle 17 | ATmv % transpose mat-vec, function handle 18 | end 19 | 20 | methods 21 | function this = LinearOperator(varargin) 22 | % constructor, LinearOperator(varargin) 23 | % 24 | % As input, either provide a matric or define m,n,Amv,ATmv 25 | if nargin==0 26 | this.runMinimalExample; 27 | return; 28 | end 29 | 30 | if nargin==1 && isnumeric(varargin{1}) 31 | A = varargin{1}; 32 | [this.m,this.n] = size(A); 33 | this.Amv = @(x) A*x; 34 | this.ATmv = @(x) A'*x; 35 | elseif nargin>=4 36 | this.m = varargin{1}; 37 | this.n = varargin{2}; 38 | this.Amv = varargin{3}; 39 | this.ATmv = varargin{4}; 40 | else 41 | error('%s - invalid number of inputs',mfilename); 42 | end 43 | end 44 | 45 | function szA = size(this,dim) 46 | if nargin==1 47 | szA = [this.m, this.n]; 48 | elseif nargin==2 && dim==1 49 | szA = this.m; 50 | elseif nargin==2 && dim==2 51 | szA = this.n; 52 | end 53 | end 54 | 55 | function nn = numel(this) 56 | nn = prod(size(this)); 57 | end 58 | 59 | function Ax = mtimes(this,B) 60 | if isscalar(B) 61 | Ax = LinearOperator(this.m,this.n,@(x) B*this.Amv(x), @(x) B*this.ATmv(x)); 62 | elseif isscalar(this) 63 | Ax = LinearOperator(B.m,B.n,@(x) this*B.Amv(x), @(x) this*B.ATmv(x)); 64 | elseif isa(B,'LinearOperator') 65 | if size(this,2)==size(B,1) || isinf(size(B,1)) 66 | if isinf(size(B,2)) 67 | n = size(this,2); 68 | else 69 | n = size(B,2); 70 | end 71 | Ax = LinearOperator(this.m,n, @(x) this*(B*x), @(x) B'*(this'*x)); 72 | else 73 | error('Inner dimensions must agree'); 74 | end 75 | else 76 | Ax = this.Amv(B); 77 | end 78 | end 79 | 80 | function AB = plus(this,B) 81 | if isnumeric(this) 82 | this = LinearOperator(this); 83 | end 84 | if isnumeric(B) 85 | B = LinearOperator(B); 86 | end 87 | if isempty(this) 88 | AB = B; 89 | return; 90 | end 91 | 92 | if any(isinf(size(this))) 93 | szAB = size(B); 94 | elseif any(isinf(size(B))) 95 | szAB = size(this); 96 | elseif any(size(this)~=size(B)) 97 | error('A and B must have same size'); 98 | else 99 | szAB = size(B); 100 | end 101 | ABf = @(x) this.Amv(x) + B.Amv(x); 102 | ABTf = @(x) this.ATmv(x) + B.ATmv(x); 103 | AB = LinearOperator(szAB(1),szAB(2), ABf, ABTf); 104 | end 105 | 106 | function AB = minus(this,B) 107 | if isnumeric(B) 108 | B = LinearOperator(B); 109 | end 110 | if any(size(this)~=size(B)) 111 | error('A and B must have same size'); 112 | end 113 | ABf = @(x) this.Amv(x) - B.Amv(x); 114 | ABTf = @(x) this.ATmv(x) - B.ATmv(x); 115 | AB = LinearOperator(this.m,this.n, ABf, ABTf); 116 | end 117 | 118 | function AB = blkdiag(this,varargin) 119 | ops = {this,varargin{:}}; 120 | AB = opBlkdiag(ops{:}); 121 | end 122 | 123 | 124 | function AB = hcat(this,B) 125 | if isnumeric(B) 126 | B = LinearOperator(B); 127 | end 128 | if this.m ~=B.m 129 | error('hcat - first dimension must agree'); 130 | end 131 | 132 | mAB = this.m; 133 | nAB = this.n + B.n; 134 | ABf = @(x) this.Amv(x(1:this.n,:)) + B.Amv(x(this.n+1:end,:)); 135 | ABTf = @(x) [vec(this.ATmv(x)); vec(B.ATmv(x))]; 136 | AB = LinearOperator(mAB,nAB,ABf,ABTf); 137 | end 138 | 139 | 140 | function AT = transpose(this) 141 | AT = LinearOperator(this.n, this.m, this.ATmv, this.Amv); 142 | end 143 | 144 | function AT = ctranspose(this) 145 | AT = LinearOperator(this.n, this.m, this.ATmv, this.Amv); 146 | end 147 | 148 | function runMinimalExample(~) 149 | A = randn(4,6); 150 | Aop = LinearOperator(A); 151 | end 152 | end 153 | end 154 | 155 | -------------------------------------------------------------------------------- /utils/cell2vec.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % a = cell2vec(A) 8 | % 9 | % vectorizes a cell array 10 | function a = cell2vec(A) 11 | 12 | a = []; 13 | for i=1:length(A) 14 | a = [a ; A{i}(:)]; 15 | end -------------------------------------------------------------------------------- /utils/opEye.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classdef opEye 8 | % 9 | % Matrix-free implementation of identity matrix 10 | % 11 | classdef opEye 12 | properties 13 | n % number of columns/rows 14 | Amv % mat-vec, Amv(x) = x 15 | ATmv % transpose mat-vec, ATmv(x)=x 16 | end 17 | properties (Dependent) 18 | m % number of rows, equal to this.n 19 | end 20 | 21 | methods 22 | function this = opEye(n) 23 | % constructor, opEye(n) 24 | this.n = n; 25 | this.Amv = @(x) x; 26 | this.ATmv = @(x) x; 27 | end 28 | 29 | function z = mtimes(this,x) 30 | z = this.Amv(x); 31 | end 32 | 33 | function this = convertGPUorPrecision(this,useGPU,precision) 34 | % do nothing 35 | end 36 | 37 | function m = get.m(this) 38 | m = this.n; 39 | end 40 | end 41 | end 42 | 43 | -------------------------------------------------------------------------------- /utils/opKron.m: -------------------------------------------------------------------------------- 1 | classdef opKron < LinearOperator 2 | %============================================================================== 3 | % This code is part of the course materials for 4 | % Numerical Methods for Deep Learning 5 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 6 | %============================================================================== 7 | % 8 | % linear operator for computing kronecker products 9 | % 10 | % kron(I,B)*vec(x) = vec(B*mat(x)*I) 11 | 12 | properties 13 | end 14 | 15 | methods 16 | function this = opKron(nI,B) 17 | this.m = nI*size(B,1); 18 | vec = @(x) x(:); 19 | this.n = nI*size(B,2); 20 | this.Amv = @(x) vec(B*reshape(x,size(B,2),[])); 21 | this.ATmv = @(x)vec(B'*reshape(x,size(B,1),[])); 22 | end 23 | 24 | function getPCop(this,~) 25 | error('nyi'); 26 | end 27 | 28 | function PCmv(A,x,alpha,gamma) 29 | error('nyi'); 30 | end 31 | function this = convertGPUorPrecision(this,useGPU,precision) 32 | % do nothing 33 | end 34 | 35 | end 36 | end 37 | 38 | -------------------------------------------------------------------------------- /utils/opZero.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % classdef opZero 8 | % 9 | % Matrix-free implementation of zeros(m,n) 10 | % 11 | classdef opZero 12 | properties 13 | m % number of rows 14 | n % number of columns 15 | Amv % mat-vec, Amv(x) = 0; 16 | ATmv % transpose mat-vec, ATmv(x) = 0; 17 | end 18 | 19 | methods 20 | function this = opZero(m,n) 21 | % constructor, opZero(m,n) 22 | this.m = m; 23 | this.n = n; 24 | this.Amv = @(x) 0; 25 | this.ATmv = @(x) 0; 26 | end 27 | function z = mtimes(this,x) 28 | z = this.Amv(x); 29 | end 30 | function this = ctranspose(this) 31 | temp = this.m; 32 | this.m = this.n; 33 | this.n = temp; 34 | temp = this.Amv; 35 | this.Amv = this.ATmv; 36 | this.ATmv = temp; 37 | end 38 | 39 | function this = convertGPUorPrecision(this,useGPU,precision) 40 | % do nothing 41 | end 42 | 43 | end 44 | end 45 | 46 | -------------------------------------------------------------------------------- /utils/vec.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % vec(x) = x(:) 8 | function x=vec(x) 9 | x=x(:); 10 | 11 | -------------------------------------------------------------------------------- /utils/vec2cell.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | function [K,b] = vec2cell(v,n) 7 | 8 | nt = size(n,2); 9 | cnt = 0; 10 | 11 | K = cell(nt,1); 12 | b = cell(nt,1); 13 | 14 | % first get the Ks 15 | for k=1:nt 16 | nk = prod(n(:,k)); 17 | K{k} = reshape( v(cnt+(1:nk)), n(:,k)'); 18 | cnt = cnt + nk; 19 | end 20 | 21 | % now get the bs 22 | for k=1:nt 23 | nb = n(end,k); 24 | b{k} = v(cnt+(1:nb)); 25 | cnt = cnt + nb; 26 | end 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /viewers/montageArray.m: -------------------------------------------------------------------------------- 1 | %============================================================================== 2 | % This code is part of the course materials for 3 | % Numerical Methods for Deep Learning 4 | % For details and license info see https://github.com/IPAIopen/NumDL-MATLAB 5 | %============================================================================== 6 | % 7 | % C = montageArray(A,ncol) 8 | % 9 | % Inputs: 10 | % 11 | % A - 3D/4D array 12 | % ncol - specify number of columns in montage. default=[] 13 | % 14 | % Outputs: 15 | % 16 | % C - montage 17 | function C = montageArray(A,ncol) 18 | 19 | 20 | 21 | [m1,m2,m3] = size(A); 22 | if not(exist('ncol','var')) || isempty(ncol) 23 | ncol = ceil(sqrt(m3)); 24 | end 25 | nrow = ceil(m3/ncol); 26 | 27 | C = zeros(m1*nrow, m2*ncol); 28 | M = zeros(m1*nrow, m2*ncol); 29 | 30 | k=0; 31 | 32 | for p=1:m1:(nrow*m1) 33 | for q=1:m2:(ncol*m2) 34 | k=k+1; 35 | if k>m3, 36 | break 37 | end 38 | C(p:(p+m1-1),q:(q+m2-1)) = A(:,:,k); 39 | M(p:(p+m1-1),q:(q+m2-1)) = 1; 40 | end 41 | end 42 | 43 | if nargout == 0 44 | h = imagesc(C); 45 | set(h, 'AlphaData', M); 46 | 47 | washold = ishold; 48 | hold on; 49 | 50 | [P,Q]= ndgrid(1:m1:((nrow+1)*m1),1:m2:((ncol+1)*m2)); 51 | P = P -0.5; 52 | Q = Q -0.5; 53 | plot(Q,P,'color',get(gcf,'color'),'linewidth',3); 54 | plot(Q',P','color',get(gcf,'color'),'linewidth',3); 55 | plot(Q,P,'k','linewidth',1); 56 | plot(Q',P','k','linewidth',1); 57 | 58 | if ~washold, 59 | hold off; 60 | end; 61 | 62 | end 63 | 64 | 65 | 66 | 67 | 68 | --------------------------------------------------------------------------------