├── LICENSE ├── README.md ├── blog_post.md ├── blog_post.pdf ├── index.html └── static ├── NN_viz.js ├── p5.dom.js └── p5.min.js /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NN_viz 2 | For FFL Blog 3 | -------------------------------------------------------------------------------- /blog_post.md: -------------------------------------------------------------------------------- 1 | # What is "Learning" for Neural Networks 2 | 3 | Neural networks have spurred a lot of excitement recently. They are quickly proving to be one of the most promising and practical implementations of AI within technological systems. At Fast Forward Labs, we've been researching and building systems that use neural networks for object recognition in images. You may have seen our prototype [pictograph](www.pictograph.us). Our goal has been to really understand this technology both technically and in terms of impact and possibility. 4 | 5 | As it turns out, these systems are *extremely* difficult to understand due to their complexity. You may have run into one of Google's efforts to make sense of neural networks through their [research blog](http://googleresearch.blogspot.ch/2015/06/inceptionism-going-deeper-into-neural.html) or their [explanatory videos](https://www.youtube.com/watch?v=bHvf7Tagt18&index=11&list=PLeqAcoTy5741GXa8rccolGQaj_nVGw76g). 6 | 7 | ## Nature of this post 8 | 9 | This post is an extension of this effort to improve how we understand neural networks, specifically around how they "learn". 10 | 11 | Let's start with two points brought home by the team at Google in the above posts: 12 | 13 | 1. Neural networks are difficult to interpret so we have to develop specific techniques to gain insight on what they are doing. 14 | 2. Certain learning tasks us humans do are *very* hard to achieve in artificial neural networks. 15 | 16 | In relation to these points, what I've built is a detailed visualization of how a neural network functions at neuron-by-neuron level, and also how it "learns". If you're already familiar with neural networks or want to follow the rest of the post with a visual cue, please see the visualization [here](http://mwskirpan.com/NN_viz) 17 | 18 | ## Neural Network Basics 19 | 20 | Let's first be sure that we're all on the same page about neural networks basics. Neural networks are composed of layers of computational units (neurons) where each neuron in a layer is connected to each neuron in the next layer. We pass data (e.g., pixel values in an image, words in a text) into our input layer, then many hidden layers transform this data until the output layer makes a prediction or classification on the original data. 21 | 22 | How this "transformation" works is that each neuron passes along a value to the next neuron. During this passing, we multiply the value by some **weight**, sum it up with all the other values incoming to the same neuron, adjust it by the neuron's **bias**, and finally pass it through an **activation function** which normalizes the output. This somewhat simple process is done over and over until finally our output layer has some *scores* or *predictions*. 23 | 24 | Now to the learning. 25 | 26 | These predictions are then compared to some **target**, or correct answer. We then use a **cost function** to determine how much we want to *punish* each of our guesses given how much they strayed from our target values. We then use this information to **backpropagate** across all our neurons and connections in order to adjust the biases and weights. 27 | 28 | And this is it, *backpropagation* is how a neural network learns a particular task. 29 | 30 | ## Details of the Visualization 31 | 32 | At this point it may be worth to go ahead and play with the visualization a bit to see these components at work. What you'll notice is that I have given you the ability to adjust the inputs, each connection has the value of its weight hovering nearby, and each neuron has its bias (b) below and the result of its activation function $\sigma$ above. 33 | 34 | When you click `forward` you can see the final layers guesses in comparison to the target values. Then when you click `backprop` you can watch as the values are adjusted minutely. Then when you press `forward` again, you should see the the output layer improve slightly in comparison to the targets. 35 | 36 | For those AI engineers out there, you'll notice there are certain complications we've ignored for the purpose of exposition. Right now, I use a [softmax function](https://en.wikipedia.org/wiki/Softmax_function) to compute our cost, and a [sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function) for activation. We have ignored other aspects of normal training like regularization, dropout, and mini-batching. 37 | 38 | The trade-off being that, with less features to pay attention to, we can hone in on understanding the fundamentals involved in this procedure. 39 | 40 | ## Interpreting Learning 41 | 42 | With some background laid and the visualization explained, let's move on to talk about learning. The first thing to notice is, even in this simple network, paying attention to one particular number does not tell us much about how the entire system behaves. In fact, this is one of the reasons neural networks are hard to interpret: inspecting specific numbers in our system gives us little to no information about the overall dynamics. 43 | 44 | So, when we think about learning, we don't want to get too invested in the meaning of tweaking each parameter. While this *is* the process, it's hard to see why this amounts to learning. Instead, we want to think about this in terms of **emergence**. That is, complex systems often run on simple rules, and those simple rules compound to create **emergent behaviors**. [Conway's game of life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a great example of this, where we can see complicated structures form by just turning cells in a grid on and off according to a few basic rules. 45 | 46 | Much like our brains, we cannot find our entire answer by looking at one particular region. Rather, we must try to make sense of how the different functional pieces give us the gestalt phenomenon of conscious thinking (which of course we are still struggling to understand). 47 | 48 | Why we need to be careful to compare neural networks to brains is that brains have much more going on than these computational processes. Each time you train a neural network, you do so against a specific, singular task. Human learning, on the other hand, involves switching across contexts and redefining your task as you go along. At the physical level, our brains do not merely *adjust* their connections, but there chemical, electrical, and even quantum effects that determine how we rewire our brains and then act toward goals. 49 | 50 | Having put these exceptions out in the open, we can still leverage the brain metaphor to understand our neural network's learning process. Feeding information forward, to us, is akin to receiving a new visual or tactile input and our brain processing this stimulus. Evaluating the cost function is the neural net's version of us evaluating a stimulus and determining the correct response. Finally, backpropagation is like the network reflecting on its errors so it can do better next time. 51 | 52 | Given this learning mechanism, it's still unclear to us what kind of intelligence we'll see emerge from these systems in the coming years. However, it is important we all develop a realistic understanding in order to not over-aggrandize or under-anticipate what may be possible. 53 | 54 | Hopefully using [my visualization](http://mwskirpan.com/NN_viz) and this accompanying explanation we have a clearer picture of what "learning" really means. Getting our heads around the new systems we create is difficult, but also important for education, public communication, and choices around how to engineer systems with realistic expectations. -------------------------------------------------------------------------------- /blog_post.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wannabeCitizen/NN_viz/15fc8cef76937b3befc9d7841c04279f34055f79/blog_post.pdf -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | FFL Blog Post - NN's 9 | 10 | 11 |
12 |
13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /static/NN_viz.js: -------------------------------------------------------------------------------- 1 | //Michael Skirpan - Fast Forward Labs 2 | //Visualization of Simple Feed-forward Neural Network Using Backpropagation Algorithm 3 | //Many thanks to: 4 | //Daniel Shiffman - http://natureofcode.com - for education and example code 5 | //P5.js folks - http://p5js.org - for example code 6 | //Michael Nielson - http://neuralnetworksanddeeplearning.com/ - for lucid explanations of algorithms 7 | //Andrej Karpathy - https://cs231n.github.io - for great attention to backpropagtion 8 | 9 | var myNetwork; 10 | var batchIn; 11 | var batchTag; 12 | 13 | function sigmoid(z){ 14 | return 1.0/(1.0+Math.exp(-z)); 15 | } 16 | 17 | function sigmoid_prime(z){ 18 | return sigmoid(z)*(1-sigmoid(z)); 19 | } 20 | 21 | // ############ 22 | // Neuron Object 23 | // ############# 24 | 25 | var Neuron = function (location, bias, value) { 26 | //Set location, any initial value (for inputs), bias 27 | this.location = location || createVector(location[0], location[1]); 28 | this.connections = []; 29 | this.backconnects = []; 30 | this.val = value || 0; 31 | this.bias = bias || random(-1, 1); 32 | this.acc = 0; 33 | this.incoming = 0; 34 | this.sig; 35 | this.learningRate = .1; 36 | this.batch = false; 37 | //For backprop stuff 38 | 39 | 40 | //physical size 41 | this.r = 32; 42 | 43 | 44 | this.addConnection = function(c) { 45 | this.connections.push(c); 46 | c.b.incoming++; 47 | } 48 | 49 | this.backConnect = function(c) { 50 | this.backconnects.push(c); 51 | } 52 | 53 | // Receive an input 54 | this.feedforward = function(input) { 55 | // Accumulate it 56 | this.val += input; 57 | this.acc++; 58 | 59 | // Activate it? 60 | if (this.acc == this.incoming) { 61 | this.val += this.bias; 62 | this.sig = sigmoid(this.val); 63 | this.acc = 0; 64 | if (this.sig > 0) { 65 | this.fire(); 66 | } 67 | this.val = 0; 68 | } 69 | } 70 | 71 | //Backpropagate 72 | this.backprop = function(grad) { 73 | //takes in the calculated gradiant leading to this node 74 | //derivative of sigmoid 75 | dsig = ((1 - this.sig) * this.sig) * grad; 76 | 77 | //update bias 78 | this.bias += (-this.learningRate * dsig) 79 | 80 | //shrink for backprop 81 | this.r = 12; 82 | 83 | //send update for weight 84 | if (this.batch){ 85 | for (bc in this.backconnects) { 86 | this.backconnects[bc].batch = true; 87 | this.backconnects[bc].backprop(dsig); 88 | } 89 | } else { 90 | for (bc in this.backconnects) { 91 | this.backconnects[bc].backprop(dsig); 92 | } 93 | } 94 | this.batch = false; 95 | } 96 | 97 | this.fire = function() { 98 | //make it bigger 99 | this.r = 64; 100 | 101 | 102 | // We send the output through all connections 103 | if (this.batch) { 104 | for (c in this.connections) { 105 | this.connections[c].batch = true; 106 | this.connections[c].feedforward(this.val); 107 | } 108 | } else { 109 | for (c in this.connections){ 110 | this.connections[c].feedforward(this.val); 111 | } 112 | } 113 | this.batch = false; 114 | } 115 | 116 | this.backDisplay = function() { 117 | stroke(0); 118 | strokeWeight(1); 119 | push(); 120 | strokeWeight(3); 121 | fill('rgba(127,47,155, .2)'); 122 | ellipse(this.location.x, this.location.y, this.r, this.r); 123 | pop(); 124 | if (this.backconnects.length != 0) { 125 | push(); 126 | fill(0, 102, 153); 127 | textSize(14); 128 | text("b= "+Math.round(this.bias * 10000) / 10000, this.location.x - 26, this.location.y + 35); 129 | pop(); 130 | } 131 | if (this.sig){ 132 | push(); 133 | fill(0, 102, 153); 134 | textSize(14); 135 | text("\u03c3= "+Math.round(this.sig * 1000000)/1000000, this.location.x - 26, this.location.y-32); 136 | pop(); 137 | } 138 | this.r = lerp(this.r, 32, 0.1); 139 | } 140 | 141 | this.display = function() { 142 | stroke(0); 143 | strokeWeight(1); 144 | push(); 145 | strokeWeight(3); 146 | fill('rgba(0, 220, 236, .2)'); 147 | ellipse(this.location.x, this.location.y, this.r, this.r); 148 | pop(); 149 | if (this.backconnects.length != 0) { 150 | push(); 151 | fill(0, 102, 153); 152 | textSize(14); 153 | text("b= "+Math.round(this.bias * 10000) / 10000, this.location.x - 26, this.location.y + 35); 154 | pop(); 155 | } 156 | if (this.sig){ 157 | push(); 158 | fill(0, 102, 153); 159 | textSize(14); 160 | text("\u03c3= "+Math.round(this.sig * 1000000)/1000000, this.location.x - 26, this.location.y-32); 161 | pop(); 162 | } 163 | 164 | // Shrink interpolation 165 | this.r = lerp(this.r,32,0.1); 166 | } 167 | } 168 | 169 | // ################### 170 | // Connection Object 171 | // ################### 172 | 173 | var Connection = function(a, b, weight) { 174 | // Connection is from Neuron A to B 175 | this.a = a; 176 | this.b = b; 177 | this.weight = weight || random(-1, 1); 178 | this.sending = false; 179 | this.output = 0; 180 | this.sender = createVector(this.a.x, this.a.y); 181 | this.learningRate = .3; 182 | this.lastVal; 183 | this.backing = false; 184 | this.batch = false; 185 | //For backprop 186 | this.da; 187 | this.dw; 188 | 189 | // The Connection is active 190 | this.feedforward = function(val) { 191 | this.lastVal = val; 192 | this.output = val*this.weight; // Compute output 193 | this.sender.x = this.a.location.x; 194 | this.sender.y = this.a.location.y; 195 | this.sending = true; // Turn on sending 196 | if (this.batch) { 197 | this.b.feedforward(this.output); 198 | this.sending = false; 199 | this.batch = false; 200 | 201 | } 202 | } 203 | 204 | //Backpropagation of weight 205 | this.backprop = function(grad) { 206 | //Accepts gradient coming from prior node 207 | this.dw = this.lastVal * grad; 208 | this.da = this.weight * grad; 209 | this.weight += -this.learningRate * this.dw; 210 | this.sender.x = this.b.location.x; 211 | this.sender.y = this.b.location.y; 212 | this.backing = true; 213 | if (this.batch) { 214 | this.a.backprop(this.da); 215 | this.backing = false; 216 | this.batch = false; 217 | } 218 | 219 | } 220 | 221 | // Update traveling sender 222 | this.update = function() { 223 | if (this.sending) { 224 | // Use a simple interpolation 225 | this.sender.x = lerp(this.sender.x, this.b.location.x, 0.1); 226 | this.sender.y = lerp(this.sender.y, this.b.location.y, 0.1); 227 | dist = p5.Vector.dist(this.sender, this.b.location); 228 | // If we've reached the end 229 | if (dist < 1) { 230 | // Pass along the output! 231 | this.b.feedforward(this.output); 232 | this.sending = false; 233 | } 234 | } else if (this.backing) { 235 | this.sender.x = lerp(this.sender.x, this.a.location.x, 0.1); 236 | this.sender.y = lerp(this.sender.y, this.a.location.y, 0.1); 237 | dist = p5.Vector.dist(this.sender, this.a.location); 238 | if (dist < 1) { 239 | this.a.backprop(this.da); 240 | this.backing = false; 241 | } 242 | } 243 | } 244 | 245 | this.backDisplay = function () { 246 | stroke(0); 247 | push(); 248 | strokeWeight(3); 249 | // seed = map(this.weight, -1, 1, 0, 1); 250 | // from = color(100, 0, 255); 251 | // to = color(255, 13, 101); 252 | // hue = lerpColor(from, to, seed); 253 | stroke(0); 254 | line(this.a.location.x, this.a.location.y, this.b.location.x, this.b.location.y); 255 | pop(); 256 | fill(0); 257 | 258 | push(); 259 | angle = p5.Vector.angleBetween(this.a.location, this.b.location); 260 | strokeWeight(1); 261 | translate(((this.b.location.x + this.a.location.x)/2.0) 262 | ,((this.b.location.y + this.a.location.y)/2.0)); 263 | if (this.a.location.y > this.b.location.y) { 264 | rotate(-angle); 265 | } else { 266 | rotate(angle); 267 | } 268 | fill(245, 81, 55); 269 | textSize(18); 270 | strokeWeight(3); 271 | text(Math.round(this.weight*10000)/10000,-20,0); 272 | pop(); 273 | 274 | if (this.backing) { 275 | //moving elipse backwards 276 | fill(127,47,155); 277 | strokeWeight(1); 278 | ellipse(this.sender.x, this.sender.y, 16, 16); 279 | } 280 | 281 | } 282 | 283 | // Draw line and traveling circle 284 | this.display = function() { 285 | stroke(0); 286 | push(); 287 | strokeWeight(3); 288 | // seed = map(this.weight, -1, 1, 0, 1); 289 | // from = color(25, 0, 255); 290 | // to = color(255, 17, 9); 291 | // hue = lerpColor(from, to, seed); 292 | stroke(0); 293 | line(this.a.location.x, this.a.location.y, this.b.location.x, this.b.location.y); 294 | pop(); 295 | fill(0); 296 | push(); 297 | angle = p5.Vector.angleBetween(this.a.location, this.b.location); 298 | strokeWeight(1); 299 | translate(((this.b.location.x + this.a.location.x)/2.0) 300 | ,((this.b.location.y + this.a.location.y)/2.0)); 301 | if (this.a.location.y > this.b.location.y) { 302 | rotate(-angle); 303 | } else { 304 | rotate(angle); 305 | } 306 | fill(34, 214, 37); 307 | textSize(18); 308 | strokeWeight(3); 309 | text(Math.round(this.weight*10000)/10000,-20,0); 310 | pop(); 311 | 312 | if (this.sending) { 313 | fill(0, 220, 236); 314 | strokeWeight(1); 315 | ellipse(this.sender.x, this.sender.y, 16, 16); 316 | } 317 | } 318 | } 319 | 320 | var Network = function (inBoxes, layers, neurons, connections, location) { 321 | 322 | // The Network has a list of neurons 323 | this.state = 'forward' 324 | this.neurons = neurons || []; 325 | this.connections = connections || []; 326 | this.location = location || createVector(0, 0); 327 | this.inBoxes = inBoxes || []; 328 | this.layers = layers || []; 329 | this.targetlocs = []; 330 | this.targets = [0, 1, 0]; 331 | this.outputs = []; 332 | this.start = false; 333 | 334 | this.createTargets = function () { 335 | 336 | for (i=this.layers[this.layers.length - 1]; i>0; i--){ 337 | loc = this.neurons[this.neurons.length - 4 + i].location; 338 | newloc = createVector(loc.x + 120, loc.y); 339 | this.targetlocs[i - 1] = newloc; 340 | //Bootstrapping this to keep track of outputs 341 | this.outputs[i - 1] = this.neurons[this.neurons.length - 4 + i]; 342 | } 343 | } 344 | 345 | // We can add a Neuron 346 | this.addNeuron = function (n) { 347 | this.neurons.push(n); 348 | } 349 | 350 | // We can connection two Neurons 351 | this.connect = function (a, b, weight) { 352 | c = new Connection(a, b, weight); 353 | a.addConnection(c); 354 | b.backConnect(c); 355 | this.connections.push(c); 356 | } 357 | 358 | 359 | // Sending an input to the first Neuron 360 | // We should do something better to track multiple inputs 361 | this.feedforward = function() { 362 | if (this.state == 'batch'){ 363 | console.log("batch forward Network"); 364 | n1 = this.neurons[0]; 365 | n1.batch = true; 366 | n1.fire(); 367 | 368 | n2 = this.neurons[1]; 369 | n2.batch = true; 370 | n2.fire(); 371 | 372 | n3 = this.neurons[2]; 373 | n3.batch = true; 374 | n3.fire(); 375 | } else { 376 | n1 = this.neurons[0]; 377 | n1.fire(); 378 | 379 | n2 = this.neurons[1]; 380 | n2.fire(); 381 | 382 | n3 = this.neurons[2]; 383 | n3.fire(); 384 | } 385 | 386 | } 387 | 388 | //Backward prop 389 | this.backprop = function() { 390 | //Get predictions and prep softmax normalization 391 | outs = []; 392 | sum = 0; 393 | for (i in this.outputs){ 394 | outs[i] = this.outputs[i].sig; 395 | sum += Math.exp(outs[i]); 396 | } 397 | 398 | //normalize and gradient of loss (softmax) 399 | douts = []; 400 | for (i in outs) { 401 | outs[i] = Math.exp(outs[i]) / sum; 402 | if (this.targets[i] == 1){ 403 | douts[i] = outs[i] - 1; 404 | } else { 405 | douts[i] = outs[i]; 406 | } 407 | } 408 | //pass loss values onto neurons for dw,db calcs 409 | if (this.state == 'batch'){ 410 | for (i in this.outputs) { 411 | this.outputs[i].batch = true; 412 | this.outputs[i].backprop(douts[i]); 413 | } 414 | } else { 415 | for (i in this.outputs) { 416 | this.outputs[i].backprop(douts[i]); 417 | } 418 | } 419 | } 420 | 421 | // Update the connections 422 | this.update = function() { 423 | 424 | for (c in this.connections) { 425 | this.connections[c].update(); 426 | } 427 | 428 | } 429 | 430 | // Draw everything 431 | this.display = function() { 432 | if (this.state == 'forward'){ 433 | push(); 434 | translate(this.location.x, this.location.y); 435 | for (n in this.neurons) { 436 | this.neurons[n].display(); 437 | } 438 | 439 | for (c in this.connections) { 440 | this.connections[c].display(); 441 | } 442 | pop(); 443 | } else if (this.state == 'backward') { 444 | push(); 445 | translate(this.location.x, this.location.y); 446 | for (n in this.neurons) { 447 | this.neurons[n].backDisplay(); 448 | } 449 | 450 | for (c in this.connections) { 451 | this.connections[c].backDisplay(); 452 | } 453 | pop(); 454 | 455 | } 456 | push(); 457 | fill(0); 458 | for (t in this.targets) { 459 | textSize(32); 460 | text(this.targets[t], this.targetlocs[t].x + 26, this.targetlocs[t].y); 461 | } 462 | textSize(42); 463 | text("Targets", this.targetlocs[0].x - 40, this.targetlocs[0].y - 50); 464 | pop(); 465 | } 466 | } 467 | 468 | function add(a, b) { 469 | return a + b; 470 | } 471 | 472 | function setup() { 473 | var myCanvas = createCanvas(windowWidth, windowHeight); 474 | myCanvas.parent('processing'); 475 | var layers = [3, 2, 3]; 476 | //var numNeurons = layers.reduce(add); 477 | var neurons = [[], [], []]; 478 | 479 | //Make these percentages later 480 | var forward = createButton('Forward'); 481 | forward.position(windowWidth - (windowWidth*.4), windowHeight - (windowHeight*.1)); 482 | forward.mousePressed(goForth); 483 | forward.addClass("btn btn-primary bg-green"); 484 | var backward = createButton('Backprop'); 485 | backward.position(windowWidth - (windowWidth*.65), windowHeight - (windowHeight*.1)); 486 | backward.mousePressed(backProp); 487 | backward.addClass("btn btn-primary bg-red"); 488 | // var batch = createButton('Batch'); 489 | // batchIn = createInput(20); 490 | // batchIn.position(windowWidth - 300, windowHeight - 50); 491 | // batch.position(windowWidth - 400, windowHeight - 50); 492 | // batch.mousePressed(batchTime); 493 | // batchTag = createP("batch running"); 494 | // batchTag.position(windowWidth - 300, windowHeight - 20); 495 | // batchTag.hide(); 496 | 497 | 498 | 499 | //Setting up text boxes for the input layers 500 | var inLayers = []; 501 | for (i = 0; iThe web is much more than just canvas and p5.dom makes it easy to interact 4 | * with other HTML5 objects, including text, hyperlink, image, input, video, 5 | * audio, and webcam.

6 | *

There is a set of creation methods, DOM manipulation methods, and 7 | * an extended p5.Element that supports a range of HTML elements. See the 8 | * 9 | * beyond the canvas tutorial for a full overview of how this addon works. 10 | * 11 | *

Methods and properties shown in black are part of the p5.js core, items in 12 | * blue are part of the p5.dom library. You will need to include an extra file 13 | * in order to access the blue functions. See the 14 | * using a library 15 | * section for information on how to include this library. p5.dom comes with 16 | * p5 complete or you can download the single file 17 | * 18 | * here.

19 | *

See tutorial: beyond the canvas 20 | * for more info on how to use this libary. 21 | * 22 | * @module p5.dom 23 | * @submodule p5.dom 24 | * @for p5.dom 25 | * @main 26 | */ 27 | 28 | (function (root, factory) { 29 | if (typeof define === 'function' && define.amd) 30 | define('p5.dom', ['p5'], function (p5) { (factory(p5));}); 31 | else if (typeof exports === 'object') 32 | factory(require('../p5')); 33 | else 34 | factory(root['p5']); 35 | }(this, function (p5) { 36 | // ============================================================================= 37 | // p5 additions 38 | // ============================================================================= 39 | 40 | /** 41 | * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' 42 | * prefixes to specify an ID or class respectively, and none for a tag) and returns it as 43 | * a p5.Element. If a class or tag name is given with more than 1 element, 44 | * only the first element will be returned. 45 | * The DOM node itself can be accessed with .elt. 46 | * Returns null if none found. 47 | * 48 | * @method select 49 | * @param {String} name id, class, or tag name of element to search for 50 | * @return {Object/p5.Element|Null} p5.Element containing node found 51 | */ 52 | p5.prototype.select = function (e) { 53 | var res; 54 | var str; 55 | if (e[0] === '.'){ 56 | str = e.slice(1); 57 | res = document.getElementsByClassName(str); 58 | if (res) { 59 | return wrapElement(res[0]); 60 | }else { 61 | return null; 62 | } 63 | }else if (e[0] === '#'){ 64 | str = e.slice(1); 65 | res = document.getElementById(str); 66 | if (res) { 67 | return wrapElement(res); 68 | }else { 69 | return null; 70 | } 71 | }else{ 72 | res = document.getElementsByTagName(e); 73 | if (res) { 74 | return wrapElement(res[0]); 75 | }else { 76 | return null; 77 | } 78 | } 79 | }; 80 | 81 | /** 82 | * Searches the page for elements with the given class or tag name (using the '.' prefix 83 | * to specify a class and no prefix for a tag) and returns them as p5.Elements 84 | * in an array. 85 | * The DOM node itself can be accessed with .elt. 86 | * Returns null if none found. 87 | * 88 | * @method selectAll 89 | * @param {String} name class or tag name of elements to search for 90 | * @return {Array} Array of p5.Elements containing nodes found 91 | */ 92 | p5.prototype.selectAll = function (e) { 93 | var arr = []; 94 | var res; 95 | var str; 96 | if (e[0] === '.'){ 97 | str = e.slice(1); 98 | res = document.getElementsByClassName(str); 99 | }else { 100 | res = document.getElementsByTagName(e); 101 | } 102 | if (res) { 103 | for (var j = 0; j < res.length; j++) { 104 | var obj = wrapElement(res[j]); 105 | arr.push(obj); 106 | } 107 | } 108 | return arr; 109 | }; 110 | 111 | /** 112 | * Helper function for getElement and getElements. 113 | */ 114 | function wrapElement(elt) { 115 | if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { 116 | return new p5.MediaElement(elt); 117 | } else { 118 | return new p5.Element(elt); 119 | } 120 | } 121 | 122 | /** 123 | * Removes all elements created by p5, except any canvas / graphics 124 | * elements created by createCanvas or createGraphics. 125 | * Event handlers are removed, and element is removed from the DOM. 126 | * @method removeElements 127 | * @example 128 | *

129 | * function setup() { 130 | * createCanvas(100, 100); 131 | * createDiv('this is some text'); 132 | * createP('this is a paragraph'); 133 | * } 134 | * function mousePressed() { 135 | * removeElements(); // this will remove the div and p, not canvas 136 | * } 137 | *
138 | * 139 | */ 140 | p5.prototype.removeElements = function (e) { 141 | for (var i=0; i 1 && typeof args[1] === 'string'){ 225 | elt.alt = args[1]; 226 | } 227 | if (elt.complete){ 228 | setAttrs(); 229 | }else{ 230 | elt.onload = function(){ 231 | setAttrs(); 232 | } 233 | } 234 | self = addElement(elt, this); 235 | return self; 236 | }; 237 | 238 | /** 239 | * Creates an <a></a> element in the DOM for including a hyperlink. 240 | * Appends to the container node if one is specified, otherwise 241 | * appends to body. 242 | * 243 | * @method createA 244 | * @param {String} href url of page to link to 245 | * @param {String} html inner html of link element to display 246 | * @param {String} [target] target where new link should open, 247 | * could be _blank, _self, _parent, _top. 248 | * @return {Object/p5.Element} pointer to p5.Element holding created node 249 | */ 250 | p5.prototype.createA = function(href, html, target) { 251 | var elt = document.createElement('a'); 252 | elt.href = href; 253 | elt.innerHTML = html; 254 | if (target) elt.target = target; 255 | return addElement(elt, this); 256 | }; 257 | 258 | /** INPUT **/ 259 | 260 | 261 | /** 262 | * Creates a slider <input></input> element in the DOM. 263 | * Use .size() to set the display length of the slider. 264 | * Appends to the container node if one is specified, otherwise 265 | * appends to body. 266 | * 267 | * @method createSlider 268 | * @param {Number} min minimum value of the slider 269 | * @param {Number} max maximum value of the slider 270 | * @param {Number} [value] default value of the slider 271 | * @return {Object/p5.Element} pointer to p5.Element holding created node 272 | */ 273 | p5.prototype.createSlider = function(min, max, value, step) { 274 | var elt = document.createElement('input'); 275 | elt.type = 'range'; 276 | elt.min = min; 277 | elt.max = max; 278 | if (step) elt.step = step; 279 | if (value) elt.value = value; 280 | return addElement(elt, this); 281 | }; 282 | 283 | /** 284 | * Creates a <button></button> element in the DOM. 285 | * Use .size() to set the display size of the button. 286 | * Use .mousePressed() to specify behavior on press. 287 | * Appends to the container node if one is specified, otherwise 288 | * appends to body. 289 | * 290 | * @method createButton 291 | * @param {String} label label displayed on the button 292 | * @param {String} [value] value of the button 293 | * @return {Object/p5.Element} pointer to p5.Element holding created node 294 | */ 295 | p5.prototype.createButton = function(label, value) { 296 | var elt = document.createElement('button'); 297 | elt.innerHTML = label; 298 | elt.value = value; 299 | if (value) elt.value = value; 300 | return addElement(elt, this); 301 | }; 302 | 303 | /** 304 | * Creates a checkbox <input></input> element in the DOM. 305 | * 306 | * @method createCheckbox 307 | * @param {String} [label] label displayed after checkbox 308 | * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false. Unchecked if no value given 309 | * @return {Object/p5.Element} pointer to p5.Element holding created node 310 | */ 311 | p5.prototype.createCheckbox = function() { 312 | var elt = document.createElement('input'); 313 | elt.type = 'checkbox'; 314 | //checkbox must be wrapped in p5.Element before label so that label appears after 315 | var self = addElement(elt, this); 316 | self.checked = function(){ 317 | if (arguments.length === 0){ 318 | return self.elt.checked; 319 | }else if(arguments[0]){ 320 | self.elt.checked = true; 321 | }else{ 322 | self.elt.checked = false; 323 | } 324 | return self; 325 | }; 326 | this.value = function(val){ 327 | self.value = val; 328 | return this; 329 | }; 330 | if (arguments[0]){ 331 | var ran = Math.random().toString(36).slice(2); 332 | var label = document.createElement('label'); 333 | elt.setAttribute('id', ran); 334 | label.htmlFor = ran; 335 | self.value(arguments[0]); 336 | label.appendChild(document.createTextNode(arguments[0])); 337 | addElement(label, this); 338 | } 339 | if (arguments[1]){ 340 | elt.checked = true; 341 | } 342 | return self; 343 | }; 344 | 345 | /** 346 | * Creates a dropdown menu <select></select> element in the DOM. 347 | * @method createSelect 348 | * @param {boolean} [multiple] [true if dropdown should support multiple selections] 349 | * @return {Object/p5.Element} pointer to p5.Element holding created node 350 | */ 351 | p5.prototype.createSelect = function(mult) { 352 | var elt = document.createElement('select'); 353 | if (mult){ 354 | elt.setAttribute('multiple', 'true'); 355 | } 356 | var self = addElement(elt, this); 357 | self.option = function(name, value){ 358 | var opt = document.createElement('option'); 359 | opt.innerHTML = name; 360 | if (arguments.length > 1) 361 | opt.value = value; 362 | else 363 | opt.value = name; 364 | elt.appendChild(opt); 365 | }; 366 | self.selected = function(value){ 367 | var arr = []; 368 | if (arguments.length > 0){ 369 | for (var i = 0; i < this.elt.length; i++){ 370 | if (value.toString() === this.elt[i].value){ 371 | this.elt.selectedIndex = i; 372 | } 373 | } 374 | return this; 375 | }else{ 376 | if (mult){ 377 | for (var i = 0; i < this.elt.selectedOptions.length; i++){ 378 | arr.push(this.elt.selectedOptions[i].value); 379 | } 380 | return arr; 381 | }else{ 382 | return this.elt.value; 383 | } 384 | } 385 | }; 386 | return self; 387 | }; 388 | 389 | /** 390 | * Creates an <input></input> element in the DOM for text input. 391 | * Use .size() to set the display length of the box. 392 | * Appends to the container node if one is specified, otherwise 393 | * appends to body. 394 | * 395 | * @method createInput 396 | * @param {Number} [value] default value of the input box 397 | * @return {Object/p5.Element} pointer to p5.Element holding created node 398 | */ 399 | p5.prototype.createInput = function(value) { 400 | var elt = document.createElement('input'); 401 | elt.type = 'text'; 402 | if (value) elt.value = value; 403 | return addElement(elt, this); 404 | }; 405 | 406 | /** 407 | * Creates an <input></input> element in the DOM of type 'file'. 408 | * This allows users to select local files for use in a sketch. 409 | * 410 | * @method createFileInput 411 | * @param {Function} [callback] callback function for when a file loaded 412 | * @param {String} [multiple] optional to allow multiple files selected 413 | * @return {Object/p5.Element} pointer to p5.Element holding created DOM element 414 | */ 415 | p5.prototype.createFileInput = function(callback, multiple) { 416 | 417 | // Is the file stuff supported? 418 | if (window.File && window.FileReader && window.FileList && window.Blob) { 419 | // Yup, we're ok and make an input file selector 420 | var elt = document.createElement('input'); 421 | elt.type = 'file'; 422 | 423 | // If we get a second argument that evaluates to true 424 | // then we are looking for multiple files 425 | if (multiple) { 426 | // Anything gets the job done 427 | elt.multiple = 'multiple'; 428 | } 429 | 430 | // Now let's handle when a file was selected 431 | elt.addEventListener('change', handleFileSelect, false); 432 | 433 | // Function to handle when a file is selected 434 | // We're simplifying life and assuming that we always 435 | // want to load every selected file 436 | function handleFileSelect(evt) { 437 | // These are the files 438 | var files = evt.target.files; 439 | // Load each one and trigger a callback 440 | for (var i = 0; i < files.length; i++) { 441 | var f = files[i]; 442 | var reader = new FileReader(); 443 | reader.onload = makeLoader(f); 444 | function makeLoader(theFile) { 445 | // Making a p5.File object 446 | var p5file = new p5.File(theFile); 447 | return function(e) { 448 | p5file.data = e.target.result; 449 | callback(p5file); 450 | }; 451 | }; 452 | 453 | // Text of data? 454 | // This should likely be improved 455 | if (f.type === 'text') { 456 | reader.readAsText(f); 457 | } else { 458 | reader.readAsDataURL(f); 459 | } 460 | } 461 | } 462 | return addElement(elt, this); 463 | } else { 464 | console.log('The File APIs are not fully supported in this browser. Cannot create element.'); 465 | } 466 | }; 467 | 468 | 469 | /** VIDEO STUFF **/ 470 | 471 | function createMedia(pInst, type, src, callback) { 472 | var elt = document.createElement(type); 473 | if (typeof src === 'string') { 474 | src = [src]; 475 | } 476 | for (var i=0; i