i am traskA machine learning craftsmanship blog.
https://iamtrask.github.io/
Wed, 18 Jan 2017 18:25:16 +0000Wed, 18 Jan 2017 18:25:16 +0000Jekyll v3.3.1Tutorial: Deep Learning in PyTorch<p><b>EDIT:</b> <a href="http://pytorch.org/">A complete revamp of PyTorch</a> was released today (Jan 18, 2017), making this blogpost a bit obselete. I will update this post with a new Quickstart Guide soon, but for now you should check out their documentation.</a></p>
<p><b>This Blogpost Will Cover:</b></p>
<ul>
<li>Part 1: PyTorch Installation</li>
<li>Part 2: Matrices and Linear Algebra in PyTorch</li>
<li>Part 3: Building a Feedforward Network (starting with <a href="https://iamtrask.github.io/2015/07/12/basic-python-network/"><u>a familiar one</u></a>)</li>
<li>Part 4: The State of PyTorch</li>
</ul>
<p><b>Pre-Requisite Knowledge:</b></p>
<ul>
<li>Simple Feedforward Neural Networks (<a href="https://iamtrask.github.io/2015/07/12/basic-python-network/"><u>Tutorial</u></a>)</li>
<li>Basic Gradient Descent (<a href="http://iamtrask.github.io/2015/07/27/python-network-part2/"><u>Tutorial</u></a>)</li>
</ul>
<p><a href="http://torch.ch/">Torch</a> is one of the most popular Deep Learning frameworks in the world, dominating much of the research community for the past few years (only recently being rivaled by major Google sponsored frameworks <a href="https://www.tensorflow.org/">Tensorflow</a> and <a href="http://keras.io/">Keras</a>). Perhaps its only drawback to new users has been the fact that it requires one to know <a href="https://www.lua.org/">Lua</a>, a language that used to be very uncommon in the Machine Learning community. Even today, this barrier to entry can seem a bit much for many new to the field, who are already in the midst of learning a tremendous amount, much less a completely new programming language.</p>
<p>However, thanks to the wonderful and billiant <a href="https://github.com/hughperkins">Hugh Perkins</a>, Torch recently got a new face, <a href="https://github.com/hughperkins/pytorch">PyTorch</a>... and it's much more accessible to the python hacker turned Deep Learning Extraordinare than it's Luariffic cousin. I have a passion for tools that make Deep Learning accessible, and so I'd like to lay out a short "Unofficial Startup Guide" for those of you interested in taking it for a spin. Before we get started, however, a question:</p>
<p><b>Why Use a Framework like PyTorch? </b>In the past, I have advocated learning Deep Learning using only a matrix library. For the purposes of actually knowing what goes on under the hood, I think that this is essential, and the lessons learned from building things from scratch are real gamechangers when it comes to the messiness of tackling real world problems with these tools. However, when building neural networks in the wild (Kaggle Competitions, Production Systems, and Research Experiments), it's best to use a framework.</p>
<p><b>Why?</b> Frameworks such as PyTorch allow you (the researcher) to focus exclusively on your experiment and iterate very quickly. Want to swap out a layer? Most frameworks will let you do this with a single line code change. Want to run on a GPU? Many frameworks will take care of it (sometimes with 0 code changes). If you built the network by hand in a matrix library, you might be spending a few hours working out these kinds of modifications. So, for learning, use a linear algebra library (like Numpy). For applying, use a framework (like PyTorch). Let's get started!</p>
<p><b>For New Readers:</b> I typically tweet out new blogposts when they're complete <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading more in the future and thanks for all the upvotes on <a href="https://news.ycombinator.com/">Hacker News</a> and Reddit! They mean a lot to me.
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 1: Installation</h2>
<p><b>Install Torch:</b> The first thing you need to do is install torch and the "nn" package using luarocks. As torch is a very robust framework, the <a href="http://torch.ch/docs/getting-started.html#_">installation instructions</a> should work well for you. After that, you should be able to run: </p>
<blockquote>luarocks install nn</blockquote>
<p> and be good to go. If any of these steps fails to work, copy paste what looks like the "error" and error description (should just be one sentence or so) from the command line and put it into Google (as is common practice when installing).</p>
<p><b>Clone the Repository: </b> At the time of writing, PyTorch doesn't seem to be in the PyPI repository. So, we'll need to clone the repo in order to install it. Assuming you have <a href="https://git-scm.com/">git</a> already installed (hint hint... if not go install it and come back), you should open up your <a href="http://www.macworld.co.uk/feature/mac-software/get-more-out-of-os-x-terminal-3608274/">Terminal</a> application and navigate to an empty folder. Personally, I have a folder called "Laboratory" in my home directory (i.e. "cd ~/Laboratory/"), which cators to various <a href="https://en.wikipedia.org/wiki/Dexter's_Laboratory">childhood memories</a> of mine. If you're not sure where to put it, feel free to use your Desktop for now. Once there, execute the commands:</p>
<blockquote>
git clone https://github.com/hughperkins/pytorch.git<br />
cd pytorch/<br />
pip install -r requirements.txt<br />
pip install -r test/requirements.txt<br />
source ~/torch/install/bin/torch-activate<br />
./build.sh<br />
</blockquote>
<p>For me, this worked flawlessly, finishing with the statement</p>
<blockquote>
Finished processing dependencies for PyTorch===4.1.1-SNAPSHOT
</blockquote>
<p>If you also see this output at the bottom of your terminal, congraulations! You have successfully installed PyTorch!</p>
<p><b>Startup Jupyter Notebook:</b> While certainly not a requirement, I highly recommend playing around with this new tool using <a href="http://jupyter.readthedocs.io/en/latest/install.html">Jupyter Notebok</a>, which is <i>definitely</i> best <a href="http://jupyter.readthedocs.io/en/latest/install.html">installed using conda</a>. Take my word for it. Install it using conda. All other ways are madness.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 2: Matrices and Linear Algebra</h2>
<p>In the spirit of starting with the basics, neural networks run on linear algebra libraries. PyTorch is no exception. So, the simplest building block of PyTorch is its linear algebra library. </p>
<p><img class="img-responsive" width="100%" src="/img/pytorch_1.png" alt="" /></p>
<p>Above, I created 4 matrices. Notice that the library doesn't call them matrices though. It calls them <i>tensors</i>.</p>
<p><b>Quick Primer on Tensors:</b> A <i>Tensor</i> is just a more generic term than <i>matrix</i> or <i>vector</i>. 1-dimensional tensors are vectors. 2-dimensional tensors are matrices. 3+ dimensional tensors are just refered to as tensors. If you're unfamiliar with these objects, here's a quick summary. A vector is "a list of numbers". A matrix is "a list of lists of numbers". A 3-d tensor is "a list of lists of lists of numbers". A 4-d tensor is... See the pattern? For more on how vectors and matrices are used to make neural networks, see my first blog post on a <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">Neural Network in 11 lines of Python</a></p>
<p><b>PyTorch Tensors</b> There appear to be 4 major types of tensors in PyTorch: Byte, Float, Double, and Long tensors. Each tensor <i>type</i> corresponds to the type of number (and more importantly the size/preision of the number) contained in each place of the matrix. So, if a 1-d Tensor is a "list of numbers", a 1-d <i>Float</i> Tensor is a list of <u>floats</u>. As a general rule of thumb, for weight matries we use FloatTensors. For data matrices, we'll likely use either FloatTensors (for real valued inputs) or Long Tensors (for integers). I'm a little bit surprised to not see IntTensor anywhere. Perhaps it has yet to be wrapped or is just non-obvious in the API.</p>
<p>The final thing to notice is that the matries seem to come with lots of rather random looking numbers inside (but not sensibly random like "evenly random between 0 and 1"). This is actually a plus of the library in my book. Let me explain (skip 1 paragraph if you're familiar with this concept)</p>
<p><b>Why Seemingly Nonsenical Values:</b> When you create a new matrix in PyTorch, the framework goes and "sets aside" enough RAM memory to store your matrix. However, "setting aside" memory is completely different from "changing all the values in that memory to 0". "Setting aside" memory while also "changing all the values to 0" is more computationally expensive. It's nice that this library doesn't assume you want the values to be any particular way. Instead, it just sets aside memory and whatever 1s and 0s happen to be there from the last program that used that piece of RAM will show up in your matrix. In most cases, we're going to set the values in our matrices to be something else anyway (say... our input data values or a specific kind of random number range). So, the fact that it doesn't pre-set the matrix values saves you a bit of processing time, but the user needs to recognize that it's their responsibility to actively choose the values he/she wants in a matrix. Numpy is not like this, which make Numpy a bit more user friendly but also less computationally efficient.</p>
<p><b>Basic Linear Algebra Operations:</b> So, now that we know how to store numbers in PyTorch, lets talk a bit about how PyTorch manipulates them. How does one go about doing linear algebra in PyTorch?</p>
<p><b>The Basic Neural Network Operations: </b> Neural networks, amidst all their complexity, are actually mostly made up of rather simple operations. If you remember from <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">A Neural Network in 11 Lines of Python</a>, we can build a working network with only Matrix-Matrix Multiplication, Vector-Matrix Multiplication, Elementwise Operations (addition, subtraction, multiplication, and division), Matrix Transposition, and a handful of elementwise functions (sigmoid, and a special function to compute sigmoid's derivative at a point which uses only the aforementioned elementwise operations). Let's initialize some matrices and start with the elementwise operations.</p>
<p><img class="img-responsive" width="100%" src="/img/pytorch_2.png" alt="" /></p>
<p><b>Elementwise Operations:</b> Above I have given several examples of elementwise addition. (simply replacing the "+" sign with - * or / will give you the others). These act <i>mostly</i> how you would expect them to act. A few hiccups here and there. Notably, if you accidentally add two Tensors that aren't aligned correctly (have different dimensions) the python kernel crashes as opposed to throwing an error. It could be just my machine, but error handling in wrappers is notoriously time consuming to finish. I expect this functionality will be worked out soon enough, and as we will see, there's a suitable substitute. <p>
<p><b>Vector/Matrix Multiplication:</b> It appears that the native matrix multiplication functionality of Torch isn't wrapped. Instead, we get to use something a bit more familiar. (This feature is really, really cool.) <i>Much of PyTorch can run on native numpy matrices.</i> That's right! The convenient functionality of numpy is now integrated with one of the most popular Deep Learning Frameworks out there. So, how should you <i>really</i> do elementwise and matrix multipliplication? Just use numpy! For completeness sake, here's the same elementwise operations using PyTorch's numpy connector.</p>
<img class="img-responsive" width="100%" src="/img/pytorch_3.png" alt="" />
<p>And now let's see how to do the basic matrix operations we need for a feedforward network.</p>
<img class="img-responsive" width="100%" src="/img/pytorch_4.png" alt="" />
<p><b>Other Neural Functions:</b> Finally, we also need to be able to compute some nonlinearities efficiently. There are both numpy and native wrappers made available which seem to run quite fast. Additionally, sigmoid has a native implementation (something that numpy does not implement), which is quite nice and a bit faster than computing it explicitly in numpy.</p>
<img class="img-responsive" width="100%" src="/img/pytorch_5.png" alt="" />
<p>I consider the fantastic integration between numpy and PyTorch to be one of the great selling points of this framework. I personally love prototyping with the full control of a matrix library, and PyTorch really respects this preference as an option. This is so nice relative to most other frameworks out there. +1 for PyTorch.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 3: Building a Feedforward Network</h2>
<p>In this section, we really get to start seeing PyTorch shine. While understanding how matrices are handled is an important pre-requisite to learning a framework, the various layers of abstraction are where frameworks really become useful. In this section, we're going to take the bare bones 3 layer neural network from <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">a previous blogpost</a> and convert it to a network using PyTorch's neural network abstractions. In this way, as we wrap each part of the network with a piece of framework functionality, you'll know exactly what PyTorch is doing under the hood. Your goal in this section should be to relate the PyTorch abstractions (objects, function calls, etc.) in the PyTorch network we will build with the matrix operations in the numpy neural network (pictured below)s. </p>
<pre class="brush: python">
import PyTorch
from PyTorch import np
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
np.random.seed(1)
# randomly initialize our weights with mean 0
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
for j in range(60000):
# Feed forward through layers 0, 1, and 2
l0 = X
l1 = nonlin(np.dot(l0,syn0))
l2 = nonlin(np.dot(l1,syn1))
# how much did we miss the target value?
l2_error = y - l2
if (j% 10000) == 0:
print("Error:" + str(np.mean(np.abs(l2_error))))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
l2_delta = l2_error*nonlin(l2,deriv=True)
# how much did each l1 value contribute to the l2 error (according to the weights)?
l1_error = l2_delta.dot(syn1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
l1_delta = l1_error * nonlin(l1,deriv=True)
# lets update our weights
syn1 += l1.T.dot(l2_delta)
syn0 += l0.T.dot(l1_delta)
</pre>
<!-- <h3>Runtime Output:</h3> -->
<pre>
Error:0.496410031903
Error:0.00858452565325
Error:0.00578945986251
Error:0.00462917677677
Error:0.00395876528027
Error:0.00351012256786
</pre>
<p>Now that we've seen how to build this network (more or less "by hand"), let's starting building the same network using PyTorch instead of numpy.</p>
<pre class="brush: python">
import PyTorch
from PyTorchAug import nn
from PyTorch import np
</pre>
<p>First, we want to import several packages from PyTorch. <i>np</i> is the numpy wrapper mentioned before. <i>nn</i> is the <i>Neural Network</i> package, which contains things like layer types, error measures, and network containers, as we'll see in a second.</p>
<pre class="brush: python">
# randomly initialize our weights with mean 0
net = nn.Sequential()
net.add(nn.Linear(3, 4))
net.add(nn.Sigmoid())
net.add(nn.Linear(4, 1))
net.add(nn.Sigmoid())
net.float()
</pre>
<p>The next section highlights the primary advantage of deep learning frameworks in general. Instead of declaring a bunch of weight matrices (like with numpy), we create layers and "glue" them together using nn.Sequential(). Contained in these "layer" objects is logic about how the layers are constructed, how each layer forward propagates predictions, and how each layer backpropagates gradients. nn.Sequential() knows how to combine these layers together to allow them to learn together when presented with a dataset, which is what we'll do next.</p>
<pre class="brush: python">
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]]).astype('float32')
y = np.array([[0],
[1],
[1],
[0]]).astype('float32')
</pre>
<p>This section is largely the same as before. We create our input (X) and output (y) datasets as numpy matrices. PyTorch seemed to want these matrices to be float32 values in order to do the implicit cast from numpy to PyTorch tensor objects well, so I added an .astype('float32') to ensure they were the right type.</p>
<pre class="brush: python">
crit = nn.MSECriterion()
crit.float()
</pre>
<p>This one might look a little strange if you're not familiar with neural network error measures. As it turns out, you can measure "how much you missed" in a variety of different ways. How you measure error changes how a network prioritizes different errors when training (what kinds of errors should it take most seriously). In this case, we're going to use the "Mean Squared Error". For a more in-depth coverage of this, please see Chapter 4 of <a href="https://www.manning.com/books/grokking-deep-learning">Grokking Deep Learning</a>.
<pre class="brush: python">
for j in range(2400):
net.zeroGradParameters()
# Feed forward through layers 0, 1, and 2
output = net.forward(X)
# how much did we miss the target value?
loss = crit.forward(output, y)
gradOutput = crit.backward(output, y)
# how much did each l1 value contribute to the l2 error (according to the weights)?
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
gradInput = net.backward(X, gradOutput)
# lets update our weights
net.updateParameters(1)
if (j% 200) == 0:
print("Error:" + str(loss))
</pre>
<p>And now for the training of the network. I have annotated each section of the code with near identical annotations as the numpy network. In this way, if you look at them side by side, you should be able to see where each operation in the numpy network occurs in the PyTorch network.</p>
<p>One part might not look familiar. The "net.zeroGradParameters()" basically just zeros out all our "delta" matrices before a new iteration. In our numpy network, this was the l2_delta variable and l1_delta variable. PyTorch re-uses the same memory allocations each time you forward propgate / back propagate (to be efficient, similar to what was mentioned in the Matrices section), so in order to keep from accidentally re-using the gradients from the prevoius iteration, you need to re-set them to 0. This is also a standard practice for most popular deep learning frameworks.</p>
<p>Finally, Torch also separates your "loss" from your "gradient". In our (somewhat oversimplified) numpy network, we just computed an "error" measure. As it turns out, your pure "error" and "delta" are actually slightly different measures. (delta is the derivative of the error). Again, for deeper coverage, see Chatper 4 of <a href="https://www.manning.com/books/grokking-deep-learning">GDL</a>.
<p><b>Putting it all together</b></p>
<pre class="brush: python">
import PyTorch
from PyTorchAug import nn
from PyTorch import np
# randomly initialize our weights with mean 0
net = nn.Sequential()
net.add(nn.Linear(3, 4))
net.add(nn.Sigmoid())
net.add(nn.Linear(4, 1))
net.add(nn.Sigmoid())
net.float()
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]]).astype('float32')
y = np.array([[0],
[1],
[1],
[0]]).astype('float32')
crit = nn.MSECriterion()
crit.float()
for j in range(2400):
net.zeroGradParameters()
# Feed forward through layers 0, 1, and 2
output = net.forward(X)
# how much did we miss the target value?
loss = crit.forward(output, y)
gradOutput = crit.backward(output, y)
# how much did each l1 value contribute to the l2 error (according to the weights)?
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
gradInput = net.backward(X, gradOutput)
# lets update our weights
net.updateParameters(1)
if (j% 200) == 0:
print("Error:" + str(loss))
</pre>
<pre>
Error:0.2521711587905884
Error:0.2500123083591461
Error:0.249952495098114
Error:0.24984735250473022
Error:0.2495250701904297
Error:0.2475520819425583
Error:0.22693687677383423
Error:0.13267411291599274
Error:0.04083901643753052
Error:0.016316475346684456
Error:0.008736669085919857
Error:0.005575092509388924
</pre>
<p>Your results may vary a bit. I do not yet see how random numbers are to be seeded. If I come across that in the future, I'll add an edit.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 4: The State of PyTorch</h2>
<p>While still a new framework with lots of ground to cover to close the gap with its competitors, PyTorch already has a lot to offer. It looks like there's an LSTM test case in the works, and strong promise for building custom layers in .lua files that you can import into Python with some simple wrapper functions. If you want to build feedforward neural networks using the industry standard Torch backend without having to deal with Lua, PyTorch is what you're looking for. If you want to build custom layers or do some heavy sequence2sequence models, I think the framework will be there very soon (with documentation / test cases to describe best practices). Overall, I'm very excited to see where this framework goes, and I encourage you to <a href="https://github.com/hughperkins/pytorch">Star/Follow it on Github</a></p>
<p><b>For New Readers:</b> I typically tweet out new blogposts when they're complete at <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading more in the future and thanks for all the upvotes on hacker news and reddit!
</p>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p></p></p></p>
Sun, 15 Jan 2017 12:00:00 +0000
https://iamtrask.github.io/2017/01/15/pytorch-tutorial/
https://iamtrask.github.io/2017/01/15/pytorch-tutorial/Grokking Deep Learning<p>If you passed <u>high school math</u> and can hack around in Python, <u>I want to teach you Deep Learning</u>.</p>
<p><b>Edit: 50% Coupon Code:</b> "mltrask" (expires August 26)</p>
<p>I've decided to write a <a href="https://www.manning.com/books/grokking-deep-learning">Deep Learning book</a> in the same style as my blog, teaching Deep Learning from an <i>intuitive</i> perspective, all in Python, using only numpy. I wanted to make the <b>lowest possible barrier to entry</b> to learn Deep Learning.</p>
<p>Here's what you need to know:
<div style="padding-left:50px">• High School Math (basic algebra)<br />
• Python... the basics</div></p>
<p><b>The Problem</b> with most <i>entry level</i> Deep Learning resources these days is that they either assume advanced knowledge of Calculus, Linear Algebra, Differential Equations, and perhaps even Convex Optimization, or they just teach a "black box" framework like Torch, Keras, or TensorFlow (where you just hit "train" but you don't actually know what's going on under the hood). Both have their appropriate audience, but I don't believe that either are appropriate for your average python hacker looking for a 101 on the fundamentals.</p>
<p><b>My Solution</b> is to teach Deep Learning from an <i>intuitive standpoint</i>, just like I've done in the other posts on this blog. Everything you need to know to understand Deep Learning will be explained like you would to a <u>5 year old</u>, including the bits and pieces of Linear Algebra and Calculus that are necessary. You'll learn how neural networks work, and how to use them to classify images, understand language (including machine translation), and even play games.</p>
<p>At the time of writing, I think that this is the only Deep Learning resource that is taught this way. I hope you enjoy it.</p>
<p><b>Who This Book Is NOT For:</b> people who would rather be taught using formulas. Individuals with advanced mathematical backgrounds should choose another resource. This book is for an introduction to Deep Learning. It's about lowering the barrier to entry.</p>
<p><a href="https://www.manning.com/books/grokking-deep-learning">Click To See the Early Release Page (where the first three chapters are)</a></p>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
Wed, 17 Aug 2016 12:00:00 +0000
https://iamtrask.github.io/2016/08/17/grokking-deep-learning/
https://iamtrask.github.io/2016/08/17/grokking-deep-learning/How to Code and Understand DeepMind's Neural Stack Machine<p><b>Summary:</b> I learn best with toy code that I can play with. This tutorial teaches <a href="http://papers.nips.cc/paper/5648-learning-to-transduce-with-unbounded-memory.pdf">DeepMind's Neural Stack</a> machine via a very simple toy example, a short python implementation. I will also explain my thought process along the way for <b>reading and implementing research papers</b> from scratch, which I hope you will find useful.</p>
<p>I typically tweet out new blogposts when they're complete at <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading more in the future and thanks for all the feedback!
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading"><hr />Part 1: What is a Neural Stack?<br /><hr /></h2>
<p><br /></p>
<iframe width="700px" height="440px" src="https://www.youtube.com/embed/3DeL7utEz_k" frameborder="0" allowfullscreen=""></iframe>
<p><br /></p>
<h3>A Simple Stack</h3>
<p>Let's start with the definition of a regular stack before we get to a neural one. In computer science, a stack is a type of data structure. Before I explain it, let me just show it to you. In the code below, we "stack" a bunch of harry potter books on an (ascii art) table.</p>
<iframe src="https://trinket.io/embed/python/e887f17901" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>
<p>Just like in the example above, picture yourself stacking Harry Potter books onto a table. A stack is pretty much the same as a list with one exception: <i>you can't add/remove a book to/from anywhere except the top</i>. So, you can add another to the top ( stack.push(book) ) or you can remove a book from the top ( stack.pop() ), however you can't do anything with the books in the middle. <b>Pushing</b> when we add a book to the top. <b>Popping</b> is when we remove a book from the top (and perhaps do something with it :) )</p>
<p><br /></p>
<h3>A Neural Stack</h3>
<p>
A close eye might ask, "We learn things with neural networks. What is there to learn with a data structure? Why would you learn how to do what you can easily code?" A neural stack is still just a stack. However, our neural network will learn <b>how to use the stack</b> to implement an algorithm. It will learn <b>when to push and pop</b> to correctly model output data given input data.
</p>
<center><p><b>How will a neural network learn when to push and pop?</b></p></center>
<p>A neural network will learn to push and pop using backpropgation. Certainly a pre-requisite to this blogpost is an intuitive understanding of neural networks and backpropagation in general. Everything in <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/"> this blogpost </a>will be enough.</p>
<p>So, how will a neural network learn when to push and pop? To answer this question, we need to understand what a "correct sequence" of pushing and popping would look like? And that's right... it's a "sequence" of pushing and popping. So, that means that our <b>input data</b> and our correct <b>output data</b> will both be sequences. So, what kinds of sequences are stacks good at modeling?</p>
<iframe src="https://trinket.io/embed/python/3e7f031729?start=result" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>
<p>When we push a sequence onto a stack, and then pop that sequence off of the stack. The squence pops off in <b>reverse order</b> to the original sequence that was pushed. So, if you have a sequence of 6 numbers, pushing 6 times and then popping 6 times is the <b>correct sequence</b> of pushing and popping to reverse a list.</p>
<h3>...so What is a Neural Stack?</h3>
<p>A Neural Stack is a stack that can learn to correctly accept a sequence of inputs, remember them, and then transform them according to a pattern learned from data.
<h3>...and How Does It Learn?</h3>
<p>A Neural Stack learns by: <br />
<br />
<b>1)</b> accepting input data, pushing and popping it according to when a neural network says to push and pop. This generates a sequence of output data (predictions).<br />
<br />
<b>2)</b> Comparing the output data to the input data to see how much the neural stack "missed".<br />
<br />
<b>3)</b> Updating the neural network to more correctly push and pop next time. (using backpropagation)<br />
<br />
... so basically... just like every other neural network learns...
</p>
<p>And now for the money question...</p>
<p><b>Money Question:</b> How does backpropagation learn to push and pop when the error is on the output of the stack and the neural network is on the input to the stack? Normally we backpropagate the error from the output of the network to the weights so that we can make a weight update. It seems like the stack is "blocking" the output from the decision making neural network (which controls the pushing and popping).</p>
<p><b>Money Answer:</b> We make the neural stack "differentiable". If you haven't had calculus, the simplest way to think about it is that we will make the "neural stack" using a sequence of vector additions, subtractions, and multiplications. If we can figure out how to mimic the stack's behaviors using only these tools, then we will be able to backpropagate the error <b>through the stack</b> just like we backpropagate it through a neural network's hidden layers. And it will be quite familiar to us! We're already used to backpropagating through sequences of additions, subtractions, and multiplications. Figuring out how to mimic the operations of a stack in a fully differentiable way was the hard part... which why Edward Grefenstette, Karl Moritz Hermann, Mustafa Suleyman, and Phil Blunsom are so brilliant!!!</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading"><hr />Part 2: Reading and Implementing Academic Papers<br /><hr /></h2>
<br />
<iframe width="700px" height="440px" src="https://www.youtube.com/embed/P7LiUOd8kdg" frameborder="0" allowfullscreen=""></iframe>
<br />
<h3>Where To Start....</h3>
<p>As promised, I want to give a bit of "meta-learning" regarding how to approach implementing academic papers. So, pop open <a href="http://arxiv.org/pdf/1506.02516v3.pdf">this paper</a> and have a look around. As a disclaimer, <b>there is no correct way</b> to read academic papers. I wish only to share how I approached this one and why. Feel free to take any/all of it with a grain of salt. If you have lessons to add from experience, please comment on the hacker news or reddit posts if you came from there... or feel free to tweet <a href="https://twitter.com/iamtrask">@iamtrask</a>. I'm happy to retweet good advice on this topic.</p>
<p><b>First Pass:</b> Most people I know start by just reading a paper start to finish. Don't try to understand everything. Just get the high level goal of what's being accomplished, the key vocabulary terms involved, and a sense of the approach. Don't worry too much about formulas. Take time to look at pictures and tables. This paper has lots of good ones, which is helpful too. :) If this paper were about how to build a car, this first pass is just about learning "We're going to build a driving machine. It's going to be able to move and turn at 60 miles per hour down a curvy road. It runs on gasolean and has wheels. I think it will be driven by a human being." Don't worry about the alternator, transmission, or spark plugs... and certainly not the optimal temperature for combustion. Just get the general idea.</p>
<p><b>Second Pass:</b> For the second pass, if you feel like you understand the background (which is always the first few sections... commonly labeled "Introduction" and "Related Work"), jump straight to the approach. In this paper the approach section starts with "3 Models" at the bottom of page 2. For this section, read each sentence <b>slowly</b>. These sections are almost always <b>extremely</b> dense. Each sentence is crafted with care, and without an understanding of each sentence in turn, the next might not make sense. At this point, still don't worry too much about the details of the formulas. Instead, just get an idea of the "major moving parts" in the algorithm. Focus on the <b>what</b> not the <b>how</b>. Again, if this were about building a car, this is about making a list of what each part is called and what it generally does like below... </p>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;text-align:center;}
.tg .tg-5rcs{font-weight:bold;font-size:20px;}
.tg .tg-4kyz{font-size:20px;text-align:center;}
</style>
<center>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="1">Part Name</th>
<th class="tg-5rcs" colspan="1">Variable</th>
<th class="tg-5rcs" colspan="1">Description When First Reading</th>
</tr>
<tr>
<td class="tg-4kyz">"The Memory"</td>
<td class="tg-4kyz">V_t</td>
<td class="tg-4kyz">Sortof like "self.contents" in our <br />VerySimpleStack. This is where<br /> our stuff goes. More specifically, this is the state of our stack at timestep "t".</td>
</tr>
<tr>
<td class="tg-4kyz">"The Controller"</td>
<td class="tg-4kyz">?</td>
<td class="tg-4kyz">The neural network that <br /> decides when to push or pop.</td>
</tr>
<tr>
<td class="tg-4kyz">"Pop Signal"</td>
<td class="tg-4kyz">u_t</td>
<td class="tg-4kyz">How much the controller wants to pop.</td>
</tr>
<tr>
<td class="tg-4kyz">"Push Signal"</td>
<td class="tg-4kyz">d_t</td>
<td class="tg-4kyz">How much the controller wants to push.</td>
</tr>
<tr>
<td class="tg-4kyz">"Strength Signal"</td>
<td class="tg-4kyz">s_t</td>
<td class="tg-4kyz">Given u_t and d_t are real valued, it seems like we can push on or pop off "parts" of objects... <br /> This vector seems to keep up with how much of each variable we still have in V (or V_t really).</td>
</tr>
<tr>
<td class="tg-4kyz">"Read Value"</td>
<td class="tg-4kyz">v_t</td>
<td class="tg-4kyz">This seems to be made by combining s_t and V_t somehow.... so some sort of weighted average of what's on the stack... interesting....</td>
</tr>
<tr>
<td class="tg-4kyz">"Time"</td>
<td class="tg-4kyz">_t</td>
<td class="tg-4kyz">This is attached to many of the variables... i think it means the state of that variable at a specific timestep in the sequence.</td>
</tr>
</table>
</center>
<p>As a sidenote, this is also a great time to create some mental pneumonics to remember which variable is which. In this case, since the "u" in "u_t" is open at the top... I thought that it looked like it has been "popped" open. It's also the "pop signal". In contrast, "d_t" is closed on top and is the "push signal". I found that this helped later when trying to read the formulas intuitively (which is the next step). If you don't know the variables by heart, it's really hard to figure out how they relate to each other in the formulas.</p>
<p><b>N More Passes:</b> At this point, you just keep reading the method section until you have your working implementation (which you can evaluate using the later sections). So, this is generally how to read the paper. :)<br /><br />
<b>Have Questions? Stuck? Feel free to tweet your question <a href="https://twitter.com/iamtrask">@iamtrask</a> for help.</b></p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading"><hr />Part 3: Building a Toy Neural Stack<br /><hr /></h2>
<br />
<iframe width="700px" height="440px" src="https://www.youtube.com/embed/XhohuJzu-Lo" frameborder="0" allowfullscreen=""></iframe>
<br />
<h3>Where To Start....</h3>
<p>Ok, so we have a general idea of what's going on. Where do we start? I'm always tempted to just start coding the whole big thing but inevitably I get halfway through with bugs I'll never find again. So, a word from experience, break down each project into distinct, testable sections. In this case, the smallest testable section is the "stack mechanism" itself. Why? Well, the bottom of page 5 gives it away "the three memory modules... contain no tunable parameters to optimize during training". In a word, they're deterministic. To me, this is always the easiest place to start. Debugging something with deterministic, constant behavior is always easier than debugging something you learn/optimize/constantly changes. Furthermore, the stack logic is at the core of the algorithm. Even better, Figure 1 section (a) gives its expected behavior which we can use as a sort of "unit test". All of these things make this a great place to start. Let's jump right into understanding this portion by looking at the diagram of the stack's architecture.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_picture.png" alt="" />
<p><b>What I'm Thinking When I See This:</b> Ok... so we can push green vectors v_t onto the stack. Each yellow bubble on the right of each green v_t looks like it coresponds to the weight of v_t in the stack... which can be 0 apparently (according to the far right bubble). So, even though there isn't a legend, I suspect that the yellow circles are infact s_t. This is very useful. Furthermore, it looks like the graphs go from left to right. So, this is 3 timesteps. t=1, t=2, and t=3. Great. I think I see what's going on.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas.png" alt="" />
<p><b>What I'm Thinking:</b> Ok. I can line up the formulas with the picture above. The first formula sets each row of V_t which are the green bubbles. The second formula determines each row of s_t, which are the yellow bubbles. The final formula doesn't seem to be pictured above but I can see what its values are given the state of the stack. (e.g. r_3 = 0.9 * v_3 + 0 * v_2 + 0.1 * v_1) Now, what are these formulas really saying?</p>
<p>So, what we're going to try to do here is "tell the story" of each part of each formula in our head. Let's start with the first formula (1) which seems the least intimidating.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_1.png" alt="" />
<p>See the part circled in blue above? Notice that it's indexed by <b>two</b> numbers, t, and i. I actually overlooked this at first and it came back to bite me. V_t is the state of our stack's memory at time t. We can see its state in the picture at t=1, t=2, and t=3. However, at each timestep, the memory can have more than one value v_t inside of it! This will have significant implications for the code later (and the memory overhead).</p>
<p><b>Bottom Line:</b> If V_t is the state of the stack's memory at time "t", then V is a list of <b>ALL</b> of the memory states the stack goes through (at every timestep). So, V is a list of lists of vectors. (a vector is a list of numbers). In your head, you can think of this as the <b>shape</b> of V. Make sure you can look away and tell yourself what the shapes of V, V_t, and V_t[i] are. You'll need that kind of information on the fly when you're reading the rest of the paper.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_2.png" alt="" />
<p>Ok, so this next section defines a conditional function. In this case, that means that the function is different depending on what value "i" takes on. If our variable "i" is greater than or equal to 1 AND is less than t, then V_t[i] = V_t-1[i]. If, on the other hand, "i" equals "t", then V_t[i] = v_t.</p>
<p>So, what story is this telling? What is really going on? Well, what are we combining to make V_t[i]? We're either using V_t-1 or v_t. That's interesting. Also, since "i" determines each row of the stack, and we've got "if" statements depending on "i", that means that different rows of the stack are created differently. If "i" == "t"... which would be the newest member of the stack... then it's equal to some variable v_t. If not, hoever, then it seems like it equals whatever the previous timestep equaled at that row. Eureka!!!</p>
<p>So, all this formula is really saying is... each row of V_t is the same as it was in the previous timestep EXCEPT for the newest row v_t... which we just added! This makes total sense given that we're building a stack! Also, when we look at the picture again, we see that each timestep adds a new row... which is curious.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_picture.png" alt="" />
<p>Interesting... so we ALWAYS add a row. We ALWAYS add v_t. That's very interesting. This sounds like we're always pushing. V_t has t rows. That must be why "i" can range from 1 to "t". We have "t" rows for "i" to index.</p>
<p>Take a deep breath. This formula is actually pretty simple, although there are a few things to note that could trip us up in the implementation. First, "i" doesn't seem to be defined at 0 (by "not defined" i mean that they didn't tell us what to do if i == 0... so what do we do?). To me, this means that the original implementation was probably written in Torch (Lua) instead of Theano (Python) because "i" seems to range from 1 to t (as opposed to 0 to t). "i" is an index into an array. In Lua, the first value in an array or list is at index 1. In Python (the language we're prototyping in), the first value in an array or list is at index 0. Thus, we'll need to compensate for the fact that we're coding this network in a different langauge from the original by subtracting 1 from each index. It's a simple fix but perhaps easy to miss.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_3.png" alt="" />
<p>So, now that we finished the first formula, can you tell what shape s_t[i] is going to be? It's also indexed by both t and i. However, there's a key difference. The "s" is lowercased which means that s_t is a vector (whereas V_t was a list of vectors... e.g. a matrix). Since s_t is a vector, then s_t[i] is a value from that vector. So, what's the shape of "s"? It's a list of "t" vectors.It's a matrix. (I suppose V is technically a strange kind of tensor.)</p>
<pre class="brush: python">
def s_t(i,t,u,d):
if(i >= 0 and i < t):
inner_sum = sum(s[t-1][i+1:t])
out = max(0,s[t-1][i] - max(0,u[t] - (inner_sum)))
return out
elif(i == t):
return d[t]
else:
print "Undefined i -> t relationship"
</pre>
<p>When whe just do an exact representation of the function in code, we get the following function above.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_4.png" alt="" />
<p>This should be very familiar. Just like the first formula (1), formula (2) is also a conditional function based on "i" and "t". They're the same conditions so I suppose there's no additional explanation here. Note that the same 1 vs 0 indexing discrepancy between Lua and Python applies here. In the code, this blue circle is modeled on <b>line 02.</b></p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_5.png" alt="" />
<p>So, we have two conditions that are identical as before. This means that the bottom part of the function (circled in blue) is only true if "i" == "t". "i" only equals "t" when we're talking about the row corresponding to the newest vector on our stack. So, what's the value of s_t for the newest member of our stack? This is where we remember back to the definitions we wrote out earlier. s_t was the strength/weight of each vector on the stack. d_t was our pushing weight. s_t is the current strength. d_t is the weight we pushed it on the stack with.</p>
<p>Pause here... try to figure it out for yourself. What is the relationship between s_t[i] and d_t when i == t?</p>
<p>Aha! This makes sense! For the newest vector that we just put on the stack (V_t[t]), it is added to the stack with the <b>same weight</b> (s_t[i]) that we <b>push</b> it onto the stack with (d_t). That's brilliant! This also answers the question of why we push every time! "not pushing" just means "pushing" with a weight equal to 0! (e.g. d_t == 0) If we push with d_t equal to zero then the weight of that vector on the stack is also equal to 0. This section is represented on <b>line 07</b> in the code.</p>
<pre class="brush: python">
def s_t(i,t,u,d):
if(i >= 0 and i < t):
inner_sum = sum(s[t-1][i+1:t])
out = max(0,s[t-1][i] - max(0,u[t] - (inner_sum)))
return out
elif(i == t):
return d[t]
else:
print "Undefined i -> t relationship"
</pre>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_6.png" alt="" />
<p>Ok, now we're getting to the meat of a slightly more complicated formula. So, we're gong to break it into slightly smaller parts. I'm also re-printing the picture below to help you visualize the formula. This sum circled in blue sums from i+1 to t-1. Intuitively this is equivalent to summing "all of the weights between s_t[i] and the top of the stack". Stop here. Make sure you have that in your head.</p>
<p>Why t-1? Well, s_t-1 only runs to t-1. s_t-1[t] would overflow.</p>
<p>Why i+1? Well, think about being at the bottom of the ocean. Imagine that s_t is measuring the amount of water at each level in the ocean. Imagine then that the sum circled in blue is measuring "the weight of the water above me". I don't want to include the water even with me when measuring the "sum total amount of water between me and the ocean's surface." Perhaps I only want to measure the water that's "between me and the surface". That's why we start from i+1. I know that's kindof a silly analogy, but that's how I think about it in my head.</p>
<p>So, what's circled in blue is "the sum total amount of weight between the current strength and the top of the stack". We don't know what we're using it for yet, but just remember that for now.</p>
<pre class="brush: python">
def s_t(i,t,u,d):
if(i >= 0 and i < t):
inner_sum = sum(s[t-1][i+1:t])
out = max(0,s[t-1][i] - max(0,u[t] - (inner_sum)))
return out
elif(i == t):
return d[t]
else:
print "Undefined i -> t relationship"
</pre>
<p>In the code, this blue circle is represented on <b>line 03</b>. It's stored in the variable "inner_sum".</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_picture.png" alt="" />
<p>Look below at the circle in the next image. This is only a slight modification to the previous circle. So, if the previous circle was "the sum total amount of weight between the current strength adn the top of the stack", this is <b>"u_t" minus that weight</b>. Remember what u_t was? It's our pop weight! So, this circle is "the amount we want to pop MINUS the weight between the current index and the top of the stack". Stop here and make sure you can picture it.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_7.png" alt="" />
<p>
What does the blue circle above mean intuitively? Let's try the ocean floor analogy again except this time the ocean is dirt. You're buried alive. The sum from before is the sum total amount of weight above you. It's the sum total of all the dirt above you. u_t is the amount of dirt that can be "popped" off. So, if you're popping more than the amount of dirt above you, then this blue circle returns a positive number. You'll be uncovered! You'll be free! However, if u_t is smaller than the amount of dirt above you, then you'll still be buried. The circle will return "-1 * amount_of_dirt_still_above_me". This circle determines how deep in the dirt you are after dirt was popped off. Negative numbers mean you're still buried. Positive numbers mean you're above the ground. The next circle will reveal more about this. Stop and make sure you've got this in your head.
</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_8.png" alt="" />
<p>Now instead of picturing yourself as being under the ground, picture yourself as a gold digger from above ground. You're wanting to figure out how far you have to dig to get to some gold. You ask yourself, "if I did 10 meters, how much (if any) gold will I get). u_t is the 10 meters you're digging. The sum previously discussed is the distance from the gold to the surface of the ground. In this case, if u_t - the sum is negative, then you get no gold. If it is positive, then you get gold. That's why we take the max. At each level, we want to know if that vector will be popped off at all. Will the gold at that level be "removed" by popping "u_t" distance. Thus, this circle takes the "max between the difference and 0" so that the output is either "how much gold we get" or "0". The output is either "we're popping off this much" or it's "0". So, the "max" represents how much we have left to "pop" at the current depth in the stack. Stop here and make sure you've got this in your head.</p>
<pre class="brush: python">
def s_t(i,t,u,d):
if(i >= 0 and i < t):
inner_sum = sum(s[t-1][i+1:t])
out = max(0,s[t-1][i] - max(0,u[t] - (inner_sum)))
return out
elif(i == t):
return d[t]
else:
print "Undefined i -> t relationship"
</pre>
<p>Can you see the second "max" function on <b>line 04</b>. It is the code equivalent of the circled function above</p>.
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_9.png" alt="" />
<p>Almost there! So, if the max from the previous circle indicates "whether u_t is large enough to pop this row off (and if so how much of it)", then s_t-1[i] - that number is how much we have left after popping.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_10.png" alt="" />
<p>If the previous circle was "how much left we have after popping", then this just guarantees that we can only have a positive amount left, which is exactly the desirable property. So, this function is really saying: given how much we're popping off at this time step (u_t), and how much is between this row and the top of the stack, how much weight is left in this row? Note that u_t doesn't have any affect if i == t. (It has no affect on how much we push on d_t) This means that we're popping before we push at each timestep. Stop here and make sure this makes sense in your head.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_picture.png" alt="" />
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_11.png" alt="" />
<p>And now onto the third formula! This sum should look very familiar. The only difference between this sum and the sum in function (2) is that in this function we sum all the way to "t" instead of stopping at "t-1". This means that we're including the most recently pushed strength (s_t) in the sum. Previously we did not.</p>
<pre class="brush: python">
def r_t(t):
r_t_out = np.zeros(stack_width)
for i in xrange(0,t+1):
temp = min(s[t][i],max(0,1 - sum(s[t][i+1:t+1])))
r_t_out += temp * V[t][i]
return r_t_out
</pre>
<p>The circled sum above is represented with the "sum" function on <b>line 04</b> of this code. The circled (1 - sum) immediately below this paragraph is equivalent to the (1 - sum) on <b>line 04</b>.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_12.png" alt="" />
<p>This "1" means a lot more than you might think. As a sneak peek, this formula is reading from the stack. How many vectors is it reading? It's reading "1" deep into the stack. The previous sum calculates (for every row of s_t) the sum of all the weights above it in the stack. The sum calculates the "depth" if you were of each strength at index "i". Thus, 1 minus that strength calculates what's "left over". This difference will be positive for s_t[i] values that are less than 1.0 units deep in the stack. It will be negative for s_t[i] values that are deeper in the stack.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_13.png" alt="" />
<p>Taking the max of the previous circle guarantees that it's positive. The previous circle was negative for s_t[i] values that were deeper in the stack than 1.0. Since we're only interested in reading values up to 1.0 deep in the stack, all the weights for deeper values in the stack will be 0.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_14.png" alt="" />
<p>If the previous circle returned 1 - the sum of the weights above a layer in the stack, then it guarantees that the weight is 0 if the layer is too deep. However, if the vector is much shallower than 1.0, the previous circle would return a very positive number (perhaps as high as 1 for the vector at the top). This min function guarantees that the weight at this level doesn't exceed the strength that was pushed onto this level s_t[i].</p>
<pre class="brush: python">
def r_t(t):
r_t_out = np.zeros(stack_width)
for i in xrange(0,t+1):
temp = min(s[t][i],max(0,1 - sum(s[t][i+1:t+1])))
r_t_out += temp * V[t][i]
return r_t_out
</pre>
<p>So, the circle in the image above is represented as the variable "temp" created on <b>line 04</b>. The circled section below is the output of the entire function, stored as "r_t_out".
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas_15.png" alt="" />
<p>So, what does this function do? It performs a weighted sum over the entire stack, multiplying each vector by s_t, if that vector is less than 1.0 depth into the stack. In other words, it reads the top 1.0 weight off of the stack by performing a weighted sum of the vectors, weighted by s_t. This is the vector that is read at time t and put into the variable r_t.</p>
<h3>Writing the Code</h3>
<p>Ok, so now we have an intuitive understanding of what these formulas are doing. Where do we start coding? Recall the following figure.</p>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_picture.png" alt="" />
<p>Let's recreate this behavior given the values of u_t, d_t, and r_t above. Remember that many of the "time indices" will be decreased by 1 relative to the Figure 1 above because we're working in Python (instead of Lua).</p>
<iframe src="https://trinket.io/embed/python/6efe1b68ad?start=result" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>
<p>So, at risk of re-explaining all of the logic above, I'll point to which places in the code correspond to each function.</p>
<p><b>Lines 1 - 18</b> initialize all of our variables. v_0, v_1, and v_2 correspond to v_1, v_2, and v_3 in the picture of a stack operating. I made them be the rows of the identity matrix so that they'd be easy to see inside the stack. v_0 has a 1 in the first position (and zeros everywhere else). v_1 has a 1 in the second position, and v_2 has a 1 in the third position.</p>
<p><b>Lines 13-17</b> create our basic stack variables... all indexed by "t"</p>
<p><b>Lines 19-24</b> correspond to function (3).</p>
<p><b>Lines 26-33</b> correspond to function (2).</p>
<p><b>Lines 35-56</b> performs a push and pop operation on our stack</p>
<p><b>Lines 45-55</b> correspond to function (1). Notice that function (1) is more about how to create V_t given V_t-1.</p>
<p><b>Lines 58-60</b> run and print out the exact operations in the picture from the paper. Follow along to make sure you see the data flow!</p>
<p><b>Lines 62-66</b> reset the stack variables so we can make sure we got the outputs correct (by making sure they equal the values from the paper)</p>
<p><b>Lines 68-70</b> assert that the operations from the graph in the paper produce the correct results</p>
<b>Have Questions? Stuck? Feel free to tweet your question <a href="https://twitter.com/iamtrask">@iamtrask</a> for help.</b></p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading"><hr />Part 4: Learning A Sequence<br /><hr /></h2>
<br />
<iframe width="700px" height="440px" src="https://www.youtube.com/embed/kO5LfoPBWDQ" frameborder="0" allowfullscreen=""></iframe>
<br />
<p>In the last section, we learned the intuitions behind the neural stack mechanism's formulas. We then constructed those exact formulas in python code and validated that they behaved identically to the example laid out in Figure 1 (a) of the paper. In this section, we're going to dig further into how the neural stack works. We will then teach our neural stack to learn a single sequence using backpropagation.</p>
<h3>Let's Revisit How The Neural Stack Will Learn</h3>
<p>In Part 2, we discussed how the neural stack is unique in that we can backpropgate error from the output of the stack back through to the input. The reason we can do this is that the stack is fully differentiable. (For background on determining whether a function is differentiable, please see <a href="https://www.youtube.com/watch?v=pj1VvscsV0s"> Khan Academy </a>. For more on derivatives and differentiability, see the rest of that tutorial.) Why do we care that the stack (as a function) is differentiable? Well, we used the "derivative" of the function to move the error around (more specifically... to backpropagate). For more on this, please see the <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">Tutorial I Wrote on Basic Neural Networks</a>, <a href="https://iamtrask.github.io/2015/07/27/python-network-part2/"> Gradient Descent</a>, and <a href="https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/">Recurrent Neural Networks</a>. I particularly recommend the last one because it demontrates backpropgating through somewhat more arbitrary vector operations... kindof like what we're going to do here. :)</p>
<p>Perhaps you might say, "Hey Andrew, pre-requisite information is all nice and good... but I'd like a little bit more intuition on why this stack is differentiable". Let me try to simplify most of it to a few easy to use rules. Backpropagation is really about credit attribution. It's about the neural network saying "ok... I messed up. I was supposed to predict 1.0 but i predicted 0.9. What parts of the function caused me to do this? What parts can I change to better predict 1.0 next time?". Consider this problem.</p>
<pre class="brush: python">
y = a + b
</pre>
<p>What if I told you that when we ran this equation, y ended up being a little bit too low. It should have been 1.0 and it was 0.9. So, the error was <b>0.1</b>. Where did the error come from? Clearly. It came from both a and b equally. So, this gives us an early rule of thumb. When we're summing two variables into another variable. The error is divided evenly between the sum... becuase it's both their faults that it missed! This is a gross oversimplification of calculus, but it helps me remember how to do the chain rule in code on the fly... so I dunno. I find it helpful... at least as a pneumonic. Let's look at another problem.</p>
<pre class="brush: python">
y = a + 2*b
</pre>
<p>Same question. Different answer. In this case, the error is 2 times more significant because of b. So remember, when you are multiplying in the function, you have to multiply the error at any point by what that point was multiplied by. So, if the error at y is 0.1. The error at a is 0.1 and the error at b is 2 * 0.1 = 0.2. By the way, this generalizes to vector addition and multiplication as well. Consider in your head why the error would be twice as significant at b. Y is twice as sensitive to changes in b!</p>
<pre class="brush: python">
y = a*b
</pre>
<p>Ok, last one for now. If you compute 0.1 error at y, what is the error at a. Well, we can't really know without knowing what b is because b is determining how sensitive y is to a. Funny enough the reverse is also true. a is determining how sensitive y is to b! So, let's take this simple intuition and reflect on our neural stack in both the formal math functions and the code. (Btw, there are many more rules to know in Calculus, and I highly recommend taking a course on it from Coursera or Khan Academy, but these rules should pretty much get you through the Neural Stack)</p>
<pre class="brush: python">
def s_t(i,t,u,d):
if(i >= 0 and i < t):
inner_sum = sum(s[t-1][i+1:t])
out = max(0,s[t-1][i] - max(0,u[t] - (inner_sum)))
return out
elif(i == t):
return d[t]
else:
print "Undefined i -> t relationship"
def r_t(t):
r_t_out = np.zeros(stack_width)
for i in xrange(0,t+1):
temp = min(s[t][i],max(0,1 - sum(s[t][i+1:t+1])))
r_t_out += temp * V[t][i]
return r_t_out
</pre>
<img class="img-responsive" width="100%" src="/img/neural_stack/neural_stack_formulas.png" alt="" />
<p>Read through each formula. What if the output of our python function r_t(t) was supposed to be 1.0 and it returned 0.9. We would (again) have an error of <b>0.1</b>. Conceptually, this means we read our stack (by calling the function r_t(t)) and got back a number that was a little bit too low. So, can you see how we can take the simple rules above and move the error (0.1) from the output of the function (line 16) back through to the various inputs? In our case, those inputs include global variables s and V. It's really not any more complicated than the 3 rules we identified above! It's just a long chain of them. This would end up putting error onto s and V. This puts error onto the stack! I find this concept really fascinating. Error in memory! It's like telling the network "dude... you remembered the wrong thing man! Remember something more relevant next time!". Pretty sweet stuff.</p>
<p>So, if we were to code up this error attribution... this backpropagation. It would look like the following.</p>
<pre class="brush: python">
def s_t_error(i,t,u,d,error):
if(i >= 0 and i < t):
if(s_t(i,t,u,d) >= 0):
s_delta[t-1][i] += error
if(max(0,u[t] - np.sum(s[t-1][i+1:t-0])) >= 0):
u_delta[t] -= error
s_delta[t-1][i+1:t-0] += error
elif(i == t):
d_delta[t] += error
else:
print "Problem"
def r_t_error(t,r_t_error):
for i in xrange(0, t+1):
temp = min(s[t][i],max(0,1 - np.sum(s[t][i+1:t+1])))
V_delta[t][i] += temp * r_t_error
temp_error = np.sum(r_t_error * V[t][i])
if(s[t][i] < max(0,1 - np.sum(s[t][i+1:t+1]))):
s_delta[t][i] += temp_error
else:
if(max(0,1 - np.sum(s[t][i+1:t+1])) > 0):
s_delta[t][i+1:t+1] -= temp_error # minus equal because of the (1-).. and drop the 1
</pre>
<p>Notice that I have variables V_delta, u_delta, and s_delta that I put the "errors" into. These are identically shaped variables to V, u, and s respectively. It's just a place to put the delta (since there are already meaningful variables in the regular V, u, and s that I don't want to erase).</p>
<h3>From Error Propagation To Learning</h3>
<p>Ok, so now we know how to move error around through two of our fun stack functions. How does this translate to learning? What are we trying to learn anyway?</p>
<p>Let's think back to our regular stack again. Remember the toy problem we had before? If we pushed an entire sequence onto a stack and then popped it off, we'd get the sequence back in reverse. What this requires is the correct sequence of pushing and popping. So, what if we pushed 3 items on our stack, could we learn to correctly pop them off by adjusting u_t? Let's give it a shot!</p>
<p>Step one is to setup our problem. We need to pick a sequence, and initialize our u_t and d_t variables. (We're initializing both, but we're only going to try to adjust u_t). Something like this will do.</p>
<pre class="brush: python">
u_weights = np.array([0,0,0,0,0,0.01])
d_weights = np.array([1,1,1,0,0,0]).astype('float64')
# for i in xrange(1000):
stack_width = 2
copy_length = 5
sequence = np.array([[0.1,0.2,0.3],[0,0,0]]).T
# INIT
V = list() # stack states
s = list() # stack strengths
d = list() # push strengths
u = list() # pop strengths
V_delta = list() # stack states
s_delta = list() # stack strengths
d_delta = list() # push strengths
u_delta = list() # pop strengths
</pre>
<p>Ok, it's time to start "reading the net" a little bit. Notice that d_weights starts wtih three 1s in the first three positions. This is what's going to push our sequence onto the stack! By just fixing these weights to 1, we will push with a weight of 1 onto the stack. We're also jumping into something a bit fancy here but important to form the right picture of the stack in our heads. Our sequence has two dimensions and three values. The first dimension (column) has the sequence 0.1, 0.2, and 0.3. The second dimension is all zeros. So, the first item in our sequence is really [0.1, 0.0]. The second is [0.2,0.0]. We're only focusing on optimizing for (reversing) the sequence in the first column, but I want to use two dimensions so that we can make sure our logic is generalized to multi-dimensional sequence inputs. We'll see why later. :)</p>
<p>Also notice that we're initializing the "delta" variables. We also make a few changes to our functions from before to make sure we keep the delta variables maintaining the same shape as their respective base variables.</p>
<p><b>NOTE:</b> When you hit "Play", the browser may freeze temporarily. Just wait for it to finish. Could be a minute or two.</p>
<iframe src="https://trinket.io/embed/python/24f5f8fc11" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>
<p>So, at risk of making this blogpost too long (it probably already is), I'll leave it up to you to use what I've taught here and in previous blogposts to work through the backpropgation steps if you like. It's really just a sequence of applying the rules that we outlined above. Furthermore, everything else in the learning stack above is based on the concepts we already learned. I encourage you to play around with the code. All we did was backprop from the error in prediction back to the popping weight array u_weights... which stores the value we enter for u_t at each timestep. We then update the weights to apply a different u_t at the next iteration. To be clear, this is basically a neural network with only 3 parameters that we update. However, since that update is whether we pop or not, it has the opportunity to optimize this toy problem. Try to learn different sequences. Break it. Fix it. Play with it!</p>
<h3>The Next Level: Learning to Push</h3>
<p>So, why did we build that last toy example? Well, for me personally, I wanted to be able to sanity check that my backpropagation logic was correct. What better way to check that than to have it optimize the simplest toy problem I could surmise. This is another best practice. Validate as much as you can along the way. What I know so far is that the deltas showing up in u_delta are correct, and if I use them to update future values of u_t, then the network converges to a sequence. However, what about d_t? Let's try to optimize both with a slightly harder problem (but only slightly... remember... we're validating code). Notice that there are very few code changes. We're just harvesting the derivatives from d_t as well to update d_weights just like we did u_weights (run for more iterations to get better convergence).</p>
<iframe src="https://trinket.io/embed/python/98c8cf72d5" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>
<b>Have Questions? Stuck? Feel free to tweet your question <a href="https://twitter.com/iamtrask">@iamtrask</a> for help.</b></p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading"><hr />Part 5: Building a Neural Controller<br /><hr /></h2>
<p><br /></p>
<iframe width="700px" height="440px" src="https://www.youtube.com/embed/J6Zaugshvqs" frameborder="0" allowfullscreen=""></iframe>
<p><br /></p>
<p>We did it! At this point, we have built a neural stack and all of its components. However, there's more to do to get it to learn arbitrary sequences. So, for a little while we're going to return to some of our fundamentals of neural networks. The next phase is to control v_t, u_t, and d_t with an external neural network called a "Controller". This network will be a Recurrent Neural Network (because we're still modeling sequences). Thus, the knowledge of RNNs contained in the previous blogpost on <a href="http://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/">Recurrent Neural Networks</a> will be considered a pre-requisite.</p>
<p>To determine what kind of neural network we will use to control these various operations, let's take a look back at the formulas describing it in the paper.</p>
<p><img class="img-responsive" width="100%" src="/img/neural_stack/controller_formulas.png" alt="" /></p>
<p>The high level takeaway of these formulas is that all of our inputs to the stack are conditioned on a vector called o_prime_t. If you are familiar with vanilla neural networks already, then this should be easy work. The code for these functions looks something like this.</p>
<pre class="brush: python">
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def tanh(x):
return np.tanh(x)
o_prime_dim = 5
stack_width = 2
output_dim = 3
o_prime_t = np.random.rand(o_prime_dim) # random input data
# weight matrix
W_d = np.random.rand(o_prime_dim,1) * 0.2 - 0.1
# bias
b_d = np.random.rand(1) * 0.2 - 0.1
# weight matrix
W_u = np.random.rand(o_prime_dim,1) * 0.2 - 0.1
# bias
b_u = np.random.rand(1) * 0.2 - 0.1
# weight matrix
W_v = np.random.rand(o_prime_dim,stack_width) * 0.2 - 0.1
#bias
b_v = np.random.rand(stack_width) * 0.2 - 0.1
#weight matrix
W_o = np.random.rand(o_prime_dim,output_dim) * 0.2 - 0.1
#bias
b_o = np.random.rand(output_dim) * 0.2 - 0.1
#forward propagation
d_t = sigmoid(np.dot(o_prime_t,W_d) + b_d)
u_t = sigmoid(np.dot(o_prime_t,W_u) + b_u)
v_t = tanh(np.dot(o_prime_t,W_v) + b_v)
o_t = tanh(np.dot(o_prime_t,W_o) + b_o)
</pre>
<p>So, this is another point where it would be tempting to hook up all of these controllers at once, build and RNN, and see if it converges. However, this is not wise. Instead, let's (again) just bite off the smallest piece that we can test. Let's start by just controlling u_t and d_t with a neural network by altering our previous codebase. This is also a good time to add some object oriented abstraction to our neural stack since we won't be changing it anymore (make it work... THEN make it pretty :) )</p>
<p><b>Note:</b> I'm just writing the code inline for you to copy and run locally. This was getting a bit too computationally intense for a browser. I highly recommend downloading <a href="http://ipython.org/notebook.html">iPython Notebook</a> and running all the rest of the examples in this blog in various notebooks. That's what I used to develop them. They're extremely effective for experimention and rapid prototyping.</p>
<pre class="brush: python">
import numpy as np
np.random.seed(1)
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_out2deriv(out):
return out * (1 - out)
def tanh(x):
return np.tanh(x)
def tanh_out2deriv(out):
return (1 - out**2)
def relu(x,deriv=False):
if(deriv):
return int(x >= 0)
return max(0,x)
class NeuralStack():
def __init__(self,stack_width=2,o_prime_dim=6):
self.stack_width = stack_width
self.o_prime_dim = o_prime_dim
self.reset()
def reset(self):
# INIT STACK
self.V = list() # stack states
self.s = list() # stack strengths
self.d = list() # push strengths
self.u = list() # pop strengths
self.r = list()
self.o = list()
self.V_delta = list() # stack states
self.s_delta = list() # stack strengths
self.d_error = list() # push strengths
self.u_error = list() # pop strengths
self.t = 0
def pushAndPopForward(self,v_t,d_t,u_t):
self.d.append(d_t)
self.d_error.append(0)
self.u.append(u_t)
self.u_error.append(0)
new_s = np.zeros(self.t+1)
for i in xrange(self.t+1):
new_s[i] = self.s_t(i)
self.s.append(new_s)
self.s_delta.append(np.zeros_like(new_s))
if(len(self.V) == 0):
V_t = np.zeros((0,self.stack_width))
else:
V_t = self.V[-1]
self.V.append(np.concatenate((V_t,np.atleast_2d(v_t)),axis=0))
self.V_delta.append(np.zeros_like(self.V[-1]))
r_t = self.r_t()
self.r.append(r_t)
self.t += 1
return r_t
def s_t(self,i):
if(i >= 0 and i < self.t):
inner_sum = self.s[self.t-1][i+1:self.t-0]
return relu(self.s[self.t-1][i] - relu(self.u[self.t] - np.sum(inner_sum)))
elif(i == self.t):
return self.d[self.t]
else:
print "Problem"
def s_t_error(self,i,error):
if(i >= 0 and i < self.t):
if(self.s_t(i) >= 0):
self.s_delta[self.t-1][i] += error
if(relu(self.u[self.t] - np.sum(self.s[self.t-1][i+1:self.t-0])) >= 0):
self.u_error[self.t] -= error
self.s_delta[self.t-1][i+1:self.t-0] += error
elif(i == self.t):
self.d_error[self.t] += error
else:
print "Problem"
def r_t(self):
r_t_out = np.zeros(self.stack_width)
for i in xrange(0,self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
r_t_out += temp * self.V[self.t][i]
return r_t_out
def r_t_error(self,r_t_error):
for i in xrange(0, self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
self.V_delta[self.t][i] += temp * r_t_error
temp_error = np.sum(r_t_error * self.V[self.t][i])
if(self.s[self.t][i] < relu(1 - np.sum(self.s[self.t][i+1:self.t+1]))):
self.s_delta[self.t][i] += temp_error
else:
if(relu(1 - np.sum(self.s[self.t][i+1:self.t+1])) > 0):
self.s_delta[self.t][i+1:self.t+1] -= temp_error # minus equal becuase of the (1-).. and drop the 1
def backprop(self,all_errors_in_order_of_training_data):
errors = all_errors_in_order_of_training_data
for error in reversed(list((errors))):
self.t -= 1
self.r_t_error(error)
for i in reversed(xrange(self.t+1)):
self.s_t_error(i,self.s_delta[self.t][i])
u_weights = np.array([0,0,0,0,0,0.0])
o_primes = np.eye(6)
y = np.array([1,0])
W_op_d = (np.random.randn(6,1) * 0.2) - 0.2
b_d = np.zeros(1)
W_op_u = (np.random.randn(6,1) * 0.2) - 0.2
b_u = np.zeros(1)
for h in xrange(10000):
sequence = np.array([np.random.rand(3),[0,0,0]]).T
sequence = np.concatenate((sequence,np.zeros_like(sequence)))
stack = NeuralStack()
d_weights = sigmoid(np.dot(o_primes,W_op_d) + b_d)
u_weights = sigmoid(np.dot(o_primes,W_op_u) + b_u)
reads = list()
for i in xrange(6):
reads.append(stack.pushAndPopForward(sequence[i],d_weights[i],u_weights[i]))
reads = np.array(reads)
reads[:3] *= 0 # eliminate errors we're not ready to backprop
errors_in_order = reads - np.array(list(reversed(sequence)))
stack.backprop(errors_in_order)
# WEIGHT UPDATE
alpha = 0.5
u_delta = np.atleast_2d(np.array(stack.u_error) * sigmoid_out2deriv(u_weights)[0])
W_op_u -= alpha * np.dot(o_primes,u_delta.T)
b_u -= alpha * np.mean(u_delta)
d_delta = np.atleast_2d(np.array(stack.d_error) * sigmoid_out2deriv(d_weights)[0])
W_op_d -= alpha * np.dot(o_primes,d_delta.T)
b_d -= alpha * np.mean(d_delta)
for k in range(len(d_weights)):
if d_weights[k] < 0:
d_weights[k] = 0
if u_weights[k] < 0:
u_weights[k] = 0
if(h % 100 == 0):
print errors_in_order
</pre>
<h3>Runtime Output:</h3>
<pre>
[[ 0. 0. ]
[ 0. 0. ]
[ 0. 0. ]
[-0.79249511 0. ]
[-0.19810149 0. ]
[-0.14038694 0. ]]
.....
.....
.....
[[ 0. 0. ]
[ 0. 0. ]
[ 0. 0. ]
[-0.00174623 0. ]
[ 0.0023387 0. ]
[-0.00084291 0. ]]
</pre>
<p>Note that I'm logging errors this time instead of the discrete sequence.</p>
<p>All this code is doing is using two weight matrices W_op_u and W_op_d (and their biases) to predict u_t and d_t. We created mock o_prime_t variables to be different at each timestep. Instead of taking the delta at u_t and changing the u_weight directly. We used the delta at u_t to update the matrices W_op_u. Even though the code is cleaned up considerably, it's still doing the same thing for 99% of it.</p>
<h3>Building Out The Rest of the Controller</h3>
<p>So, all we're really doing now is taking the RNN from my previous blogpost on Recurrent Neural Networks and using it to generate o_prime_t. We then hook up the forward and backpropagation and we get the following code. I'm going to write the code in section here and describe (at a high level) what's going on. I'll then give you a single block with all the code together (that's runnable)</p>
<pre class="brush: python">
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_out2deriv(out):
return out * (1 - out)
def tanh(x):
return np.tanh(x)
def tanh_out2deriv(out):
return (1 - out**2)
def relu(x,deriv=False):
if(deriv):
return int(x >= 0)
return max(0,x)
</pre>
<p>Seen this before. Just some utility nonlinearities to use at various layers. Note that I'm using relu here instead of using the "max(0,x)" from before. They are identical. So, wherever you used to see "max(0," you will now see "relu(".</p>
<pre class="brush: python">
class NeuralStack():
def __init__(self,stack_width=2,o_prime_dim=6):
self.stack_width = stack_width
self.o_prime_dim = o_prime_dim
self.reset()
def reset(self):
# INIT STACK
self.V = list() # stack states
self.s = list() # stack strengths
self.d = list() # push strengths
self.u = list() # pop strengths
self.r = list()
self.o = list()
self.V_delta = list() # stack states
self.s_delta = list() # stack strengths
self.d_error = list() # push strengths
self.u_error = list() # pop strengths
self.t = 0
def pushAndPopForward(self,v_t,d_t,u_t):
self.d.append(d_t)
self.d_error.append(0)
self.u.append(u_t)
self.u_error.append(0)
new_s = np.zeros(self.t+1)
for i in xrange(self.t+1):
new_s[i] = self.s_t(i)
self.s.append(new_s)
self.s_delta.append(np.zeros_like(new_s))
if(len(self.V) == 0):
V_t = np.zeros((0,self.stack_width))
else:
V_t = self.V[-1]
self.V.append(np.concatenate((V_t,np.atleast_2d(v_t)),axis=0))
self.V_delta.append(np.zeros_like(self.V[-1]))
r_t = self.r_t()
self.r.append(r_t)
self.t += 1
return r_t
def s_t(self,i):
if(i >= 0 and i < self.t):
inner_sum = self.s[self.t-1][i+1:self.t-0]
return relu(self.s[self.t-1][i] - relu(self.u[self.t] - np.sum(inner_sum)))
elif(i == self.t):
return self.d[self.t]
else:
print "Problem"
def s_t_error(self,i,error):
if(i >= 0 and i < self.t):
if(self.s_t(i) >= 0):
self.s_delta[self.t-1][i] += error
if(relu(self.u[self.t] - np.sum(self.s[self.t-1][i+1:self.t-0])) >= 0):
self.u_error[self.t] -= error
self.s_delta[self.t-1][i+1:self.t-0] += error
elif(i == self.t):
self.d_error[self.t] += error
else:
print "Problem"
def r_t(self):
r_t_out = np.zeros(self.stack_width)
for i in xrange(0,self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
r_t_out += temp * self.V[self.t][i]
return r_t_out
def r_t_error(self,r_t_error):
for i in xrange(0, self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
self.V_delta[self.t][i] += temp * r_t_error
temp_error = np.sum(r_t_error * self.V[self.t][i])
if(self.s[self.t][i] < relu(1 - np.sum(self.s[self.t][i+1:self.t+1]))):
self.s_delta[self.t][i] += temp_error
else:
if(relu(1 - np.sum(self.s[self.t][i+1:self.t+1])) > 0):
self.s_delta[self.t][i+1:self.t+1] -= temp_error # minus equal becuase of the (1-).. and drop the 1
def backprop_single(self,r_t_error):
self.t -= 1
self.r_t_error(r_t_error)
for i in reversed(xrange(self.t+1)):
self.s_t_error(i,self.s_delta[self.t][i])
def backprop(self,all_errors_in_order_of_training_data):
errors = all_errors_in_order_of_training_data
for error in reversed(list((errors))):
self.backprop_single(error)
</pre>
<p>This is pretty much the same Neural Stack we developed before. I broke the "backprop" method into two methods: backprop and backprop_single. Backpropagating over all the timesteps can be done by calling backprop. If you just want to backprop a single step at a time (which was useful when making sure to backprop through the RNN), then call backprop_single.</p>
<pre class="brush: python">
options = 2
sub_sequence_length = 2
sequence_length = sub_sequence_length*2
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+1
sequence[-1] = 0
sequence
X = np.zeros((sub_sequence_length*2,options+1))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
Y[-i][sequence[i]] = 1
x_dim = X.shape[1]
h_dim = 16
o_prime_dim = 16
stack_width = options
y_dim = Y.shape[1]
</pre>
<p>This segment of code does a couple things. First, it constructs a training example sequence. "sub_sequence_length" is the lengh of the sequence that we want to remember and then reverse with the neural stack. "options" is the number of unique elements in the sequence. Setting options to 2 generates a binary sequence, which is what we're running here. The sequence_length is just double the sub_sequence_length. This is because we need to first encode the whole sequence and then decode the whole sequence. So, if the sub_sequence_length is of length 5, then we have to generate 10 training examples (5 encoding and 5 decoding). Note that we set the last number in the sequence to 0 which is a special index indicating that we have reached the end of the sequence. The network will learn to start reversing at this point.</p>
<p>X and Y are our input and output training examples respectively. They one-hot encode our training data for both inputs and outputs.</p>
<p>Finally, we have the dimensionality of our neural network. In accordance with the paper, we the input dimension x_dim (equal to the number of "options" in our sequence plus one special character for the end of sequence marker). We also have two hidden layers. "h_dim" refers to the hidden layer in the recurrent neural network. "o_prime_dim" is the second hidden layer (generated from the recurrent hidden layer) which sends information into our neural stack. We have set the dimensionality of both hidden layers to 16. Note that this is WAY smaller than the 256 and 512 size layers in the paper. For ease, we're going to work with shorter binary sequences which require smaller hidden layers sizes (mostly because of the number of options, not the length of the sequence...)</p>
<p>"stack_width" is still the width of the vectors on the stack. In this case, I'm setting it to the number of options so that it can (in theory) one hot encode the input data into the stack. In theory you could actually use log_base_2(options) but this level of compression just requires more training time. I tried several experiments making this bigger with mixed results.</p>
<p>"y_dim" is the dimensionality of the output sequence to be predicted. Note that this could be (in theory) any sequence, but in this case it is the reverse of the input.</p>
<pre class="brush: python">
W_xh = (np.random.rand(x_dim,h_dim)*0.2) - 0.1
W_xh_update = np.zeros_like(W_xh)
W_hh = (np.random.rand(h_dim,h_dim)*0.2) - 0.1
W_hh_update = np.zeros_like(W_hh)
W_rh = (np.random.rand(stack_width,h_dim)*0.2) - 0.1
W_rh_update = np.zeros_like(W_rh)
b_h = (np.random.rand(h_dim)*0.2) - 0.1
b_h_update = np.zeros_like(b_h)
W_hop = (np.random.rand(h_dim,o_prime_dim) * 0.2) - 0.1
W_hop_update = np.zeros_like(W_hop)
b_op = (np.random.rand(o_prime_dim)*0.2) - 0.1
b_op_update = np.zeros_like(b_op)
W_op_d = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_d_update = np.zeros_like(W_op_d)
W_op_u = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_u_update = np.zeros_like(W_op_u)
W_op_v = (np.random.rand(o_prime_dim,stack_width)*0.2) - 0.1
W_op_v_update = np.zeros_like(W_op_v)
W_op_o = (np.random.rand(o_prime_dim,y_dim)*0.2) - 0.1
W_op_o_update = np.zeros_like(W_op_o)
b_d = (np.random.rand(1)*0.2)+0.1
b_d_update = np.zeros_like(b_d)
b_u = (np.random.rand(1)*0.2)-0.1
b_u_update = np.zeros_like(b_u)
b_v = (np.random.rand(stack_width)*0.2)-0.1
b_v_update = np.zeros_like(b_v)
b_o = (np.random.rand(y_dim)*0.2)-0.1
b_o_update = np.zeros_like(b_o)
</pre>
<p>This initializes all of our weight matrices necessary for the Recurrent Neural Network Controller. I generally used the notation W_ for weight matrices and b_ for biases. Following the W is shorthand for what it connects from and to. For example, W_xh connects the input (x) to the recurrent hidden layer (h). "op" is shorthand for "o_prime".</p>
<p>There is one other note here that you can find in the appendix of the paper. Initialization of b_d and b_u has significant impact on how well the neural stack is learned. In general, if the first iterations of the network don't push anything onto the stack, then no derivatives will backpropagate THROUGH the stack, and the neural network will just ignore it. Thus, initializing b_d (the push bias) to a higher number (+0.1 instead of -0.1) encourages the network to push onto the neural stack during the beginning of training. This has a nice parallel intuition to life. If you had a stack but never pushed anything onto it... how would you know what it does? Generally the same thing going on here intuitively.</p>
<p>The reason we have _update variables is that we're going to be implementing mini-batch updates. Thus, we'll create updates and save them in the _update variables and only occasionally update the actual variables. This make for smoother training. See more on this in previous blogposts.</p>
<pre class="brush: python">
error = 0
max_len = 1
batch_size = 10
for it in xrange(1000000000):
sub_sequence_length = np.random.randint(max_len)+1
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+1
# sequence[-1] = 0
sequence
X = np.zeros((sub_sequence_length*2,options+1))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
X[i][0] = 1
Y[-i-1][sequence[i]] = 1
</pre>
<p>Ok, so the logic above that creates training examples doesn't exactly get used. I just use that section further up to experiment with the training example logic. I encourage you to do it. As you can see here, we randomly generate new training examples as we go. Note that "max_len" refers to the maximum length that we will model initially. As the error goes down (the neural network learns), this number will increase, modeling longer and longer sequences. Basically, we start by training the neural stack on short sequences, and once it gets good at those we start presenting longer ones. Experimenting with how long to start with was very fascinating to me. I highly encourage playing around with it.</p>
<pre class="brush: python">
layers = list()
stack = NeuralStack(stack_width=stack_width,o_prime_dim=o_prime_dim)
for i in xrange(len(X)):
layer = {}
layer['x'] = X[i]
if(i == 0):
layer['h_t-1'] = np.zeros(h_dim)
layer['h_t-1'][0] = 1
layer['r_t-1'] = np.zeros(stack_width)
layer['r_t-1'][0] = 1
else:
layer['h_t-1'] = layers[i-1]['h_t']
layer['r_t-1'] = layers[i-1]['r_t']
layer['h_t'] = tanh(np.dot(layer['x'],W_xh) + np.dot(layer['h_t-1'],W_hh) + np.dot(layer['r_t-1'],W_rh) + b_h)
layer['o_prime_t'] = tanh(np.dot(layer['h_t'],W_hop)+b_op)
layer['o_t'] = tanh(np.dot(layer['o_prime_t'],W_op_o) + b_o)
if(i < len(X)-1):
layer['d_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_d) + b_d)
layer['u_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_u) + b_u)
layer['v_t'] = tanh(np.dot(layer['o_prime_t'],W_op_v) + b_v)
layer['r_t'] = stack.pushAndPopForward(layer['v_t'],layer['d_t'],layer['u_t'])
layers.append(layer)
</pre>
<p>This is the forward propagation step. Notice that it's just a recurrent neural network with one extra input r_t-1 which is the neural stack r_t from the previous timestep. Generally, you can also see that x->h, h->o_prime, o_prime->stack_controllers, stack_controllers->stack, stack->r_t, and then r_t is fed into the next layer. Study this portion of code until the "information flow" becomes clear. Also notice the convention I use of storing the intermediate variables into the "layers" list. This will help make backpropagation easier later. Note that the prediction of the neural network is layer['o'] which isn't exactly what we read off of the stack. Information must travel from the stack to the hidden layer and out through layer['o']. We'll talk more about how to encourage this in a minute.</p>
<pre class="brush: python">
for i in list(reversed(xrange(len(X)))):
layer = layers[i]
layer['o_t_error'] = Y[i] - layer['o_t']
error += np.sum(np.abs(layer['o_t_error']))
if(it % 100 == 99):
if(i == len(X)-1):
if(it % 10000 == 9999):
print "MaxLen:"+str(max_len)+ " Iter:" + str(it) + " Error:" + str(error) + "True:" + str(sequence) + " Pred:" + str(map(lambda x:np.argmax(x['o_t']),layers[sub_sequence_length:]))
if(error < (5*max_len)):
max_len+=1
error = 0
# sub_sequence_length += 1
# print str(Y[i]) + " - " + str(layer['o_t']) + " = " + str(layer['o_t_error'])
layer['o_t_delta'] = layer['o_t_error'] * tanh_out2deriv(layer['o_t'])
layer['o_prime_t_error'] = np.dot(layer['o_t_delta'],W_op_o.T)
if(i < len(X)-1):
layer['r_t_error'] = layers[i+1]['r_t-1_error']
stack.backprop_single(layer['r_t_error'])
layer['v_t_error'] = stack.V_delta[i][i]
layer['v_t_delta'] = layer['v_t_error'] * tanh_out2deriv(layer['v_t'])
layer['o_prime_t_error'] += np.dot(layer['v_t_delta'],W_op_v.T)
layer['u_t_error'] = stack.u_error[i]
layer['u_t_delta'] = layer['u_t_error'] * sigmoid_out2deriv(layer['u_t'])
layer['o_prime_t_error'] += np.dot(layer['u_t_delta'],W_op_u.T)
layer['d_t_error'] = stack.d_error[i]
layer['d_t_delta'] = layer['d_t_error'] * sigmoid_out2deriv(layer['d_t'])
layer['o_prime_t_error'] += np.dot(layer['d_t_delta'],W_op_d.T)
layer['o_prime_t_delta'] = layer['o_prime_t_error'] * tanh_out2deriv(layer['o_prime_t'])
layer['h_t_error'] = np.dot(layer['o_prime_t_delta'],W_hop.T)
if(i < len(X)-1):
layer['h_t_error'] += layers[i+1]['h_t-1_error']
layer['h_t_delta'] = layer['h_t_error'] * tanh_out2deriv(layer['h_t'])
layer['h_t-1_error'] = np.dot(layer['h_t_delta'],W_hh.T)
layer['r_t-1_error'] = np.dot(layer['h_t_delta'],W_rh.T)
</pre>
<p>This is the backpropagation step. Again, we're just taking the delta we get from the neural stack and then backpropagating it through all the layers just like we did with the recurrent neural network in the previous blogpost. Also note the logic on lines 7-13. If the error gets below 5*max_len, then it increases the length of the sequence it's trying to model by 1 at the next iteration.</p>
<pre class="brush: python">
for i in xrange(len(X)):
layer = layers[i]
max_alpha = 0.005 * batch_size
alpha = max_alpha / sub_sequence_length
W_xh_update += alpha * np.outer(layer['x'],layer['h_t_delta'])
W_hh_update += alpha * np.outer(layer['h_t-1'],layer['h_t_delta'])
W_rh_update += alpha * np.outer(layer['r_t-1'],layer['h_t_delta'])
b_h_update += alpha * layer['h_t_delta']
W_hop_update += alpha * np.outer(layer['h_t'],layer['o_prime_t_delta'])
b_op_update += alpha * layer['o_prime_t_delta']
if(i < len(X)-1):
W_op_d_update += alpha * np.outer(layer['o_prime_t'],layer['d_t_delta'])
W_op_u_update += alpha * np.outer(layer['o_prime_t'],layer['u_t_delta'])
W_op_v_update += alpha * np.outer(layer['o_prime_t'],layer['v_t_delta'])
b_d_update += alpha * layer['d_t_delta']
b_u_update += alpha * layer['u_t_delta']
b_v_update += alpha * layer['v_t_delta']
W_op_o_update += alpha * np.outer(layer['o_prime_t'],layer['o_t_delta'])
b_o_update += alpha * layer['o_t_delta']
</pre>
<p>At this phase, we create our weight updates by multiplying the outer product of each layers weights by the deltas at the immediately following layer. We save these updates aside into our _update variables. Note that this doesn't change the weights. It just collects the updates. </p>
<pre class="brush: python">
if(it % batch_size == (batch_size-1)):
W_xh += W_xh_update/batch_size
W_xh_update *= 0
W_hh += W_hh_update/batch_size
W_hh_update *= 0
W_rh += W_rh_update/batch_size
W_rh_update *= 0
b_h += b_h_update/batch_size
b_h_update *= 0
W_hop += W_hop_update/batch_size
W_hop_update *= 0
b_op += b_op_update/batch_size
b_op_update *= 0
W_op_d += W_op_d_update/batch_size
W_op_d_update *= 0
W_op_u += W_op_u_update/batch_size
W_op_u_update *= 0
W_op_v += W_op_v_update/batch_size
W_op_v_update *= 0
b_d += b_d_update/batch_size
b_d_update *= 0
b_d += b_d * 0.00025 * batch_size
b_u += b_u_update/batch_size
b_u_update *= 0
b_v += b_v_update/batch_size
b_v_update *= 0
W_op_o += W_op_o_update/batch_size
W_op_o_update *= 0
b_o += b_o_update/batch_size
b_o_update *= 0
</pre>
<p>And if we are at the end of a mini-batch, then we update the weights using the average of all the updates we had accumulated so far. We then clear out each _update variable by multiplying it by 0.</p>
<h3>And We Have It!!!</h3>
<p>So, for all the code in one big file for you to run</p>
<pre class="brush: python">
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_out2deriv(out):
return out * (1 - out)
def tanh(x):
return np.tanh(x)
def tanh_out2deriv(out):
return (1 - out**2)
def relu(x,deriv=False):
if(deriv):
return int(x >= 0)
return max(0,x)
class NeuralStack():
def __init__(self,stack_width=2,o_prime_dim=6):
self.stack_width = stack_width
self.o_prime_dim = o_prime_dim
self.reset()
def reset(self):
# INIT STACK
self.V = list() # stack states
self.s = list() # stack strengths
self.d = list() # push strengths
self.u = list() # pop strengths
self.r = list()
self.o = list()
self.V_delta = list() # stack states
self.s_delta = list() # stack strengths
self.d_error = list() # push strengths
self.u_error = list() # pop strengths
self.t = 0
def pushAndPopForward(self,v_t,d_t,u_t):
self.d.append(d_t)
self.d_error.append(0)
self.u.append(u_t)
self.u_error.append(0)
new_s = np.zeros(self.t+1)
for i in xrange(self.t+1):
new_s[i] = self.s_t(i)
self.s.append(new_s)
self.s_delta.append(np.zeros_like(new_s))
if(len(self.V) == 0):
V_t = np.zeros((0,self.stack_width))
else:
V_t = self.V[-1]
self.V.append(np.concatenate((V_t,np.atleast_2d(v_t)),axis=0))
self.V_delta.append(np.zeros_like(self.V[-1]))
r_t = self.r_t()
self.r.append(r_t)
self.t += 1
return r_t
def s_t(self,i):
if(i >= 0 and i < self.t):
inner_sum = self.s[self.t-1][i+1:self.t-0]
return relu(self.s[self.t-1][i] - relu(self.u[self.t] - np.sum(inner_sum)))
elif(i == self.t):
return self.d[self.t]
else:
print "Problem"
def s_t_error(self,i,error):
if(i >= 0 and i < self.t):
if(self.s_t(i) >= 0):
self.s_delta[self.t-1][i] += error
if(relu(self.u[self.t] - np.sum(self.s[self.t-1][i+1:self.t-0])) >= 0):
self.u_error[self.t] -= error
self.s_delta[self.t-1][i+1:self.t-0] += error
elif(i == self.t):
self.d_error[self.t] += error
else:
print "Problem"
def r_t(self):
r_t_out = np.zeros(self.stack_width)
for i in xrange(0,self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
r_t_out += temp * self.V[self.t][i]
return r_t_out
def r_t_error(self,r_t_error):
for i in xrange(0, self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
self.V_delta[self.t][i] += temp * r_t_error
temp_error = np.sum(r_t_error * self.V[self.t][i])
if(self.s[self.t][i] < relu(1 - np.sum(self.s[self.t][i+1:self.t+1]))):
self.s_delta[self.t][i] += temp_error
else:
if(relu(1 - np.sum(self.s[self.t][i+1:self.t+1])) > 0):
self.s_delta[self.t][i+1:self.t+1] -= temp_error # minus equal becuase of the (1-).. and drop the 1
def backprop_single(self,r_t_error):
self.t -= 1
self.r_t_error(r_t_error)
for i in reversed(xrange(self.t+1)):
self.s_t_error(i,self.s_delta[self.t][i])
def backprop(self,all_errors_in_order_of_training_data):
errors = all_errors_in_order_of_training_data
for error in reversed(list((errors))):
self.backprop_single(error)
options = 2
sub_sequence_length = 5
sequence_length = sub_sequence_length*2
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+1
sequence[-1] = 0
sequence
X = np.zeros((sub_sequence_length*2,options+1))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
Y[-i][sequence[i]] = 1
sequence_length = len(X)
x_dim = X.shape[1]
h_dim = 16
o_prime_dim = 16
stack_width = options
y_dim = Y.shape[1]
sub_sequence_length = 2
W_xh = (np.random.rand(x_dim,h_dim)*0.2) - 0.1
W_xh_update = np.zeros_like(W_xh)
W_hh = (np.random.rand(h_dim,h_dim)*0.2) - 0.1
W_hh_update = np.zeros_like(W_hh)
W_rh = (np.random.rand(stack_width,h_dim)*0.2) - 0.1
W_rh_update = np.zeros_like(W_rh)
b_h = (np.random.rand(h_dim)*0.2) - 0.1
b_h_update = np.zeros_like(b_h)
W_hop = (np.random.rand(h_dim,o_prime_dim) * 0.2) - 0.1
W_hop_update = np.zeros_like(W_hop)
b_op = (np.random.rand(o_prime_dim)*0.2) - 0.1
b_op_update = np.zeros_like(b_op)
W_op_d = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_d_update = np.zeros_like(W_op_d)
W_op_u = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_u_update = np.zeros_like(W_op_u)
W_op_v = (np.random.rand(o_prime_dim,stack_width)*0.2) - 0.1
W_op_v_update = np.zeros_like(W_op_v)
W_op_o = (np.random.rand(o_prime_dim,y_dim)*0.2) - 0.1
W_op_o_update = np.zeros_like(W_op_o)
b_d = (np.random.rand(1)*0.2)+0.1
b_d_update = np.zeros_like(b_d)
b_u = (np.random.rand(1)*0.2)-0.1
b_u_update = np.zeros_like(b_u)
b_v = (np.random.rand(stack_width)*0.2)-0.1
b_v_update = np.zeros_like(b_v)
b_o = (np.random.rand(y_dim)*0.2)-0.1
b_o_update = np.zeros_like(b_o)
error = 0
max_len = 1
batch_size = 10
for it in xrange(1000000000):
sub_sequence_length = np.random.randint(max_len)+1
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+1
# sequence[-1] = 0
sequence
X = np.zeros((sub_sequence_length*2,options+1))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
X[i][0] = 1
Y[-i-1][sequence[i]] = 1
layers = list()
stack = NeuralStack(stack_width=stack_width,o_prime_dim=o_prime_dim)
for i in xrange(len(X)):
layer = {}
layer['x'] = X[i]
if(i == 0):
layer['h_t-1'] = np.zeros(h_dim)
layer['h_t-1'][0] = 1
layer['r_t-1'] = np.zeros(stack_width)
layer['r_t-1'][0] = 1
else:
layer['h_t-1'] = layers[i-1]['h_t']
layer['r_t-1'] = layers[i-1]['r_t']
layer['h_t'] = tanh(np.dot(layer['x'],W_xh) + np.dot(layer['h_t-1'],W_hh) + np.dot(layer['r_t-1'],W_rh) + b_h)
layer['o_prime_t'] = tanh(np.dot(layer['h_t'],W_hop)+b_op)
layer['o_t'] = tanh(np.dot(layer['o_prime_t'],W_op_o) + b_o)
if(i < len(X)-1):
layer['d_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_d) + b_d)
layer['u_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_u) + b_u)
layer['v_t'] = tanh(np.dot(layer['o_prime_t'],W_op_v) + b_v)
layer['r_t'] = stack.pushAndPopForward(layer['v_t'],layer['d_t'],layer['u_t'])
layers.append(layer)
for i in list(reversed(xrange(len(X)))):
layer = layers[i]
layer['o_t_error'] = Y[i] - layer['o_t']
error += np.sum(np.abs(layer['o_t_error']))
if(it % 100 == 99):
if(i == len(X)-1):
if(it % 10000 == 9999):
print "MaxLen:"+str(max_len)+ " Iter:" + str(it) + " Error:" + str(error) + "True:" + str(sequence) + " Pred:" + str(map(lambda x:np.argmax(x['o_t']),layers[sub_sequence_length:]))
if(error < (5*max_len)):
max_len+=1
error = 0
layer['o_t_delta'] = layer['o_t_error'] * tanh_out2deriv(layer['o_t'])
layer['o_prime_t_error'] = np.dot(layer['o_t_delta'],W_op_o.T)
if(i < len(X)-1):
layer['r_t_error'] = layers[i+1]['r_t-1_error']
stack.backprop_single(layer['r_t_error'])
layer['v_t_error'] = stack.V_delta[i][i]
layer['v_t_delta'] = layer['v_t_error'] * tanh_out2deriv(layer['v_t'])
layer['o_prime_t_error'] += np.dot(layer['v_t_delta'],W_op_v.T)
layer['u_t_error'] = stack.u_error[i]
layer['u_t_delta'] = layer['u_t_error'] * sigmoid_out2deriv(layer['u_t'])
layer['o_prime_t_error'] += np.dot(layer['u_t_delta'],W_op_u.T)
layer['d_t_error'] = stack.d_error[i]
layer['d_t_delta'] = layer['d_t_error'] * sigmoid_out2deriv(layer['d_t'])
layer['o_prime_t_error'] += np.dot(layer['d_t_delta'],W_op_d.T)
layer['o_prime_t_delta'] = layer['o_prime_t_error'] * tanh_out2deriv(layer['o_prime_t'])
layer['h_t_error'] = np.dot(layer['o_prime_t_delta'],W_hop.T)
if(i < len(X)-1):
layer['h_t_error'] += layers[i+1]['h_t-1_error']
layer['h_t_delta'] = layer['h_t_error'] * tanh_out2deriv(layer['h_t'])
layer['h_t-1_error'] = np.dot(layer['h_t_delta'],W_hh.T)
layer['r_t-1_error'] = np.dot(layer['h_t_delta'],W_rh.T)
for i in xrange(len(X)):
layer = layers[i]
max_alpha = 0.005 * batch_size
alpha = max_alpha / sub_sequence_length
W_xh_update += alpha * np.outer(layer['x'],layer['h_t_delta'])
W_hh_update += alpha * np.outer(layer['h_t-1'],layer['h_t_delta'])
W_rh_update += alpha * np.outer(layer['r_t-1'],layer['h_t_delta'])
b_h_update += alpha * layer['h_t_delta']
W_hop_update += alpha * np.outer(layer['h_t'],layer['o_prime_t_delta'])
b_op_update += alpha * layer['o_prime_t_delta']
if(i < len(X)-1):
W_op_d_update += alpha * np.outer(layer['o_prime_t'],layer['d_t_delta'])
W_op_u_update += alpha * np.outer(layer['o_prime_t'],layer['u_t_delta'])
W_op_v_update += alpha * np.outer(layer['o_prime_t'],layer['v_t_delta'])
b_d_update += alpha * layer['d_t_delta']
b_u_update += alpha * layer['u_t_delta']
b_v_update += alpha * layer['v_t_delta']
W_op_o_update += alpha * np.outer(layer['o_prime_t'],layer['o_t_delta'])
b_o_update += alpha * layer['o_t_delta']
if(it % batch_size == (batch_size-1)):
W_xh += W_xh_update/batch_size
W_xh_update *= 0
W_hh += W_hh_update/batch_size
W_hh_update *= 0
W_rh += W_rh_update/batch_size
W_rh_update *= 0
b_h += b_h_update/batch_size
b_h_update *= 0
W_hop += W_hop_update/batch_size
W_hop_update *= 0
b_op += b_op_update/batch_size
b_op_update *= 0
W_op_d += W_op_d_update/batch_size
W_op_d_update *= 0
W_op_u += W_op_u_update/batch_size
W_op_u_update *= 0
W_op_v += W_op_v_update/batch_size
W_op_v_update *= 0
b_d += b_d_update/batch_size
b_d_update *= 0
b_d += b_d * 0.00025 * batch_size
b_u += b_u_update/batch_size
b_u_update *= 0
b_v += b_v_update/batch_size
b_v_update *= 0
W_op_o += W_op_o_update/batch_size
W_op_o_update *= 0
b_o += b_o_update/batch_size
b_o_update *= 0
</pre>
<h3>Expected Output:</h3>
<p>If you run this code overnight on your CPU...you should see output that looks a lot like this. Note that the predictions are the reverse of the original sequence.</p>
<pre>
.......
.......
.......
.......
MaxLen:19 Iter:2789999 Error:168.444794145True:[2 2 1 1 2 1 2 1 1 2] Pred:[2, 1, 1, 2, 1, 2, 1, 1, 2, 2]
MaxLen:19 Iter:2799999 Error:207.262352698True:[1] Pred:[1]
MaxLen:19 Iter:2809999 Error:182.105266119True:[1 1 2 1 2 2 2 1 1 2 1] Pred:[1, 2, 1, 1, 2, 2, 2, 1, 2, 1, 1]
MaxLen:19 Iter:2819999 Error:184.174791858True:[2 1 2 2] Pred:[2, 2, 1, 2]
MaxLen:19 Iter:2829999 Error:206.158101496True:[2 1 2 2 2 1 1 2] Pred:[2, 1, 1, 2, 2, 2, 1, 2]
MaxLen:19 Iter:2839999 Error:209.114103766True:[1 2 1 2 2 2 1 1 1 1 2] Pred:[2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 1]
MaxLen:19 Iter:2849999 Error:167.128615254True:[2 1 2 1 1 2 1 2 1 2 1 1 2 2 2 1 2] Pred:[2, 1, 2, 2, 2, 1, 2, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2]
MaxLen:19 Iter:2859999 Error:200.380921774True:[2 2 2 1 1] Pred:[1, 1, 2, 2, 2]
MaxLen:19 Iter:2869999 Error:112.94541202True:[2 2 1 2 2 1 2 2 1 1 2 1 2] Pred:[2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 2]
MaxLen:19 Iter:2879999 Error:160.091183839True:[2 1 2 2 1 2] Pred:[2, 1, 2, 2, 1, 2]
MaxLen:19 Iter:2889999 Error:112.598129039True:[1 1 2] Pred:[2, 1, 1]
MaxLen:19 Iter:2899999 Error:186.041933391True:[2 2 2 1 1 2 1 2 2 1 1 2 2 1] Pred:[1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2]
MaxLen:19 Iter:2909999 Error:236.064449725True:[2 2 2 1 1 2 2 1 2 2 1 1 1 1 1 2 2] Pred:[2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1]
MaxLen:19 Iter:2919999 Error:152.776428031True:[1 1 2 1 1 1 1 2 2 1 1 1 2 2 1 2 2] Pred:[2, 2, 1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2]
MaxLen:19 Iter:2929999 Error:143.007796452True:[1 2 1 1] Pred:[1, 1, 2, 1]
MaxLen:19 Iter:2939999 Error:255.744221264True:[2 2 1 1 1 2 1] Pred:[1, 2, 1, 1, 1, 2, 2]
MaxLen:19 Iter:2949999 Error:183.147078344True:[1 2 1 1 2 2 1 1 1 1 2 1 1 1 2 1] Pred:[1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 1, 1, 2, 2]
MaxLen:19 Iter:2959999 Error:231.447857024True:[2 2 1 1] Pred:[1, 1, 2, 2]
</pre>
<h3>Something Went Wrong!!!</h3>
<p>At this point, I declared victory! I broke open a few brewskis and kicked back. Yay! Deepmind's Neural Stack before my very eyes! How bout it! Alas... I started taking things apart and realized that something was wrong... most notably these two things. Immediately after this log ending I printed out the following variables.</p>
<h4>stack.u</h4>
<pre>
[array([ 0.52627134]),
array([ 0.48875265]),
array([ 0.4833596]),
array([ 0.51072936]),
array([ 0.51525512]),
array([ 0.55418935]),
array([ 0.51561233]),
array([ 0.54271031]),
array([ 0.46972942]),
array([ 0.50030726]),
array([ 0.50420808]),
array([ 0.51277284]),
array([ 0.49249017]),
array([ 0.52770061]),
array([ 0.53647627]),
array([ 0.52879516]),
array([ 0.57190229]),
array([ 0.51895631]),
array([ 0.50232574]),
array([ 0.44804661]),
array([ 0.50789469]),
array([ 0.53620111]),
array([ 0.57897974]),
array([ 0.53155877])]
</pre>
<h4>satck.d</h4>
<pre>
[array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.]),
array([ 1.])]
</pre>
<p>Disaster... the neural network somehow learned how to model these sequences by pushing all of them onto the stack and then only popping off each number half at a time. What does this mean? Honestly, it could certainly be that I didn't train long enough. What do we do? Andrew... why are you sharing this with us? Was this 30 pages of blogging all for nothing?!?!</p>
<p>At this point, we have reached a very realistic point in a neural network researcher's lifecycle. Furthermore, it's one that the authors have discussed somewhat extensively both in the paper and in external presentations. If we're not careful, the network can discover less than expected ways of solving the problem that you give it. So, what do we do?</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 6: When Things Really Get Interesting</h2>
<p>I did end up getting the neural network to push and pop correctly. Here's the code. This blog is already like 80 pages long on my laptop so... Enjoy the puzzle!</p>
<p>Hint: Autoencoder</p>
<pre class="brush: python">
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_out2deriv(out):
return out * (1 - out)
def tanh(x):
return np.tanh(x)
def tanh_out2deriv(out):
return (1 - out**2)
def relu(x,deriv=False):
if(deriv):
return int(x >= 0)
return max(0,x)
class NeuralStack():
def __init__(self,stack_width=2,o_prime_dim=6):
self.stack_width = stack_width
self.o_prime_dim = o_prime_dim
self.reset()
def reset(self):
# INIT STACK
self.V = list() # stack states
self.s = list() # stack strengths
self.d = list() # push strengths
self.u = list() # pop strengths
self.r = list()
self.o = list()
self.V_delta = list() # stack states
self.s_delta = list() # stack strengths
self.d_error = list() # push strengths
self.u_error = list() # pop strengths
self.t = 0
def pushAndPopForward(self,v_t,d_t,u_t):
self.d.append(d_t)
self.d_error.append(0)
self.u.append(u_t)
self.u_error.append(0)
new_s = np.zeros(self.t+1)
for i in xrange(self.t+1):
new_s[i] = self.s_t(i)
self.s.append(new_s)
self.s_delta.append(np.zeros_like(new_s))
if(len(self.V) == 0):
V_t = np.zeros((0,self.stack_width))
else:
V_t = self.V[-1]
self.V.append(np.concatenate((V_t,np.atleast_2d(v_t)),axis=0))
self.V_delta.append(np.zeros_like(self.V[-1]))
r_t = self.r_t()
self.r.append(r_t)
self.t += 1
return r_t
def s_t(self,i):
if(i >= 0 and i < self.t):
inner_sum = self.s[self.t-1][i+1:self.t-0]
return relu(self.s[self.t-1][i] - relu(self.u[self.t] - np.sum(inner_sum)))
elif(i == self.t):
return self.d[self.t]
else:
print "Problem"
def s_t_error(self,i,error):
if(i >= 0 and i < self.t):
if(self.s_t(i) >= 0):
self.s_delta[self.t-1][i] += error
if(relu(self.u[self.t] - np.sum(self.s[self.t-1][i+1:self.t-0])) >= 0):
self.u_error[self.t] -= error
self.s_delta[self.t-1][i+1:self.t-0] += error
elif(i == self.t):
self.d_error[self.t] += error
else:
print "Problem"
def r_t(self):
r_t_out = np.zeros(self.stack_width)
for i in xrange(0,self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
r_t_out += temp * self.V[self.t][i]
return r_t_out
def r_t_error(self,r_t_error):
for i in xrange(0, self.t+1):
temp = min(self.s[self.t][i],relu(1 - np.sum(self.s[self.t][i+1:self.t+1])))
self.V_delta[self.t][i] += temp * r_t_error
temp_error = np.sum(r_t_error * self.V[self.t][i])
if(self.s[self.t][i] < relu(1 - np.sum(self.s[self.t][i+1:self.t+1]))):
self.s_delta[self.t][i] += temp_error
else:
if(relu(1 - np.sum(self.s[self.t][i+1:self.t+1])) > 0):
self.s_delta[self.t][i+1:self.t+1] -= temp_error # minus equal becuase of the (1-).. and drop the 1
def backprop_single(self,r_t_error):
self.t -= 1
self.r_t_error(r_t_error)
for i in reversed(xrange(self.t+1)):
self.s_t_error(i,self.s_delta[self.t][i])
def backprop(self,all_errors_in_order_of_training_data):
errors = all_errors_in_order_of_training_data
for error in reversed(list((errors))):
self.backprop_single(error)
options = 2
sub_sequence_length = 5
sequence_length = sub_sequence_length*2
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+2
sequence
X = np.zeros((sub_sequence_length*2,options+2))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
X[-i-1][0] = 1
X[i][1] = 1
Y[-i-1][sequence[i]] = 1
sequence_length = len(X)
x_dim = X.shape[1]
h_dim = 8
o_prime_dim = 8
stack_width = 2
y_dim = Y.shape[1]
np.random.seed(1)
sub_sequence_length = 2
W_xh = (np.random.rand(x_dim,h_dim)*0.2) - 0.1
W_xh_update = np.zeros_like(W_xh)
W_hox = (np.random.rand(h_dim,x_dim)*0.2) - 0.1
W_hox_update = np.zeros_like(W_hox)
W_opx = (np.random.rand(o_prime_dim,x_dim)*0.2) - 0.1
W_opx_update = np.zeros_like(W_opx)
W_hh = (np.random.rand(h_dim,h_dim)*0.2) - 0.1
W_hh_update = np.zeros_like(W_hh)
W_rh = (np.random.rand(stack_width,h_dim)*0.2) - 0.1
W_rh_update = np.zeros_like(W_rh)
b_h = (np.random.rand(h_dim)*0.2) - 0.1
b_h_update = np.zeros_like(b_h)
W_hop = (np.random.rand(h_dim,o_prime_dim) * 0.2) - 0.1
W_hop_update = np.zeros_like(W_hop)
b_op = (np.random.rand(o_prime_dim)*0.2) - 0.1
b_op_update = np.zeros_like(b_op)
W_op_d = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_d_update = np.zeros_like(W_op_d)
W_op_u = (np.random.rand(o_prime_dim,1)*0.2) - 0.1
W_op_u_update = np.zeros_like(W_op_u)
W_op_v = (np.random.rand(o_prime_dim,stack_width)*0.2) - 0.1
W_op_v_update = np.zeros_like(W_op_v)
W_op_o = (np.random.rand(o_prime_dim,y_dim)*0.2) - 0.1
W_op_o_update = np.zeros_like(W_op_o)
b_d = (np.random.rand(1)*0.2)+1
b_d_update = np.zeros_like(b_d)
b_u = (np.random.rand(1)*0.2)-1
b_u_update = np.zeros_like(b_u)
b_v = (np.random.rand(stack_width)*0.2)-0.1
b_v_update = np.zeros_like(b_v)
b_o = (np.random.rand(y_dim)*0.2)-0.1
b_o_update = np.zeros_like(b_o)
error = 0
reconstruct_error = 0
reconstruct_error_2 = 0
max_len = 3
batch_size = 50
for it in xrange(750000):
# if(it % 100 == 0):
sub_sequence_length = np.random.randint(max_len)+3
sequence = (np.random.random(sub_sequence_length)*options).astype(int)+2
sequence
X = np.zeros((sub_sequence_length*2,options+2))
Y = np.zeros_like(X)
for i in xrange(len(sequence)):
X[i][sequence[i]] = 1
X[-i-1][0] = 1
X[i][1] = 1
Y[-i-1][sequence[i]] = 1
layers = list()
stack = NeuralStack(stack_width=stack_width,o_prime_dim=o_prime_dim)
for i in xrange(len(X)):
layer = {}
layer['x'] = X[i]
if(i == 0):
layer['h_t-1'] = np.zeros(h_dim)
# layer['h_t-1'][0] = 1
layer['r_t-1'] = np.zeros(stack_width)
# layer['r_t-1'][0] = 1
else:
layer['h_t-1'] = layers[i-1]['h_t']
layer['r_t-1'] = layers[i-1]['r_t']
layer['h_t'] = tanh(np.dot(layer['x'],W_xh) + np.dot(layer['h_t-1'],W_hh) + np.dot(layer['r_t-1'],W_rh) + b_h)
layer['xo_t'] = sigmoid(np.dot(layer['h_t'],W_hox))
layer['o_prime_t'] = tanh(np.dot(layer['h_t'],W_hop)+b_op)
layer['o_prime_x_t'] = sigmoid(np.dot(layer['o_prime_t'],W_opx))
layer['o_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_o) + b_o)
if(i < len(X)-1):
layer['d_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_d) + b_d)
layer['u_t'] = sigmoid(np.dot(layer['o_prime_t'],W_op_u) + b_u)
layer['v_t'] = tanh(np.dot(layer['o_prime_t'],W_op_v) + b_v)
layer['r_t'] = stack.pushAndPopForward(layer['v_t'],layer['d_t'],layer['u_t'])
layers.append(layer)
for i in list(reversed(xrange(len(X)))):
layer = layers[i]
layer['o_t_error'] = (Y[i] - layer['o_t'])
if(i>0):
layer['xo_t_error'] = layers[i-1]['x'] - layer['xo_t']
layer['xo_t_delta'] = layer['xo_t_error'] * sigmoid_out2deriv(layer['xo_t'])
layer['x_o_prime_x_t_error'] = (layers[i-1]['x'] - layer['o_prime_x_t'])
layer['x_o_prime_x_t_delta'] = layer['x_o_prime_x_t_error'] * sigmoid_out2deriv(layer['o_prime_x_t'])
else:
layer['xo_t_delta'] = np.zeros_like(layer['x'])
layer['x_o_prime_x_t_delta'] = np.zeros_like(layer['x'])
# if(it > 2000):
layer['xo_t_delta'] *= 1
layer['x_o_prime_x_t_delta'] *= 1
error += np.sum(np.abs(layer['o_t_error']))
if(i > 0):
reconstruct_error += np.sum(np.abs(layer['xo_t_error']))
reconstruct_error_2 += np.sum(np.abs(layer['x_o_prime_x_t_error']))
if(it % 100 == 99):
if(i == len(X)-1):
if(it % 1000 == 999):
print "MaxLen:"+str(max_len)+ " Iter:" + str(it) + " Error:" + str(error)+ " RecError:" + str(reconstruct_error) + " RecError2:"+ str(reconstruct_error_2) + " True:" + str(sequence) + " Pred:" + str(map(lambda x:np.argmax(x['o_t']),layers[sub_sequence_length:]))
if(it % 10000 == 9999):
print "U:" + str(np.array(stack.u).T[0])
print "D:" + str(np.array(stack.d).T[0])
# print "o_t:"
# for l in layers[sub_sequence_length:]:
# print l['o_t']
# print "V_t:"
# for row in stack.V[-1]:
# print row
if(error < max_len+4 and it > 10000):
max_len += 1
it = 0
error = 0
reconstruct_error = 0
reconstruct_error_2 = 0
layer['o_t_delta'] = layer['o_t_error'] * sigmoid_out2deriv(layer['o_t'])
layer['o_prime_t_error'] = np.dot(layer['o_t_delta'],W_op_o.T)
layer['o_prime_t_error'] += np.dot(layer['x_o_prime_x_t_delta'],W_opx.T)
if(i < len(X)-1):
layer['r_t_error'] = layers[i+1]['r_t-1_error']
stack.backprop_single(layer['r_t_error'])
layer['v_t_error'] = stack.V_delta[i][i]
layer['v_t_delta'] = layer['v_t_error'] * tanh_out2deriv(layer['v_t'])
layer['o_prime_t_error'] += np.dot(layer['v_t_delta'],W_op_v.T)
layer['u_t_error'] = stack.u_error[i]
layer['u_t_delta'] = layer['u_t_error'] * sigmoid_out2deriv(layer['u_t'])
layer['o_prime_t_error'] += np.dot(layer['u_t_delta'],W_op_u.T)
layer['d_t_error'] = stack.d_error[i]
layer['d_t_delta'] = layer['d_t_error'] * sigmoid_out2deriv(layer['d_t'])
layer['o_prime_t_error'] += np.dot(layer['d_t_delta'],W_op_d.T)
layer['o_prime_t_delta'] = layer['o_prime_t_error'] * tanh_out2deriv(layer['o_prime_t'])
layer['h_t_error'] = np.dot(layer['o_prime_t_delta'],W_hop.T)
layer['h_t_error'] += np.dot(layer['xo_t_delta'],W_hox.T)
if(i < len(X)-1):
layer['h_t_error'] += layers[i+1]['h_t-1_error']
layer['h_t_delta'] = layer['h_t_error'] * tanh_out2deriv(layer['h_t'])
layer['h_t-1_error'] = np.dot(layer['h_t_delta'],W_hh.T)
layer['r_t-1_error'] = np.dot(layer['h_t_delta'],W_rh.T)
for i in xrange(len(X)):
layer = layers[i]
if(it<2000):
max_alpha = 0.05 * batch_size
# else:
# max_alpha = 0.05 * batch_size
alpha = max_alpha / sub_sequence_length
W_xh_update += alpha * np.outer(layer['x'],layer['h_t_delta'])
W_hh_update += alpha * np.outer(layer['h_t-1'],layer['h_t_delta'])
W_rh_update += alpha * np.outer(layer['r_t-1'],layer['h_t_delta'])
W_hox_update += alpha * np.outer(layer['h_t'],layer['xo_t_delta'])
b_h_update += alpha * layer['h_t_delta']
W_hop_update += alpha * np.outer(layer['h_t'],layer['o_prime_t_delta'])
b_op_update += alpha * layer['o_prime_t_delta']
W_opx_update += alpha * np.outer(layer['o_prime_t'],layer['x_o_prime_x_t_delta'])
if(i < len(X)-1):
W_op_d_update += alpha * np.outer(layer['o_prime_t'],layer['d_t_delta'])
W_op_u_update += alpha * np.outer(layer['o_prime_t'],layer['u_t_delta'])
W_op_v_update += alpha * np.outer(layer['o_prime_t'],layer['v_t_delta'])
b_d_update += alpha * layer['d_t_delta']# * 10
b_u_update += alpha * layer['u_t_delta']# * 10
b_v_update += alpha * layer['v_t_delta']
W_op_o_update += alpha * np.outer(layer['o_prime_t'],layer['o_t_delta'])
b_o_update += alpha * layer['o_t_delta']
if(it % batch_size == (batch_size-1)):
W_xh += W_xh_update/batch_size
W_xh_update *= 0
W_hh += W_hh_update/batch_size
W_hh_update *= 0
W_rh += W_rh_update/batch_size
W_rh_update *= 0
b_h += b_h_update/batch_size
b_h_update *= 0
W_hop += W_hop_update/batch_size
W_hop_update *= 0
b_op += b_op_update/batch_size
b_op_update *= 0
W_op_d += W_op_d_update/batch_size
W_op_d_update *= 0
W_op_u += W_op_u_update/batch_size
W_op_u_update *= 0
W_op_v += W_op_v_update/batch_size
W_op_v_update *= 0
W_opx += W_opx_update/batch_size
W_opx_update *= 0
W_hox += W_hox_update/batch_size
W_hox_update *= 0
b_d += b_d_update/batch_size
b_d_update *= 0
b_u += b_u_update/batch_size
b_u_update *= 0
b_v += b_v_update/batch_size
b_v_update *= 0
W_op_o += W_op_o_update/batch_size
W_op_o_update *= 0
b_o += b_o_update/batch_size
b_o_update *= 0
</pre>
<h3>Training Time Output</h3>
<pre>
....
....
....
....
MaxLen:3 Iter:745999 Error:7.56448795544 RecError:7.10891969494 RecError2:5.73615942287 True:[3 3 2 2 3] Pred:[3, 2, 2, 3, 3]
MaxLen:3 Iter:746999 Error:7.40633215737 RecError:6.69030096695 RecError2:6.19218015399 True:[3 2 3 2] Pred:[2, 3, 2, 3]
MaxLen:3 Iter:747999 Error:7.6670587332 RecError:7.00484905169 RecError2:5.98610855847 True:[2 2 2 2 2] Pred:[2, 2, 2, 2, 2]
MaxLen:3 Iter:748999 Error:7.58710695632 RecError:7.25143585612 RecError2:6.02631960485 True:[2 3 2] Pred:[2, 3, 2]
MaxLen:3 Iter:749999 Error:7.36136812467 RecError:7.05922903111 RecError2:5.87101840726 True:[3 3 2 3 2] Pred:[2, 3, 2, 3, 3]
U:[ 1.42111936e-03 4.24234116e-05 4.38773521e-05 1.90306228e-03
4.46779468e-05 1.61383041e-03 9.99610386e-01 9.76241526e-01
9.99635875e-01]
D:[ 9.96007159e-01 9.98850792e-01 9.98678243e-01 9.93183510e-01
9.98787118e-01 2.95677776e-02 4.76367458e-04 4.53054877e-04
5.11268758e-04]
</pre>
<h3> Known Deviations / Ambiguities From the Paper (and Reasons)</h3>
<p><b>1: </b>The Controller is an RNN instead of an LSTM. I haven't finished the blogpost on LSTMs yet, and I wanted to only used previous blogposts as pre-requisite information.</p>
<p><b>2: </b>Instead of padding using a single buffer token to signify when to repeat the sequence back, I turned the single buffer on turing all of encoding and off for all of decoding. This is related to not having an LSTM to save the binary state. RNNs lose this kind of information and I wanted the network to converge quickly when training on the CPUs of this blog's readership.</p>
<p><b>3: </b>I didn't see specifics on which nonlinearities were used in the RNN or how all the various weights were initialized. I chose to use best practices</p>
<p><b>4: </b>I trained this with a minibatch size of 50 instead of 10.</p>
<p><b>5: </b>The hidden layers are considerably smaller. This also falls in the category of "getting it to converge faster for readers". However, small hidden layers also force the network to use the stack, which seems like a good reason to use them.</p>
<p><b>6: </b>Not sure how many epochs this was trained on originally.
<p><b>7: </b>And of course... this was written in python using just a matrix library as opposed to Torch's deep learning framework. There are likely small things done as a best practice implicit into Torch's framework that might not be represented here.</p>
<p><b>8: </b>I haven't attempted Queues or DeQueues yet... but in theory it's just a matter of swapping out the Neural Stack... that'd be a great project for a reader if you want to take this to the next level!</p>
<p><b>9: </b>My timeframe for writing this blogpost was quite short. The post itself was written in < 24 hours. I'd like to do further experimentation with LSTMs and more benchmarking relative to the posted results in the paper. This, however, is primarily a teaching tool.</p>
<p><b>10: </b>I haven't actually checked the backpropagation against the formulas in Appendix A of the paper. Again.. time constraint and I thought it would be more fun to try to figure them out independently.</p>
<p><b>11: </b>I wasn't sure if o_prime_t was really generated as a PART of the recurrent hidden layer or if it was supposed to be one layer deeper (with a matrix between the recurrent hidden layer and o_prime). I assumed the latter but the former could be possible. If you happen to be an author on the paper and you're reading this far, I'd love to know.</p>
<p>If you have questions or comments, tweet <a href="https://twitter.com/iamtrask"><b>@iamtrask</b></a> and I'll be happy to help.</p>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p>
Thu, 25 Feb 2016 12:00:00 +0000
https://iamtrask.github.io/2016/02/25/deepminds-neural-stack-machine/
https://iamtrask.github.io/2016/02/25/deepminds-neural-stack-machine/Anyone Can Learn To Code an LSTM-RNN in Python (Part 1: RNN)<p><b>Summary:</b> I learn best with toy code that I can play with. This tutorial teaches Recurrent Neural Networks via a very simple toy example, a short python implementation.</p>
<p>I'll tweet out <b>(Part 2: LSTM)</b> when it's complete at <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading it and thanks for all the feedback!
</p>
<h3>Just Give Me The Code:</h3>
<pre class="brush: python">
import copy, numpy as np
np.random.seed(0)
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
# training dataset generation
int2binary = {}
binary_dim = 8
largest_number = pow(2,binary_dim)
binary = np.unpackbits(
np.array([range(largest_number)],dtype=np.uint8).T,axis=1)
for i in range(largest_number):
int2binary[i] = binary[i]
# input variables
alpha = 0.1
input_dim = 2
hidden_dim = 16
output_dim = 1
# initialize neural network weights
synapse_0 = 2*np.random.random((input_dim,hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,output_dim)) - 1
synapse_h = 2*np.random.random((hidden_dim,hidden_dim)) - 1
synapse_0_update = np.zeros_like(synapse_0)
synapse_1_update = np.zeros_like(synapse_1)
synapse_h_update = np.zeros_like(synapse_h)
# training logic
for j in range(10000):
# generate a simple addition problem (a + b = c)
a_int = np.random.randint(largest_number/2) # int version
a = int2binary[a_int] # binary encoding
b_int = np.random.randint(largest_number/2) # int version
b = int2binary[b_int] # binary encoding
# true answer
c_int = a_int + b_int
c = int2binary[c_int]
# where we'll store our best guess (binary encoded)
d = np.zeros_like(c)
overallError = 0
layer_2_deltas = list()
layer_1_values = list()
layer_1_values.append(np.zeros(hidden_dim))
# moving along the positions in the binary encoding
for position in range(binary_dim):
# generate input and output
X = np.array([[a[binary_dim - position - 1],b[binary_dim - position - 1]]])
y = np.array([[c[binary_dim - position - 1]]]).T
# hidden layer (input ~+ prev_hidden)
layer_1 = sigmoid(np.dot(X,synapse_0) + np.dot(layer_1_values[-1],synapse_h))
# output layer (new binary representation)
layer_2 = sigmoid(np.dot(layer_1,synapse_1))
# did we miss?... if so, by how much?
layer_2_error = y - layer_2
layer_2_deltas.append((layer_2_error)*sigmoid_output_to_derivative(layer_2))
overallError += np.abs(layer_2_error[0])
# decode estimate so we can print it out
d[binary_dim - position - 1] = np.round(layer_2[0][0])
# store hidden layer so we can use it in the next timestep
layer_1_values.append(copy.deepcopy(layer_1))
future_layer_1_delta = np.zeros(hidden_dim)
for position in range(binary_dim):
X = np.array([[a[position],b[position]]])
layer_1 = layer_1_values[-position-1]
prev_layer_1 = layer_1_values[-position-2]
# error at output layer
layer_2_delta = layer_2_deltas[-position-1]
# error at hidden layer
layer_1_delta = (future_layer_1_delta.dot(synapse_h.T) + layer_2_delta.dot(synapse_1.T)) * sigmoid_output_to_derivative(layer_1)
# let's update all our weights so we can try again
synapse_1_update += np.atleast_2d(layer_1).T.dot(layer_2_delta)
synapse_h_update += np.atleast_2d(prev_layer_1).T.dot(layer_1_delta)
synapse_0_update += X.T.dot(layer_1_delta)
future_layer_1_delta = layer_1_delta
synapse_0 += synapse_0_update * alpha
synapse_1 += synapse_1_update * alpha
synapse_h += synapse_h_update * alpha
synapse_0_update *= 0
synapse_1_update *= 0
synapse_h_update *= 0
# print out progress
if(j % 1000 == 0):
print "Error:" + str(overallError)
print "Pred:" + str(d)
print "True:" + str(c)
out = 0
for index,x in enumerate(reversed(d)):
out += x*pow(2,index)
print str(a_int) + " + " + str(b_int) + " = " + str(out)
print "------------"
</pre>
<h3>Runtime Output:</h3>
<pre>
Error:[ 3.45638663]
Pred:[0 0 0 0 0 0 0 1]
True:[0 1 0 0 0 1 0 1]
9 + 60 = 1
------------
Error:[ 3.63389116]
Pred:[1 1 1 1 1 1 1 1]
True:[0 0 1 1 1 1 1 1]
28 + 35 = 255
------------
Error:[ 3.91366595]
Pred:[0 1 0 0 1 0 0 0]
True:[1 0 1 0 0 0 0 0]
116 + 44 = 72
------------
Error:[ 3.72191702]
Pred:[1 1 0 1 1 1 1 1]
True:[0 1 0 0 1 1 0 1]
4 + 73 = 223
------------
Error:[ 3.5852713]
Pred:[0 0 0 0 1 0 0 0]
True:[0 1 0 1 0 0 1 0]
71 + 11 = 8
------------
Error:[ 2.53352328]
Pred:[1 0 1 0 0 0 1 0]
True:[1 1 0 0 0 0 1 0]
81 + 113 = 162
------------
Error:[ 0.57691441]
Pred:[0 1 0 1 0 0 0 1]
True:[0 1 0 1 0 0 0 1]
81 + 0 = 81
------------
Error:[ 1.42589952]
Pred:[1 0 0 0 0 0 0 1]
True:[1 0 0 0 0 0 0 1]
4 + 125 = 129
------------
Error:[ 0.47477457]
Pred:[0 0 1 1 1 0 0 0]
True:[0 0 1 1 1 0 0 0]
39 + 17 = 56
------------
Error:[ 0.21595037]
Pred:[0 0 0 0 1 1 1 0]
True:[0 0 0 0 1 1 1 0]
11 + 3 = 14
------------
</pre>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 1: What is Neural Memory?</h2>
<p>List the alphabet forward.... you can do it, yes?</p>
<p>List the alphabet backward.... hmmm... perhaps a bit tougher.</p>
<p>Try with the lyrics of a song you know?.... Why is it easier to recall forward than it is to recall backward? Can you jump into the middle of the second verse?... hmm... also difficult. Why?</p>
<p>There's a very logical reason for this....you haven't learned the letters of the alphabet or the lyrics of a song like a computer storing them as a set on a hard drive. You learned them as a <b>sequence</b>. You are really good at indexing from one letter to the next. It's a kind of conditional memory... you only have it when you very recently had the previous memory. It's also a lot like a <b>linked list</b> if you're familiar with that.</p>
<p>However, it's not that you <i>don't</i> have the song in your memory except when you're singing it. Instead, when you try to jump straight to the middle of the song, you simply have a hard time finding that representation in your brain (perhaps that set of neurons). It starts searching all over looking for the middle of the song, but it hasn't tried to look for it this way before, so it doesn't have a map to the location of the middle of the second verse. It's a lot like living in a neighborhood with lots of coves/cul-de-sacs. It's much easier to picture how to get to someone's house by following all the windy roads because you've done it many times, but knowing exactly where to cut straight across someone's backyard is really difficult. Your brain instead uses the "directions" that it knows... through the neurons at the beginning of a song. (for more on brain stuff, click <a href="http://www.human-memory.net/processes_recall.html" target="_blank">here</a>)</p>
<p>Much like a linked list, storing memory like this is very efficient. We will find that similar properties/advantages exist in giving our neural networks this type of memory as well. Some processes/problems/representations/searches are far more efficient if modeled as a sequence with a short term / pseudo conditional memory.</p>
<p>Memory matters when your data is a <b>sequence</b> of some kind. (It means you have something to remember!) Imagine having a video of a bouncing ball. (here... i'll help this time)<br /><br />
<center><iframe width="700" height="525" src="https://www.youtube.com/embed/UL0ZOgN2SqY?loop=1&autoplay=0" frameborder="0" allowfullscreen=""></iframe><br /><br /></center><br />
Each data point is a frame of your video. If you wanted to train a neural network to predict where the ball would be in the next frame, it would be really helpful to know where the ball was in the last frame! Sequential data like this is why we build recurrent neural networks. So, how does a neural network remember what it saw in previous time steps?</p>
<p>Neural networks have hidden layers. Normally, the state of your hidden layer is <b>based ONLY on your input data</b>. So, normally a neural network's information flow would look like this:<br />
<center><b>input -> hidden -> output</b></center>
<br />
<p>This is straightforward. Certain types of input create certain types of hidden layers. Certain types of hidden layers create certain types of output layers. It's kindof a closed system. Memory changes this. Memory means that the hidden layer is a combination of your input data at the current timestep <b>and the hidden layer of the previous timestep</b>.</p>
<center><b>(input + prev_hidden) -> hidden -> output</b></center>
<p>
Why the hidden layer? Well, we could technically do this.
</p>
<center><b>(input + prev_input) -> hidden -> output</b></center>
<p>However, we'd be missing out. I encourage you to sit and consider the difference between these two information flows. For a little helpful hint, consider how this plays out. Here, we have 4 timesteps of a recurrent neural network pulling information from the previous hidden layer.</p>
<center><b>(input + empty_hidden) -> hidden -> output</b></center>
<center><b>(input + prev_hidden) -> hidden -> output</b></center>
<center><b>(input + prev_hidden) -> hidden -> output</b></center>
<center><b>(input + prev_hidden) -> hidden -> output</b></center>
<p>And here, we have 4 timesteps of a recurrent neural network pulling information from the previous input layer</p>
<center><b>(input + empty_input) -> hidden -> output</b></center>
<center><b>(input + prev_input) -> hidden -> output</b></center>
<center><b>(input + prev_input) -> hidden -> output</b></center>
<center><b>(input + prev_input) -> hidden -> output</b></center>
<p>Maybe, if I colored things a bit, it would become more clear. Again, 4 timesteps with <b>hidden layer recurrence</b>:</p>
<center><b>(<font color="blue">input</font> + empty_hidden) -> <font color="blue">hidden</font> -> output</b></center>
<center><b>(<font color="red">input</font> + prev_<font color="blue">hidden</font>) -> <font color="red">hid</font><font color="blue">den</font> -> output</b></center>
<center><b>(<font color="green">input</font> + prev_<font color="red">hid</font><font color="blue">den</font>) -> <font color="green">hi</font><font color="red">dd</font><font color="blue">en</font> -> output</b></center>
<center><b>(<font color="purple">input</font> + prev_<font color="green">hi</font><font color="red">dd</font><font color="blue">en</font> ) -> <font color="purple">hi</font><font color="red">d</font><font color="green">de</font><font color="blue">n</font> -> output</b></center>
<p>.... and 4 timesteps with <b>input layer recurrence</b>....</p>
<center><b>(<font color="blue">input</font> + empty_input) -> <font color="blue">hidden</font> -> output</b></center>
<center><b>(<font color="red">input</font> + prev_<font color="blue">input</font>) -> <font color="red">hid</font><font color="blue">den</font> -> output</b></center>
<center><b>(<font color="green">input</font> + prev_<font color="red">input</font>) -> <font color="green">hid</font><font color="red">den</font> -> output</b></center>
<center><b>(<font color="purple">input</font> + prev_<font color="green">input</font>) -> <font color="purple">hid</font><font color="green">den</font> -> output</b></center>
<p>Focus on the last hidden layer (4th line). In the hidden layer recurrence, we see a presence of every input seen so far. In the input layer recurrence, it's exclusively defined by the current and previous inputs. This is why we model hidden recurrence. Hidden recurrence <b>learns what to remember</b> whereas input recurrence is hard wired to just remember the immediately previous datapoint. </p>
<p>Now compare and contrast these two approaches with the backwards alphabet and middle-of-song exercises. The hidden layer is constantly changing as it gets more inputs. Furthermore, the only way that we could reach these hidden states is with the correct <b>sequence</b> of inputs. Now the money statement, the output is deterministic given the hidden layer, and the hidden layer is only reachable with the right <b>sequence</b> of inputs. Sound familiar?</p>
<p>What's the practical difference? Let's say we were trying to predict the next word in a song given the previous. The "input layer recurrence" would break down if the song accidentally had the same sequence of two words in multiple places. Think about it, if the song had the statements "I love you", and "I love carrots", and the network was trying to predict the next word, how would it know what follows "I love"? It could be carrots. It could be you. The network REALLY needs to know more about what part of the song its in. However, the "hidden layer recurrence" doesn't break down in this way. It subtely remembers everything it saw (with memories becoming more subtle as it they fade into the past). To see this in action, check out <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" target="_blank"> this</a>.
<center><b>stop and make sure this feels comfortable in your mind</b></center><br />
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 2 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="3842123822"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 2: RNN - Neural Network Memory</h2>
<p>Now that we have the intuition, let's dive down a layer (ba dum bump...). As described in the <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/"><u>backpropagation post</u></a>, our input layer to the neural network is determined by our input dataset. Each row of input data is used to generate the hidden layer (via forward propagation). Each hidden layer is then used to populate the output layer (assuming only 1 hidden layer). As we just saw, memory means that the hidden layer is a combination of the input data and the previous hidden layer. How is this done? Well, much like every other propagation in neural networks, it's done with a matrix. This matrix defines the relationship between the previous hidden layer and the current one.</p>
<img class="img-responsive" width="100%" src="/img/basic_recurrence_singleton.png" alt="" />
<p>Big thing to take from this picture, there are only three weight matrices. Two of them should be very familiar (same names too). SYNAPSE_0 propagates the input data to the hidden layer. SYNAPSE_1 propagates the hidden layer to the output data. The new matrix (SYNAPSE_h....the recurrent one), propagates from the hidden layer (layer_1) to the hidden layer at the next timestep (still layer_1).
<center><b>stop and make sure this feels comfortable in your mind</b></center><br />
<img class="img-responsive" width="95%" src="/img/recurrence_gif.gif" alt="" />
<p>The gif above reflects the magic of recurrent networks, and several very, very important properties. It depicts 4 timesteps. The first is exclusively influenced by the input data. The second one is a mixture of the first and second inputs. This continues on. You should recognize that, in some way, network 4 is "full". Presumably, timestep 5 would have to choose which memories to keep and which ones to overwrite. This is very real. It's the notion of memory "capacity". As you might expect, bigger layers can hold more memories for a longer period of time. Also, this is when the network learns to <b>forget irrelevant memories</b> and <b>remember important memories</b>. What significant thing do you notice in timestep 3? Why is there more <font color="green">green</font> in the hidden layer than the other colors?</p>
<p>Also notice that the hidden layer is the barrier between the input and the output. In reality, the output is no longer a pure function of the input. The input is just changing what's in the memory, and the output is exclusively based on the memory. Another interesting takeaway. If there was no input at timesteps 2,3,and 4, the hidden layer would still change from timestep to timestep.</p>
<center><b>i know i've been stopping... but really make sure you got that last bit</b></center><br />
<h2 class="section-heading">Part 3: Backpropagation Through Time:</h2>
<p>So, how do recurrent neural networks learn? Check out this graphic. Black is the prediction, errors are bright yellow, derivatives are mustard colored.</p>
<img class="img-responsive" width="95%" src="/img/backprop_through_time.gif" alt="" />
<p>They learn by fully propagating forward from 1 to 4 (through an entire sequence of arbitrary length), and then backpropagating all the derivatives from 4 back to 1. You can also pretend that it's just a funny shaped normal neural network, except that we're re-using the same weights (synapses 0,1,and h) in their respective places. Other than that, it's normal backpropagation.
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 3 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="5318857026"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 4: Our Toy Code</h2>
<p>We're going to be using a recurrent neural network to model <b>binary addition</b>. Do you see the sequence below? What do the colored ones in squares at the top signify?</p>
<img class="img-responsive" width="95%" src="/img/binary_addition.GIF" alt="" />
<font size="2" color="gray">source: angelfire.com</font>
<p>The colorful 1s in boxes at the top signify the "carry bit". They "carry the one" when the sum overfows at each place. This is the tiny bit of memory that we're going to teach our neural network how to model. It's going to "carry the one" when the sum requires it. (click <a href="https://www.youtube.com/watch?v=jB_sRh5yoZk">here</a> to learn about when this happens)</p>
<p>So, binary addition moves from right to left, where we try to predict the number beneath the line given the numbers above the line. We want the neural network to move along the binary sequences and remember when it has carried the 1 and when it hasn't, so that it can make the correct prediction. Don't get too caught up in the problem. The network actually doesn't care too much. Just recognize that we're going to have two inputs at each time step, (either a one or a zero from each number begin added). These two inputs will be propagated to the hidden layer, which will have to remember whether or not we carry. The prediction will take all of this information into account to predict the correct bit at the given position (time step).</p>
<center><i>At this point, I recommend opening this page in two windows so that you can follow along with the line numbers in the code example at the top. That's how I wrote it.</i></center>
<p><b>Lines 0-2:</b> Importing our dependencies and seeding the random number generator. We will only use numpy and copy. Numpy is for matrix algebra. Copy is to copy things.</p>
<p><b>Lines 4-11:</b> Our nonlinearity and derivative. For details, please read this <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/"> Neural Network Tutorial</a></p>
<p><b>Line 15:</b> We're going to create a lookup table that maps from an integer to its binary representation. The binary representations will be our input and output data for each math problem we try to get the network to solve. This lookup table will be very helpful in converting from integers to bit strings.</p>
<p><b>Line 16:</b> This is where I set the maximum length of the binary numbers we'll be adding. If I've done everything right, you can adjust this to add potentially very large numbers.</p>
<p><b>Line 18:</b> This computes the largest number that is possible to represent with the binary length we chose</p>
<p><b>Line 19:</b> This is a lookup table that maps from an integer to its binary representation. We copy it into the int2binary. This is kindof un-ncessary but I thought it made things more obvious looking.</p>
<p><b>Line 26:</b> This is our learning rate.</p>
<p><b>Line 27:</b> We are adding two numbers together, so we'll be feeding in two-bit strings one character at the time each. Thus, we need to have two inputs to the network (one for each of the numbers being added).</p>
<p><b>Line 28:</b> This is the size of the hidden layer that will be storing our carry bit. Notice that it is way larger than it theoretically needs to be. Play with this and see how it affects the speed of convergence. Do larger hidden dimensions make things train faster or slower? More iterations or fewer?</p>
<p><b>Line 29:</b> Well, we're only predicting the sum, which is one number. Thus, we only need one output</p>
<p><b>Line 33:</b> This is the matrix of weights that connects our input layer and our hidden layer. Thus, it has "input_dim" rows and "hidden_dim" columns. (2 x 16 unless you change it). If you forgot what it does, look for it in the pictures in Part 2 of this blogpost.</p>
<p><b>Line 34:</b> This is the matrix of weights that connects the hidden layer to the output layer. Thus, it has "hidden_dim" rows and "output_dim" columns. (16 x 1 unless you change it). If you forgot what it does, look for it in the pictures in Part 2 of this blogpost.</p>
<p><b>Line 35:</b> This is the matrix of weights that connects the hidden layer in the previous time-step to the hidden layer in the current timestep. It also connects the hidden layer in the current timestep to the hidden layer in the next timestep (we keep using it). Thus, it has the dimensionality of "hidden_dim" rows and "hidden_dim" columns. (16 x 16 unless you change it). If you forgot what it does, look for it in the pictures in Part 2 of this blogpost.</p>
<p><b>Line 37 - 39:</b> These store the weight updates that we would like to make for each of the weight matrices. After we've accumulated several weight updates, we'll actually update the matrices. More on this later.</p>
<p><b>Line 42:</b> We're iterating over 100,000 training examples</p>
<p><b>Line 45:</b> We're going to generate a random addition problem. So, we're initializing an integer randomly between 0 and half of the largest value we can represent. If we allowed the network to represent more than this, than adding two number could theoretically overflow (be a bigger number than we have bits to represent). Thus, we only add numbers that are less than half of the largest number we can represent.</p>
<p><b>Line 46:</b> We lookup the binary form for "a_int" and store it in "a"</p>
<p><b>Line 48:</b> Same thing as line 45, just getting another random number.</p>
<p><b>Line 49:</b> Same thing as line 46, looking up the binary representation.</p>
<p><b>Line 52:</b> We're computing what the correct answer should be for this addition</p>
<p><b>Line 53:</b> Converting the true answer to its binary representation</p>
<p><b>Line 56:</b> Initializing an empty binary array where we'll store the neural network's predictions (so we can see it at the end). You could get around doing this if you want...but i thought it made things more intuitive</p>
<p><b>Line 58:</b> Resetting the error measure (which we use as a means to track convergence... see my tutorial on backpropagation and gradient descent to learn more about this)</p>
<p><b>Lines 60-61:</b> These two lists will keep track of the layer 2 derivatives and layer 1 values at each time step.</p>
<p><b>Line 62:</b> Time step zero has no previous hidden layer, so we initialize one that's off.</p>
<p><b>Line 65:</b> This for loop iterates through the binary representation</p>
<p><b>Line 68:</b> X is the same as "layer_0" in the pictures. X is a list of 2 numbers, one from a and one from b. It's indexed according to the "position" variable, but we index it in such a way that it goes from right to left. So, when position == 0, this is the farhest bit to the right in "a" and the farthest bit to the right in "b". When position equals 1, this shifts to the left one bit.
</p>
<p><b>Line 69:</b> Same indexing as line 62, but instead it's the value of the correct answer (either a 1 or a 0)</p>
<p><b>Line 72:</b> This is the magic!!! Make sure you understand this line!!! To construct the hidden layer, we first do two things. First, we propagate from the input to the hidden layer (np.dot(X,synapse_0)). Then, we propagate from the previous hidden layer to the current hidden layer (np.dot(prev_layer_1, synapse_h)). Then WE SUM THESE TWO VECTORS!!!!... and pass through the sigmoid function.</p>
<p>So, how do we combine the information from the previous hidden layer and the input? After each has been propagated through its various matrices (read: interpretations), we sum the information. </p>
<p><b>Line 75:</b> This should look very familiar. It's the same as previous tutorials. It propagates the hidden layer to the output to make a prediction</p>
<p><b>Line 78:</b> Compute by how much the prediction missed</p>
<p><b>Line 79:</b> We're going to store the derivative (mustard orange in the graphic above) in a list, holding the derivative at each timestep.</p>
<p><b>Line 80:</b> Calculate the sum of the absolute errors so that we have a scalar error (to track propagation). We'll end up with a sum of the error at each binary position.</p>
<p><b>Line 83</b> Rounds the output (to a binary value, since it is between 0 and 1) and stores it in the designated slot of d.
<p><b>Line 86</b> Copies the layer_1 value into an array so that at the next time step we can apply the hidden layer at the current one.</p>
<p><b>Line 90:</b> So, we've done all the forward propagating for all the time steps, and we've computed the derivatives at the output layers and stored them in a list. Now we need to backpropagate, starting with the last timestep, backpropagating to the first</p>
<p><b>Line 92:</b> Indexing the input data like we did before</p>
<p><b>Line 93:</b> Selecting the current hidden layer from the list.</p>
<p><b>Line 94:</b> Selecting the previous hidden layer from the list</p>
<p><b>Line 97:</b> Selecting the current output error from the list</p>
<p><b>Line 99:</b> this computes the current hidden layer error given the error at the hidden layer from the future and the error at the current output layer.</p>
<p><b>Line 102-104:</b> Now that we have the derivatives backpropagated at this current time step, we can construct our weight updates (but not actually update the weights just yet). We don't actually update our weight matrices until after we've fully backpropagated everything. Why? Well, we use the weight matrices for the backpropagation. Thus, we don't want to go changing them yet until the actual backprop is done. See the <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">backprop blog post</a> for more details.</p>
<p><b>Line 109 - 115</b> Now that we've backpropped everything and created our weight updates. It's time to update our weights (and empty the update variables).</p>
<p><b>Line 118 - end</b> Just some nice logging to show progress</p>
<h2 class="section-heading">Part 5: Questions / Comments</h2>
If you have questions or comments, tweet <a href="https://twitter.com/iamtrask"><b>@iamtrask</b></a> and I'll be happy to help.
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p></p></p></p></p>
Sun, 15 Nov 2015 12:00:00 +0000
https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/
https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/Hinton's Dropout in 3 Lines of Python<p><b>Summary:</b> Dropout is a vital feature in almost every state-of-the-art neural network implementation. This tutorial teaches how to install Dropout into a neural network in only a few lines of Python code. Those who walk through this tutorial will finish with a working Dropout implementation and will be empowered with the intuitions to install it and tune it in any neural network they encounter.</p>
<p><b>Followup Post:</b> I intend to write a followup post to this one adding popular features leveraged by <a href="http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html">state-of-the-art approaches</a>. I'll tweet it out when it's complete <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading more and thanks for all the feedback!</p>
<p><h3>Just Give Me The Code:</h3>
<pre class="brush:python; highlight:[4,9,10]">
import numpy as np
X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim,dropout_percent,do_dropout = (0.5,4,0.2,True)
synapse_0 = 2*np.random.random((3,hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
for j in xrange(60000):
layer_1 = (1/(1+np.exp(-(np.dot(X,synapse_0)))))
if(do_dropout):
layer_1 *= np.random.binomial([np.ones((len(X),hidden_dim))],1-dropout_percent)[0] * (1.0/(1-dropout_percent))
layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1))))
layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
synapse_0 -= (alpha * X.T.dot(layer_1_delta))
</pre>
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 1: What is Dropout?</h2>
<p>As discovered in the <a href="http://iamtrask.github.io/2015/07/27/python-network-part2/">previous post</a>, a neural network is a glorified search problem. Each node in the neural network is searching for correlation between the input data and the correct output data.</p>
<p><img class="img-responsive" width="100%" src="/img/sgd_randomness_ensemble.png" alt="" /></p>
<p>
Consider the graphic above from the previous post. The line represents the error the network generates for every value of a particular weight. The low-points (READ: low error) in that line signify the weight "finding" points of correlation between the input and output data. The balls in the picture signify various weights. They are trying to find those low points.</p>
<p>Consider the color. The ball's initial positions are randomly generated (just like weights in a neural network). If two balls randomly start in the same colored zone, they will converge to the same point. This makes them redundant! They're wasting computation and memory! This is exactly what happens in neural networks.
</p>
<p><b>Why Dropout:</b> Dropout helps prevent weights from converging to identical positions. It does this by <b>randomly turning nodes off</b> when forward propagating. It then back-propagates with all the nodes turned on. Let’s take a closer look.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 2 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="3842123822"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 2: How Do I Install and Tune Dropout?</h2>
<p>The highlighted code above demonstrates how to install dropout. To perform dropout on a layer, you randomly set some of the layer's values to 0 during forward propagation. This is demonstrated on <b>line 10</b>.</p>
<p><b>Line 9:</b> parameterizes using dropout at all. You see, you only want to use Dropout during <b>training</b>. Do not use it at runtime or on your testing dataset. </p>
<p><b>EDIT: Line 9:</b> has a second portion to increase the size of the values being propagated forward. This happens in proportion to the number of values being turned off. A simple intuition is that if you're turning off half of your hidden layer, you want to double the values that ARE pushing forward so that the output compensates correctly. Many thanks to <a href="https://twitter.com/karpathy">@karpathy</a> for catching this one.</p>
<h3>Tuning Best Practice</h3>
<p><b>Line 4:</b> parameterizes the dropout_percent. This affects the probability that any one node will be turned off. A good initial configuration for this for hidden layers is 50%. If applying dropout to an input layer, it's best to not exceed 25%.</p>
<p>Hinton advocates tuning dropout in conjunction with tuning the size of your hidden layer. Increase your hidden layer size(s) with dropout turned off until you perfectly fit your data. Then, using the same hidden layer size, train with dropout turned on. This should be a nearly optimal configuration. Turn off dropout as soon as you're done training and voila! You have a working neural network!</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 3 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="5318857026"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<!--
<h3 class="section-heading">Part 3: Why does Dropout Work?</h3>
<i> (This section builds upon concepts laid out in the <a href="http://iamtrask.github.io/2015/07/27/python-network-part2/">previous post</a>.)</i>
<p>Imagine that you had two identical values in your hidden layer. By "idential", I mean that their input weights were the same, so they turned on and off at exactly the same time. Given what we learned in Section 1 of this post, we know that this is a very real possibility.</p>
<p>This means that each weight was contributing half of an identical "vote" to the output. What if we turned one off and kept training? In this case, the network would start making errors because it was trained to expect two nodes to make this vote. In response, it would <b>turn up the volume</b> on the node that was still turned on until it was casting a <i>full vote</i> instead of a <i>half vote</i>.</p>
<p>So, what happens to the node that's turned off? Well, under the dropout approach, it's not turned off all the time. It's only turned off in the "forward propagation" step. It's not turned off in the "backward propagation" step. This means that it still updates its weights to account for the error in the network. However, since it's turned off, each of its updates doesn't actually affect the error of the network. So, we're updating a weight that's actually quite irrelevant to the quality of the network. Why would we do this?</p>
<p>Remember that when we update a weight, it converges to reduce the error. Once it has reduced the error, the network doesn't backprop anything in that direction anymore. So, when our "turned on" node starts having a "full vote", the "turned off" node doesn't feel the pull in that direction anymore.</p>
<p>So if the turned off node is feeling the pull of the network's error, EXCEPT for the pull in the direction of the "turned on" node, then it is free to ESCAPE to find a unique position in the network! <b>This is why dropout works!</b></p>
<p>Another intuitive perspective on dropout is that it is a form of <b>model averaging</b>. Basically, if you force the network to converge using random subsets of its hidden nodes, you're forcing nodes to not have to "rely" on each other, because you don't know if your neighbor is going to be turned on or off. This forces each node to be a very valuable "individual contributer" instead of converging to similar places as its neighbors. (This is the more common explanation.)</p>
<p><b>Wallah!</b> Now we know how dropout works! Well done!</p>
<img class="img-responsive" width="100%" src="/img/ford.jpg" alt="">
<hr />
-->
<h2 class="section-heading">Want to Work in Machine Learning?</h2>
<p>
One of the best things you can do to learn Machine Learning is to have a job where you're <b>practicing Machine Learning professionally</b>. I'd encourage you to check out the <a href="http://www.digitalreasoning.com/careers">positions at Digital Reasoning</a> in your job hunt. If you have questions about any of the positions or about life at Digital Reasoning, feel free to send me a message on <a href="https://www.linkedin.com/profile/view?id=226572677&trk=nav_responsive_tab_profile">my LinkedIn</a>. I'm happy to hear about where you want to go in life, and help you evaluate whether Digital Reasoning could be a good fit.
</p>
<p>If none of the positions above feel like a good fit. Continue your search! Machine Learning expertise is one of the <b>most valuable skills in the job market today</b>, and there are many firms looking for practitioners. Perhaps some of these services below will help you in your hunt.
<style type="text/css">#indJobContent{padding-bottom: 5px;}#indJobContent .company_location{font-size: 11px;overflow: hidden;display:block;}#indJobContent.wide .job{display:block;float:left;margin-right: 5px;width: 135px;overflow: hidden}#indeed_widget_wrapper{position: relative;font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;font-size: 13px;font-weight: normal;line-height: 18px;padding: 10px;height: auto;overflow: hidden;}#indeed_widget_header{font-size:18px; padding-bottom: 5px; }#indeed_search_wrapper{clear: both;font-size: 12px;margin-top: 5px;padding-top: 5px;}#indeed_search_wrapper label{font-size: 12px;line-height: inherit;text-align: left; margin-right: 5px;}#indeed_search_wrapper input[type='text']{width: 100px; font-size: 11px; }#indeed_search_wrapper #qc{float:left;}#indeed_search_wrapper #lc{float:right;}#indeed_search_wrapper.stacked #qc, #indeed_search_wrapper.stacked #lc{float: none; clear: both;}#indeed_search_wrapper.stacked input[type='text']{width: 150px;}#indeed_search_wrapper.stacked label{display: block;padding-bottom: 5px;}#indeed_search_footer{width:295px; padding-top: 5px; clear: both;}#indeed_link{position: absolute;bottom: 1px;right: 5px;clear: both;font-size: 11px; }#indeed_link a{text-decoration: none;}#results .job{padding: 1px 0px;}#pagination { clear: both; }</style><style type="text/css">
#indeed_widget_wrapper{ width: 50%; height: 600px; background: #FFFFFF;}
#indeed_widget_wrapper{ border: 1px solid #DDDDDD; }
#indeed_widget_wrapper, #indeed_link a{ color: #000000;}
#indJobContent, #indeed_search_wrapper{ border-top: 1px solid #DDDDDD; }
#indJobContent a { color: #00c; }
#indeed_widget_header{ color: #000000; }
</style>
<script type="text/javascript">
var ind_pub = '9172611916208179';
var ind_el = 'indJobContent';
var ind_pf = '';
var ind_q = 'Machine Learning';
var ind_l = '';
var ind_chnl = 'none';
var ind_n = 15;
var ind_d = 'http://www.indeed.com';
var ind_t = 40;
var ind_c = 30;
</script>
<script type="text/javascript" src="http://www.indeed.com/ads/jobroll-widget-v3.js"></script>
<div id="indeed_widget_wrapper" style="">
<div id="indeed_widget_header">Machine Learning Jobs</div>
<div id="indJobContent" class=""></div>
<div id="indeed_search_wrapper">
<script type="text/javascript">
function clearDefaults() {
var formInputs = document.getElementById('indeed_jobform').elements;
for(var i = 0; i < formInputs.length; i++) {
if(formInputs[i].value == 'title, keywords' || formInputs[i].value == 'city, state, or zip') {
formInputs[i].value = '';
}
}
}
</script>
<form onsubmit="clearDefaults();" method="get" action="http://www.indeed.com/jobs" id="indeed_jobform" target="_new">
<div id="qc"><label>What:</label><input type="text" onfocus="this.value=""" value="title, keywords" name="q" id="q" /></div>
<div id="lc"><label>Where:</label><input type="text" onfocus="this.value=""" value="city, state, or zip" name="l" id="l" /></div>
<div id="indeed_search_footer">
<div style="float:left"><input type="submit" value="Find Jobs" class="findjobs" /></div>
</div>
<input type="hidden" name="indpubnum" id="indpubnum" value="9172611916208179" />
</form>
</div>
<div id="indeed_link">
<a title="Job Search" href="http://www.indeed.com/" target="_new">jobs by <img alt="Indeed" src="http://www.indeed.com/p/jobsearch.gif" style="border: 0;vertical-align: bottom;" />
</a>
</div>
</div>
<div style="position:absolute; margin-top:-600px; margin-left:400px" id="MonsterJobSearchResultPlaceHolderNXAAAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQUeLsOxB7mqhf97nwIpkVXQ--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkNXAAAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/jobs/?q=Machine-Learning">View More Job Search Results</a>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p>
Tue, 28 Jul 2015 12:00:00 +0000
https://iamtrask.github.io/2015/07/28/dropout/
https://iamtrask.github.io/2015/07/28/dropout/A Neural Network in 13 lines of Python (Part 2 - Gradient Descent)<p><b>Summary:</b> I learn best with toy code that I can play with. This tutorial teaches gradient descent via a very simple toy example, a short python implementation.
<p><b>Followup Post:</b> I intend to write a followup post to this one adding popular features leveraged by <a href="http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html">state-of-the-art approaches</a> (likely Dropout, DropConnect, and Momentum). I'll tweet it out when it's complete <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading more and thanks for all the feedback!</p>
<p><h3>Just Give Me The Code:</h3>
<pre class="brush:python">
import numpy as np
X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
y = np.array([[0,1,1,0]]).T
alpha,hidden_dim = (0.5,4)
synapse_0 = 2*np.random.random((3,hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,1)) - 1
for j in xrange(60000):
layer_1 = 1/(1+np.exp(-(np.dot(X,synapse_0))))
layer_2 = 1/(1+np.exp(-(np.dot(layer_1,synapse_1))))
layer_2_delta = (layer_2 - y)*(layer_2*(1-layer_2))
layer_1_delta = layer_2_delta.dot(synapse_1.T) * (layer_1 * (1-layer_1))
synapse_1 -= (alpha * layer_1.T.dot(layer_2_delta))
synapse_0 -= (alpha * X.T.dot(layer_1_delta))
</pre>
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 1: Optimization</h2>
<p>In <a href="http://iamtrask.github.io/2015/07/12/basic-python-network/">Part 1</a>, I laid out the basis for backpropagation in a simple neural network. Backpropagation allowed us to measure how each weight in the network contributed to the overall error. This ultimately allowed us to change these weights using a different algorithm, <b>Gradient Descent</b>.
<p>The takeaway here is that <b>backpropagation doesn't optimize</b>! It moves the error information from the end of the network to all the weights inside the network so that a different algorithm can optimize those weights to fit our data. We actually have a plethora of different <b>nonlinear optimization methods</b> that we could use with backpropagation:</p>
<p style="margin-left:40px">
<b>A Few Optimization Methods:</b><br />
• <a href="http://www.heatonresearch.com/articles/9">Annealing</a><br />
• <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent">Stochastic Gradient Descent</a><br />
• <a href="http://arxiv.org/pdf/1506.09016v1.pdf">AW-SGD (new!)</a><br />
• <a href="http://jmlr.org/proceedings/papers/v28/sutskever13.pdf">Momentum (SGD)</a><br />
• <a href="http://jmlr.org/proceedings/papers/v28/sutskever13.pdf">Nesterov Momentum (SGD)</a><br />
• <a href="http://www.magicbroom.info/Papers/DuchiHaSi10.pdf">AdaGrad</a><br />
• <a href="http://arxiv.org/abs/1212.5701">AdaDelta</a><br />
• <a href="http://arxiv.org/abs/1412.6980">ADAM</a><br />
• <a href="https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm">BFGS</a><br />
• <a href="https://en.wikipedia.org/wiki/Limited-memory_BFGS">LBFGS</a>
<br /><br />
<b>Visualizing the Difference:</b><br />
• <a href="http://cs.stanford.edu/people/karpathy/convnetjs/demo/trainers.html">ConvNet.js</a><br />
• <a href="http://www.robertsdionne.com/bouncingball/">RobertsDionne</a>
</p>
<p>Many of these optimizations are good for different purposes, and in some cases several can be used together. In this tutorial, we will walk through Gradient Descent, which is arguably the simplest and most widely used neural network optimization algorithm. By learning about Gradient Descent, we will then be able to improve our toy neural network through parameterization and tuning, and ultimately make it a <b>lot more powerful</b>.
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 2 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="3842123822"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 2: Gradient Descent</h2>
<p>Imagine that you had a red ball inside of a rounded bucket like in the picture below. Imagine further that the red ball is trying to find the bottom of the bucket. This is <b>optimization</b>. In our case, the ball is optimizing it's position (from left to right) to find the lowest point in the bucket.</p>
<p style="text-align:center"><i>(pause here.... make sure you got that last sentence.... got it?)</i></p>
<p>So, to gamify this a bit. The ball has two options, left or right. It has one goal, get as low as possible. So, it needs to press the left and right buttons correctly to find the lowest spot</p>
<img class="img-responsive" width="100%" src="/img/sgd_no_lines.png" alt="" />
<p>So, what information does the ball use to adjust its position to find the lowest point? The only information it has is the <b>slope</b> of the side of the bucket at its current position, pictured below with the blue line. Notice that when the slope is negative (downward from left to right), the ball should move to the right. However, when the slope is positive, the ball should move to the left. As you can see, this is more than enough information to find the bottom of the bucket in a few iterations. This is a sub-field of optimization called <b>gradient optimization</b>. (Gradient is just a fancy word for slope or steepness).
</p>
<img class="img-responsive" width="100%" src="/img/sgd_optimal.png" alt="" />
<p>
<h4>Oversimplified Gradient Descent:</h4>
<ul>
<li>Calculate slope at current position</li>
<li>If slope is negative, move right</li>
<li>If slope is positive, move left</li>
<li>(Repeat until slope == 0)</li>
</ul>
</p>
<p>The question is, however, <b>how much should the ball move </b>at each time step? Look at the bucket again. The steeper the slope, the farther the ball is from the bottom. That's helpful! Let's improve our algorithm to leverage this new information. Also, let's assume that the bucket is on an (x,y) plane. So, it's location is x (along the bottom). Increasing the ball's "x" position moves it to the right. Decreasing the ball's "x" position moves it to the left.</p>
<p>
<h4>Naive Gradient Descent:</h4>
<ul>
<li>Calculate "slope" at current "x" position</li>
<li>Change x by the negative of the slope. (x = x - slope)</li>
<li>(Repeat until slope == 0)</li>
</ul>
</p>
<p>Make sure you can picture this process in your head before moving on. This is a considerable improvement to our algorithm. For very positive slopes, we move left by a lot. For only slightly positive slopes, we move left by only a little. As it gets closer and closer to the bottom, it takes smaller and smaller steps until the slope equals zero, at which point it stops. This stopping point is called <b>convergence</b>.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 3 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="5318857026"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 3: Sometimes It Breaks</h2>
<p>Gradient Descent isn't perfect. Let's take a look at its issues and how people get around them. This will allow us to improve our network to overcome these issues.</p>
<h3>Problem 1: When slopes are too big</h3>
<p>How big is too big? Remember our step size is based on the steepness of the slope. Sometimes the slope is so steep that we overshoot by a lot. Overshooting by a little is ok, but sometimes we overshoot by so much that we're even farther away than we started! See below. <br /></p>
<img class="img-responsive" width="100%" src="/img/sgd_high.png" alt="" />
<p>What makes this problem so destructive is that overshooting this far means we land at an <i>EVEN STEEPER</i> slope in the opposite direction. This causes us to overshoot again <i>EVEN FARTHER</i>. This viscious cycle of overshooting leading to more overshooting is called <b>divergence</b>.</p>
<h3>Solution 1: Make Slopes Smaller</h3>
<p>Lol. This may seem too simple to be true, but it's used in pretty much every neural network. If our gradients are too big, we make them smaller! We do this by multiplying them (all of them) by a single number between 0 and 1 (such as 0.01). This fraction is typically a single float called <b>alpha</b>. When we do this, we don't overshoot and our network converges.
<img class="img-responsive" width="100%" src="/img/sgd_optimal.png" alt="" /></p>
<p>
<h4>Improved Gradient Descent:</h4>
alpha = 0.1 (or some number between 0 and 1)
<ul>
<li>Calculate "slope" at current "x" position</li>
<li>x = x - (alpha*slope)</li>
<li>(Repeat until slope == 0)</li>
</ul>
</p>
<h3>Problem 2: Local Minimums</h3>
<p>Sometimes your bucket has a funny shape, and following the slope doesn't take you to the absolute lowest point. Consider the picture below.</p>
<img class="img-responsive" width="100%" src="/img/sgd_local_min.png" alt="" />
<p>
This is by far the most difficult problem with gradient descent. There are a myriad of options to try to overcome this. Generally speaking, they all involve an element of random searching to try lots of different parts of the bucket.
</p>
<h3>Solution 2: Multiple Random Starting States</h3>
<p>
There are a myriad of ways in which randomness is used to overcome getting stuck in a local minimum. It begs the question, if we have to use randomness to find the global minimum, why are we still optimizing in the first place? Why not just try randomly? The answer lies in the graph below.
</p>
<img class="img-responsive" width="100%" src="/img/sgd_randomness_ensemble.png" alt="" />
<p>
Imagine that we randomly placed 100 balls on this line and started optimizing all of them. If we did so, they would all end up in only 5 positions, mapped out by the five colored balls above. The colored regions represent the domain of each local minimum. For example, if a ball randomly falls within the blue domain, it will converge to the blue minimum. This means that to search the entire space, we only have to randomly find 5 spaces! This is far better than pure random searching, which has to randomly try EVERY space (which could easily be millions of places on this black line depending on the granularity).
</p>
<p><b>In Neural Networks:</b> One way that neural networks accomplish this is by having very large hidden layers. You see, each hidden node in a layer starts out in a different random starting state. This allows each hidden node to converge to different patterns in the network. Parameterizing this size allows the neural network user to potentially try thousands <a href="http://www.digitalreasoning.com/buzz/digital-reasoning-trains-worlds-largest-neural-network-shatters-record-previously-set-by-google.1672770">(or tens of billions)</a> of different local minima in a single neural network.</p>
<p><b>Sidenote 1:</b> <b>This is why neural networks are so powerful!</b> They have the ability to search far more of the space than they actually compute! We can search the entire black line above with (in theory) only 5 balls and a handful of iterations. Searching that same space in a brute force fashion could easily take orders of magnitude more computation.</p>
<p><b>Sidenote 2:</b> A close eye might ask, "Well, why would we allow a lot of nodes to converge to the same spot? That's actually wasting computational power!" That's an excellent point. The current state-of-the-art approaches to avoiding hidden nodes coming up with the same answer (by searching the same space) are Dropout and Drop-Connect, which I intend to cover in a later post.</p>
<h3>Problem 3: When Slopes are Too Small</h3>
<p>Neural networks sometimes suffer from the slopes being too small. The answer is also obvious but I wanted to mention it here to expand on its symptoms. Consider the following graph.</p>
<img class="img-responsive" width="100%" src="/img/sgd_small.png" alt="" />
<p>Our little red ball up there is just stuck! If your alpha is too small, this can happen. The ball just drops right into an instant local minimum and ignores the big picture. It doesn't have the <b>umph</b> to get out of the rut.</p>
</p>
<img class="img-responsive" width="100%" src="/img/sgd_small2.png" alt="" />
<p>And perhaps the more obvious symptom of deltas that are too small is that the convergence will just take a very, very long time.
<h3>Solution 3: Increase the Alpha</h3>
<p>As you might expect, the solution to both of these symptoms is to increase the alpha. We might even multiply our deltas by a weight higher than 1. This is very rare, but it does sometimes happen.</p>
<!-- <h3>Problem 3: When some slopes are too small AND others are too big!</h3>
<p>This one might sound a bit ridiculous. How can a single ball have more than one slope? In two dimensions where one is being optimized, this isn't possible. However, if a ball is sitting on a 3 dimensional hill, it has a coordinate for x,y,and z. Thus, if z is the height (which we're optimizing for), then both x and y can have slopes! Consider the following shape.
-->
<h2 class="section-heading">Part 4: SGD in Neural Networks</h2>
<p>So at this point you might be wondering, how does this relate to neural networks and backpropagation? This is the hardest part, so get ready to hold on tight and take things slow. It's also quite important.</p>
<img class="img-responsive" width="100%" src="/img/sgd_local_min.png" alt="" />
<p>
That big nasty curve? In a neural network, we're trying to minimize the <b>error with respect to the weights</b>. So, what that curve represents is the network's error relative to the position of a single weight. So, if we computed the network's error for every possible value of a single weight, it would generate the curve you see above. We would then pick the value of the single weight that has the lowest error (the lowest part of the curve). I say <i>single</i> weight because it's a two-dimensional plot. Thus, the x dimension is the value of the weight and the y dimension is the neural network's error when the weight is at that position.</p>
<center><b><i>Stop and make sure you got that last paragraph. It's key. </i></b></center>
<p>Let's take a look at what this process looks like in a simple 2 layer neural network.</p>
<h3>2 Layer Neural Network:</h3>
<pre class="brush: python">
import numpy as np
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
# input dataset
X = np.array([ [0,1],
[0,1],
[1,0],
[1,0] ])
# output dataset
y = np.array([[0,0,1,1]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# initialize weights randomly with mean 0
synapse_0 = 2*np.random.random((2,1)) - 1
for iter in xrange(10000):
# forward propagation
layer_0 = X
layer_1 = sigmoid(np.dot(layer_0,synapse_0))
# how much did we miss?
layer_1_error = layer_1 - y
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1)
synapse_0_derivative = np.dot(layer_0.T,layer_1_delta)
# update weights
synapse_0 -= synapse_0_derivative
print "Output After Training:"
print layer_1
</pre>
<p>So, in this case, we have a single error at the output (single value), which is computed on line 35. Since we have 2 weights, the output "error plane" is a 3 dimensional space. We can think of this as an (x,y,z) plane, where vertical is the error, and x and y are the values of our two weights in syn0.</p>
<p>Let's try to plot what the error plane looks like for the network/dataset above. So, how do we compute the error for a given set of weights? Lines 31,32,and 35 show us that. If we take that logic and plot the overall error (a single scalar representing the network error over the entire dataset) for every possible set of weights (from -10 to 10 for x and y), it looks something like this.</p>
<center>
<img class="img-responsive" width="50%" src="/img/3d_error_plane.gif" alt="" />
</center>
<p>Don't be intimidated by this. It really is as simple as computing every possible set of weights, and the error that the network generates at each set. x is the first synapse_0 weight and y is the second synapse_0 weight. z is the overall error. As you can see, our output data is <b>positively correlated</b> with the first input data. Thus, the error is minimized when x (the first synapse_0 weight) is high. What about the second synapse_0 weight? How is it optimal?</p>
<h3>How Our 2 Layer Neural Network Optimizes</h3>
<p>So, given that lines 31,32,and 35 end up computing the error. It can be natural to see that lines 39, 40, and 43 optimize to reduce the error. This is where Gradient Descent is happening! Remember our pseudocode?
<p>
<h4>Naive Gradient Descent:</h4>
<ul>
<li><b>Lines 39 and 40: </b>Calculate "slope" at current "x" position</li>
<li><b>Line 43: </b>Change x by the negative of the slope. (x = x - slope)</li>
<li><b>Line 28: </b>(Repeat until slope == 0)</li>
</ul>
</p>
<p>It's exactly the same thing! The only thing that has changed is that we have 2 weights that we're optimizing instead of just 1. The logic, however, is identical.</p>
<h2 class="section-heading">Part 5: Improving our Neural Network</h2>
<p>Remember that Gradient Descent had some weaknesses. Now that we have seen how our neural network leverages Gradient Descent, we can improve our network to overcome these weaknesses in the same way that we improved Gradient Descent in Part 3 (the 3 problems and solutions).</p>
<h3>Improvement 1: Adding and Tuning the Alpha Parameter</h3>
<!-- <p>
If you have ever tuned an iterative algorithm, you have probably come across the shrouded, hand-wavey mystery around tuning the alpha parameter. Neural networks are the poster child of seemingly random optimal tuning. Quite frequently, authors of famous papers will later post that better tuning has lead to increased quality with the same algorithm long after their publication.
</p> -->
<p><b>What is Alpha?</b> As described above, the alpha parameter reduces the size of each iteration's update in the simplest way possible. At the very last minute, right before we update the weights, we multiply the weight update by alpha (usually between 0 and 1, thus reducing the size of the weight update). This tiny change to the code has absolutely <b>massive</b> impact on its ability to train.
</p>
<p>We're going to jump back to our 3 layer neural network from the first post and add in an alpha parameter at the appropriate place. Then, we're going to run a series of experiments to align all the intuition we developed around alpha with its behavior in live code.</p>
<p>
<h4>Improved Gradient Descent:</h4>
<ul>
<li>Calculate "slope" at current "x" position</li>
<li><b>Lines 56 and 57: </b>Change x by the negative of the slope scaled by alpha. (x = x - (alpha*slope) )</li>
<li>(Repeat until slope == 0)</li>
</ul>
</p>
<pre class="brush:python; highlight:[56,57]">
import numpy as np
alphas = [0.001,0.01,0.1,1,10,100,1000]
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
for alpha in alphas:
print "\nTraining With Alpha:" + str(alpha)
np.random.seed(1)
# randomly initialize our weights with mean 0
synapse_0 = 2*np.random.random((3,4)) - 1
synapse_1 = 2*np.random.random((4,1)) - 1
for j in xrange(60000):
# Feed forward through layers 0, 1, and 2
layer_0 = X
layer_1 = sigmoid(np.dot(layer_0,synapse_0))
layer_2 = sigmoid(np.dot(layer_1,synapse_1))
# how much did we miss the target value?
layer_2_error = layer_2 - y
if (j% 10000) == 0:
print "Error after "+str(j)+" iterations:" + str(np.mean(np.abs(layer_2_error)))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
layer_2_delta = layer_2_error*sigmoid_output_to_derivative(layer_2)
# how much did each l1 value contribute to the l2 error (according to the weights)?
layer_1_error = layer_2_delta.dot(synapse_1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1)
synapse_1 -= alpha * (layer_1.T.dot(layer_2_delta))
synapse_0 -= alpha * (layer_0.T.dot(layer_1_delta))
</pre>
<pre>
Training With Alpha:0.001
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.495164025493
Error after 20000 iterations:0.493596043188
Error after 30000 iterations:0.491606358559
Error after 40000 iterations:0.489100166544
Error after 50000 iterations:0.485977857846
Training With Alpha:0.01
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.457431074442
Error after 20000 iterations:0.359097202563
Error after 30000 iterations:0.239358137159
Error after 40000 iterations:0.143070659013
Error after 50000 iterations:0.0985964298089
Training With Alpha:0.1
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.0428880170001
Error after 20000 iterations:0.0240989942285
Error after 30000 iterations:0.0181106521468
Error after 40000 iterations:0.0149876162722
Error after 50000 iterations:0.0130144905381
Training With Alpha:1
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.00858452565325
Error after 20000 iterations:0.00578945986251
Error after 30000 iterations:0.00462917677677
Error after 40000 iterations:0.00395876528027
Error after 50000 iterations:0.00351012256786
Training With Alpha:10
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.00312938876301
Error after 20000 iterations:0.00214459557985
Error after 30000 iterations:0.00172397549956
Error after 40000 iterations:0.00147821451229
Error after 50000 iterations:0.00131274062834
Training With Alpha:100
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.125476983855
Error after 20000 iterations:0.125330333528
Error after 30000 iterations:0.125267728765
Error after 40000 iterations:0.12523107366
Error after 50000 iterations:0.125206352756
Training With Alpha:1000
Error after 0 iterations:0.496410031903
Error after 10000 iterations:0.5
Error after 20000 iterations:0.5
Error after 30000 iterations:0.5
Error after 40000 iterations:0.5
Error after 50000 iterations:0.5
</pre>
<p>So, what did we observe with the different alpha sizes?</p>
<p><b>Alpha = 0.001</b> <br />The network with a crazy small alpha didn't hardly converge! This is because we made the weight updates so small that they hardly changed anything, even after 60,000 iterations! This is textbook <b>Problem 3:When Slopes Are Too Small</b>.</p>
<p><b>Alpha = 0.01</b> <br />This alpha made a rather pretty convergence. It was quite smooth over the course of the 60,000 iterations but ultimately didn't converge as far as some of the others. This still is textbook <b>Problem 3:When Slopes Are Too Small</b>.</p>
<p><b>Alpha = 0.1</b><br />This alpha made some of progress very quickly but then slowed down a bit. This is still <b>Problem 3</b>. We need to increase alpha some more. </p>
<p><b>Alpha = 1</b><br />As a clever eye might suspect, this had the exact convergence as if we had no alpha at all! Multiplying our weight updates by 1 doesn't change anything. :)</p>
<p><b>Alpha = 10</b><br />Perhaps you were surprised that an alpha that was greater than 1 achieved the best score after only 10,000 iterations! This tells us that our weight updates were being too conservative with smaller alphas. This means that in the smaller alpha parameters (less than 10), the network's weights were generally headed in the right direction, they just needed to hurry up and get there!</p>
<p><b>Alpha = 100</b><br />
Now we can see that taking steps that are too large can be very counterproductive. The network's steps are so large that it can't find a reasonable lowpoint in the error plane. This is textbook <b>Problem 1</b>. The Alpha is too big so it just jumps around on the error plane and never "settles" into a local minimum.
</p>
<p><b>Alpha = 1000</b><br />
And with an extremely large alpha, we see a textbook example of divergence, with the error increasing instead of decreasing... hardlining at 0.5. This is a more extreme version of <b>Problem 3</b> where it overcorrectly whildly and ends up very far away from any local minimums.
</p>
<h3>Let's Take a Closer Look</h3>
<pre class="brush:python">
import numpy as np
alphas = [0.001,0.01,0.1,1,10,100,1000]
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
for alpha in alphas:
print "\nTraining With Alpha:" + str(alpha)
np.random.seed(1)
# randomly initialize our weights with mean 0
synapse_0 = 2*np.random.random((3,4)) - 1
synapse_1 = 2*np.random.random((4,1)) - 1
prev_synapse_0_weight_update = np.zeros_like(synapse_0)
prev_synapse_1_weight_update = np.zeros_like(synapse_1)
synapse_0_direction_count = np.zeros_like(synapse_0)
synapse_1_direction_count = np.zeros_like(synapse_1)
for j in xrange(60000):
# Feed forward through layers 0, 1, and 2
layer_0 = X
layer_1 = sigmoid(np.dot(layer_0,synapse_0))
layer_2 = sigmoid(np.dot(layer_1,synapse_1))
# how much did we miss the target value?
layer_2_error = y - layer_2
if (j% 10000) == 0:
print "Error:" + str(np.mean(np.abs(layer_2_error)))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
layer_2_delta = layer_2_error*sigmoid_output_to_derivative(layer_2)
# how much did each l1 value contribute to the l2 error (according to the weights)?
layer_1_error = layer_2_delta.dot(synapse_1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1)
synapse_1_weight_update = (layer_1.T.dot(layer_2_delta))
synapse_0_weight_update = (layer_0.T.dot(layer_1_delta))
if(j > 0):
synapse_0_direction_count += np.abs(((synapse_0_weight_update > 0)+0) - ((prev_synapse_0_weight_update > 0) + 0))
synapse_1_direction_count += np.abs(((synapse_1_weight_update > 0)+0) - ((prev_synapse_1_weight_update > 0) + 0))
synapse_1 += alpha * synapse_1_weight_update
synapse_0 += alpha * synapse_0_weight_update
prev_synapse_0_weight_update = synapse_0_weight_update
prev_synapse_1_weight_update = synapse_1_weight_update
print "Synapse 0"
print synapse_0
print "Synapse 0 Update Direction Changes"
print synapse_0_direction_count
print "Synapse 1"
print synapse_1
print "Synapse 1 Update Direction Changes"
print synapse_1_direction_count
</pre>
<pre>
Training With Alpha:0.001
Error:0.496410031903
Error:0.495164025493
Error:0.493596043188
Error:0.491606358559
Error:0.489100166544
Error:0.485977857846
Synapse 0
[[-0.28448441 0.32471214 -1.53496167 -0.47594822]
[-0.7550616 -1.04593014 -1.45446052 -0.32606771]
[-0.2594825 -0.13487028 -0.29722666 0.40028038]]
Synapse 0 Update Direction Changes
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 1. 0. 1. 1.]]
Synapse 1
[[-0.61957526]
[ 0.76414675]
[-1.49797046]
[ 0.40734574]]
Synapse 1 Update Direction Changes
[[ 1.]
[ 1.]
[ 0.]
[ 1.]]
Training With Alpha:0.01
Error:0.496410031903
Error:0.457431074442
Error:0.359097202563
Error:0.239358137159
Error:0.143070659013
Error:0.0985964298089
Synapse 0
[[ 2.39225985 2.56885428 -5.38289334 -3.29231397]
[-0.35379718 -4.6509363 -5.67005693 -1.74287864]
[-0.15431323 -1.17147894 1.97979367 3.44633281]]
Synapse 0 Update Direction Changes
[[ 1. 1. 0. 0.]
[ 2. 0. 0. 2.]
[ 4. 2. 1. 1.]]
Synapse 1
[[-3.70045078]
[ 4.57578637]
[-7.63362462]
[ 4.73787613]]
Synapse 1 Update Direction Changes
[[ 2.]
[ 1.]
[ 0.]
[ 1.]]
Training With Alpha:0.1
Error:0.496410031903
Error:0.0428880170001
Error:0.0240989942285
Error:0.0181106521468
Error:0.0149876162722
Error:0.0130144905381
Synapse 0
[[ 3.88035459 3.6391263 -5.99509098 -3.8224267 ]
[-1.72462557 -5.41496387 -6.30737281 -3.03987763]
[ 0.45953952 -1.77301389 2.37235987 5.04309824]]
Synapse 0 Update Direction Changes
[[ 1. 1. 0. 0.]
[ 2. 0. 0. 2.]
[ 4. 2. 1. 1.]]
Synapse 1
[[-5.72386389]
[ 6.15041318]
[-9.40272079]
[ 6.61461026]]
Synapse 1 Update Direction Changes
[[ 2.]
[ 1.]
[ 0.]
[ 1.]]
Training With Alpha:1
Error:0.496410031903
Error:0.00858452565325
Error:0.00578945986251
Error:0.00462917677677
Error:0.00395876528027
Error:0.00351012256786
Synapse 0
[[ 4.6013571 4.17197193 -6.30956245 -4.19745118]
[-2.58413484 -5.81447929 -6.60793435 -3.68396123]
[ 0.97538679 -2.02685775 2.52949751 5.84371739]]
Synapse 0 Update Direction Changes
[[ 1. 1. 0. 0.]
[ 2. 0. 0. 2.]
[ 4. 2. 1. 1.]]
Synapse 1
[[ -6.96765763]
[ 7.14101949]
[-10.31917382]
[ 7.86128405]]
Synapse 1 Update Direction Changes
[[ 2.]
[ 1.]
[ 0.]
[ 1.]]
Training With Alpha:10
Error:0.496410031903
Error:0.00312938876301
Error:0.00214459557985
Error:0.00172397549956
Error:0.00147821451229
Error:0.00131274062834
Synapse 0
[[ 4.52597806 5.77663165 -7.34266481 -5.29379829]
[ 1.66715206 -7.16447274 -7.99779235 -1.81881849]
[-4.27032921 -3.35838279 3.44594007 4.88852208]]
Synapse 0 Update Direction Changes
[[ 7. 19. 2. 6.]
[ 7. 2. 0. 22.]
[ 19. 26. 9. 17.]]
Synapse 1
[[ -8.58485788]
[ 10.1786297 ]
[-14.87601886]
[ 7.57026121]]
Synapse 1 Update Direction Changes
[[ 22.]
[ 15.]
[ 4.]
[ 15.]]
Training With Alpha:100
Error:0.496410031903
Error:0.125476983855
Error:0.125330333528
Error:0.125267728765
Error:0.12523107366
Error:0.125206352756
Synapse 0
[[-17.20515374 1.89881432 -16.95533155 -8.23482697]
[ 5.70240659 -17.23785161 -9.48052574 -7.92972576]
[ -4.18781704 -0.3388181 2.82024759 -8.40059859]]
Synapse 0 Update Direction Changes
[[ 8. 7. 3. 2.]
[ 13. 8. 2. 4.]
[ 16. 13. 12. 8.]]
Synapse 1
[[ 9.68285369]
[ 9.55731916]
[-16.0390702 ]
[ 6.27326973]]
Synapse 1 Update Direction Changes
[[ 13.]
[ 11.]
[ 12.]
[ 10.]]
Training With Alpha:1000
Error:0.496410031903
Error:0.5
Error:0.5
Error:0.5
Error:0.5
Error:0.5
Synapse 0
[[-56.06177241 -4.66409623 -5.65196179 -23.05868769]
[ -4.52271708 -4.78184499 -10.88770202 -15.85879101]
[-89.56678495 10.81119741 37.02351518 -48.33299795]]
Synapse 0 Update Direction Changes
[[ 3. 2. 4. 1.]
[ 1. 2. 2. 1.]
[ 6. 6. 4. 1.]]
Synapse 1
[[ 25.16188889]
[ -8.68235535]
[-116.60053379]
[ 11.41582458]]
Synapse 1 Update Direction Changes
[[ 7.]
[ 7.]
[ 7.]
[ 3.]]
</pre>
<p>What I did in the above code was count the <b>number of times a derivative changed direction</b>. That's the "Update Direction Changes" readout at the end of training. If a slope (derivative) changes direction, it means that it passed OVER the local minimum and needs to go back. If it never changes direction, it means that it probably didn't go far enough.</p>
<h4>A Few Takeaways:</h4>
<ul>
<li>When the alpha was tiny, the derivatives almost never changed direction.</li>
<li>When the alpha was optimal, the derivative changed directions a TON.</li>
<li>When the alpha was huge, the derivative changed directions a medium amount.</li>
<li>When the alph was tiny, the weights ended up being reasonably small too</li>
<li>When the alpha was huge, the weights got huge too!</li>
</ul>
<h3>Improvement 2: Parameterizing the Size of the Hidden Layer</h3>
<p>Being able to increase the size of the hidden layer increases the amount of search space that we converge to in each iteration. Consider the network and output</p>
<pre class="brush:python">
import numpy as np
alphas = [0.001,0.01,0.1,1,10,100,1000]
hiddenSize = 32
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
for alpha in alphas:
print "\nTraining With Alpha:" + str(alpha)
np.random.seed(1)
# randomly initialize our weights with mean 0
synapse_0 = 2*np.random.random((3,hiddenSize)) - 1
synapse_1 = 2*np.random.random((hiddenSize,1)) - 1
for j in xrange(60000):
# Feed forward through layers 0, 1, and 2
layer_0 = X
layer_1 = sigmoid(np.dot(layer_0,synapse_0))
layer_2 = sigmoid(np.dot(layer_1,synapse_1))
# how much did we miss the target value?
layer_2_error = layer_2 - y
if (j% 10000) == 0:
print "Error after "+str(j)+" iterations:" + str(np.mean(np.abs(layer_2_error)))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
layer_2_delta = layer_2_error*sigmoid_output_to_derivative(layer_2)
# how much did each l1 value contribute to the l2 error (according to the weights)?
layer_1_error = layer_2_delta.dot(synapse_1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1)
synapse_1 -= alpha * (layer_1.T.dot(layer_2_delta))
synapse_0 -= alpha * (layer_0.T.dot(layer_1_delta))
</pre>
<pre>
Training With Alpha:0.001
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.491049468129
Error after 20000 iterations:0.484976307027
Error after 30000 iterations:0.477830678793
Error after 40000 iterations:0.46903846539
Error after 50000 iterations:0.458029258565
Training With Alpha:0.01
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.356379061648
Error after 20000 iterations:0.146939845465
Error after 30000 iterations:0.0880156127416
Error after 40000 iterations:0.065147819275
Error after 50000 iterations:0.0529658087026
Training With Alpha:0.1
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.0305404908386
Error after 20000 iterations:0.0190638725334
Error after 30000 iterations:0.0147643907296
Error after 40000 iterations:0.0123892429905
Error after 50000 iterations:0.0108421669738
Training With Alpha:1
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.00736052234249
Error after 20000 iterations:0.00497251705039
Error after 30000 iterations:0.00396863978159
Error after 40000 iterations:0.00338641021983
Error after 50000 iterations:0.00299625684932
Training With Alpha:10
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.00224922117381
Error after 20000 iterations:0.00153852153014
Error after 30000 iterations:0.00123717718456
Error after 40000 iterations:0.00106119569132
Error after 50000 iterations:0.000942641990774
Training With Alpha:100
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.5
Error after 20000 iterations:0.5
Error after 30000 iterations:0.5
Error after 40000 iterations:0.5
Error after 50000 iterations:0.5
Training With Alpha:1000
Error after 0 iterations:0.496439922501
Error after 10000 iterations:0.5
Error after 20000 iterations:0.5
Error after 30000 iterations:0.5
Error after 40000 iterations:0.5
Error after 50000 iterations:0.5
</pre>
<p>Notice that the best error with 32 nodes is 0.0009 whereas the best error with 4 hidden nodes was only 0.0013. This might not seem like much, but it's an important lesson. We <b>do not need any more than 3 nodes to represent this dataset</b>. However, because we had more nodes when we started, we searched more of the space in each iteration and ultimately converged faster. Even though this is very marginal in this toy problem, this affect plays a huge role when modeling very complex datasets.</p>
<h2>Part 6: Conclusion and Future Work</h2>
<br />
<p><h3>My Recommendation:</h3>
If you're serious about neural networks, I have one recommendation. <b>Try to rebuild this network from memory.</b> I know that might sound a bit crazy, but it seriously helps. If you want to be able to create arbitrary architectures based on new academic papers or read and understand sample code for these different architectures, I think that it's a killer exercise. I think it's useful even if you're using frameworks like <a href="http://torch.ch/">Torch</a>, <a href="http://caffe.berkeleyvision.org/">Caffe</a>, or <a href="http://deeplearning.net/software/theano/">Theano</a>. I worked with neural networks for a couple years before performing this exercise, and it was the best investment of time I've made in the field (and it didn't take long).
</p>
<p><h3>Future Work</h3>
This toy example still needs quite a few bells and whistles to really approach the state-of-the-art architectures. Here's a few things you can look into if you want to further improve your network. (Perhaps I will in a followup post.)</p>
<p style="padding-left:20px">
• <a href="http://stackoverflow.com/questions/2480650/role-of-bias-in-neural-networks">Bias Units</a><br />
• <a href="https://class.coursera.org/ml-003/lecture/106">Mini-Batches</a><br />
• Delta Trimming <br />
• <a href="https://www.youtube.com/watch?v=XqRUHEeiyCs">Parameterized Layer Sizes</a><br />
• <a href="https://class.coursera.org/ml-003/lecture/63">Regularization</a><br />
• <a href="http://videolectures.net/nips2012_hinton_networks/">Dropout</a><br />
• <a href="https://www.youtube.com/watch?v=XqRUHEeiyCs">Momentum</a><br />
• <a href="http://arxiv.org/abs/1502.03167">Batch Normalization</a> <br />
• GPU Compatability<br />
• Other Awesomeness You Implement<br />
</p>
<hr />
<h2 class="section-heading">Want to Work in Machine Learning?</h2>
<p>
One of the best things you can do to learn Machine Learning is to have a job where you're <b>practicing Machine Learning professionally</b>. I'd encourage you to check out the <a href="https://www.linkedin.com/vsearch/j?page_num=1&locationType=Y&f_C=74158&trk=jobs_biz_prem_all_header">positions at Digital Reasoning</a> in your job hunt. If you have questions about any of the positions or about life at Digital Reasoning, feel free to send me a message on <a href="https://www.linkedin.com/profile/view?id=226572677&trk=nav_responsive_tab_profile">my LinkedIn</a>. I'm happy to hear about where you want to go in life, and help you evaluate whether Digital Reasoning could be a good fit.
</p>
<p>If none of the positions above feel like a good fit. Continue your search! Machine Learning expertise is one of the <b>most valuable skills in the job market today</b>, and there are many firms looking for practitioners. Perhaps some of these services below will help you in your hunt.
<style type="text/css">#indJobContent{padding-bottom: 5px;}#indJobContent .company_location{font-size: 11px;overflow: hidden;display:block;}#indJobContent.wide .job{display:block;float:left;margin-right: 5px;width: 135px;overflow: hidden}#indeed_widget_wrapper{position: relative;font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;font-size: 13px;font-weight: normal;line-height: 18px;padding: 10px;height: auto;overflow: hidden;}#indeed_widget_header{font-size:18px; padding-bottom: 5px; }#indeed_search_wrapper{clear: both;font-size: 12px;margin-top: 5px;padding-top: 5px;}#indeed_search_wrapper label{font-size: 12px;line-height: inherit;text-align: left; margin-right: 5px;}#indeed_search_wrapper input[type='text']{width: 100px; font-size: 11px; }#indeed_search_wrapper #qc{float:left;}#indeed_search_wrapper #lc{float:right;}#indeed_search_wrapper.stacked #qc, #indeed_search_wrapper.stacked #lc{float: none; clear: both;}#indeed_search_wrapper.stacked input[type='text']{width: 150px;}#indeed_search_wrapper.stacked label{display: block;padding-bottom: 5px;}#indeed_search_footer{width:295px; padding-top: 5px; clear: both;}#indeed_link{position: absolute;bottom: 1px;right: 5px;clear: both;font-size: 11px; }#indeed_link a{text-decoration: none;}#results .job{padding: 1px 0px;}#pagination { clear: both; }</style><style type="text/css">
#indeed_widget_wrapper{ width: 50%; height: 600px; background: #FFFFFF;}
#indeed_widget_wrapper{ border: 1px solid #DDDDDD; }
#indeed_widget_wrapper, #indeed_link a{ color: #000000;}
#indJobContent, #indeed_search_wrapper{ border-top: 1px solid #DDDDDD; }
#indJobContent a { color: #00c; }
#indeed_widget_header{ color: #000000; }
</style>
<script type="text/javascript">
var ind_pub = '9172611916208179';
var ind_el = 'indJobContent';
var ind_pf = '';
var ind_q = 'Machine Learning';
var ind_l = '';
var ind_chnl = 'none';
var ind_n = 15;
var ind_d = 'http://www.indeed.com';
var ind_t = 40;
var ind_c = 30;
</script>
<script type="text/javascript" src="http://www.indeed.com/ads/jobroll-widget-v3.js"></script>
<div id="indeed_widget_wrapper" style="">
<div id="indeed_widget_header">Machine Learning Jobs</div>
<div id="indJobContent" class=""></div>
<div id="indeed_search_wrapper">
<script type="text/javascript">
function clearDefaults() {
var formInputs = document.getElementById('indeed_jobform').elements;
for(var i = 0; i < formInputs.length; i++) {
if(formInputs[i].value == 'title, keywords' || formInputs[i].value == 'city, state, or zip') {
formInputs[i].value = '';
}
}
}
</script>
<form onsubmit="clearDefaults();" method="get" action="http://www.indeed.com/jobs" id="indeed_jobform" target="_new">
<div id="qc"><label>What:</label><input type="text" onfocus="this.value=""" value="title, keywords" name="q" id="q" /></div>
<div id="lc"><label>Where:</label><input type="text" onfocus="this.value=""" value="city, state, or zip" name="l" id="l" /></div>
<div id="indeed_search_footer">
<div style="float:left"><input type="submit" value="Find Jobs" class="findjobs" /></div>
</div>
<input type="hidden" name="indpubnum" id="indpubnum" value="9172611916208179" />
</form>
</div>
<div id="indeed_link">
<a title="Job Search" href="http://www.indeed.com/" target="_new">jobs by <img alt="Indeed" src="http://www.indeed.com/p/jobsearch.gif" style="border: 0;vertical-align: bottom;" />
</a>
</div>
</div>
<div style="position:absolute; margin-top:-600px; margin-left:400px" id="MonsterJobSearchResultPlaceHolderNXAAAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQUeLsOxB7mqhf97nwIpkVXQ--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkNXAAAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/jobs/?q=Machine-Learning">View More Job Search Results</a>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p></p></p></p>
Mon, 27 Jul 2015 12:00:00 +0000
https://iamtrask.github.io/2015/07/27/python-network-part2/
https://iamtrask.github.io/2015/07/27/python-network-part2/A Neural Network in 11 lines of Python (Part 1)<p><b>Summary:</b> I learn best with toy code that I can play with. This tutorial teaches backpropagation via a very simple toy example, a short python implementation.</p>
<p><b>Edit:</b> Some folks have asked about a followup article, and I'm planning to write one. I'll tweet it out when it's complete at <a href="https://twitter.com/iamtrask">@iamtrask</a>. Feel free to follow if you'd be interested in reading it and thanks for all the feedback!
</p>
<h3>Just Give Me The Code:</h3>
<pre class="brush: python">
X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ])
y = np.array([[0,1,1,0]]).T
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
for j in xrange(60000):
l1 = 1/(1+np.exp(-(np.dot(X,syn0))))
l2 = 1/(1+np.exp(-(np.dot(l1,syn1))))
l2_delta = (y - l2)*(l2*(1-l2))
l1_delta = l2_delta.dot(syn1.T) * (l1 * (1-l1))
syn1 += l1.T.dot(l2_delta)
syn0 += X.T.dot(l1_delta)
</pre>
<p><b>Other Languages: </b><a href="https://github.com/Marenz/neural_net_examples">D</a><br /></p>
<p>However, this is a bit terse…. let’s break it apart into a few simple parts.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 1: A Tiny Toy Network</h2>
<p>A neural network trained with backpropagation is attempting to use input to predict output.</p>
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px;}
.tg .tg-4kyz{font-size:20px;text-align:center;}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="3">Inputs</th>
<th class="tg-5rcs">Output</th>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
</table>
</center>
<p>Consider trying to predict the output column given the three input columns. We could solve this problem by simply <b>measuring statistics</b> between the input values and the output values. If we did so, we would see that the leftmost input column is <i>perfectly correlated</i> with the output. Backpropagation, in its simplest form, measures statistics like this to make a model. Let's jump right in and use it to do this.</p>
<h3>2 Layer Neural Network:</h3>
<pre class="brush: python">
import numpy as np
# sigmoid function
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input dataset
X = np.array([ [0,0,1],
[0,1,1],
[1,0,1],
[1,1,1] ])
# output dataset
y = np.array([[0,0,1,1]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1
for iter in xrange(10000):
# forward propagation
l0 = X
l1 = nonlin(np.dot(l0,syn0))
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
l1_delta = l1_error * nonlin(l1,True)
# update weights
syn0 += np.dot(l0.T,l1_delta)
print "Output After Training:"
print l1
</pre>
<pre>
Output After Training:
[[ 0.00966449]
[ 0.00786506]
[ 0.99358898]
[ 0.99211957]]
</pre>
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px; text-align:center; padding-left:20px; padding-right: 20px;}
.tg .tg-4kyx{font-size:20px;text-align:center;font-weight:italic; padding-left:20px; padding-right: 20px;}
.tg .tg-4kyz{font-size:20px;text-align:left; padding-left: 20px;}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="1">Variable</th>
<th class="tg-5rcs">Definition</th>
</tr>
<tr>
<td class="tg-4kyx">X</td>
<td class="tg-4kyz">Input dataset matrix where each row is a training example</td>
</tr>
<tr>
<td class="tg-4kyx">y</td>
<td class="tg-4kyz">Output dataset matrix where each row is a training example</td>
</tr>
<tr>
<td class="tg-4kyx">l0</td>
<td class="tg-4kyz">First Layer of the Network, specified by the input data</td>
</tr>
<tr>
<td class="tg-4kyx">l1</td>
<td class="tg-4kyz">Second Layer of the Network, otherwise known as the hidden layer</td>
</tr>
<tr>
<td class="tg-4kyx">syn0</td>
<td class="tg-4kyz">First layer of weights, Synapse 0, connecting l0 to l1.</td>
</tr>
<tr>
<td class="tg-4kyx">*</td>
<td class="tg-4kyz">Elementwise multiplication, so two vectors of equal size are multiplying corresponding values 1-to-1 to generate a final vector of identical size.</td>
</tr>
</tr>
<tr>
<td class="tg-4kyx">-</td>
<td class="tg-4kyz">Elementwise subtraction, so two vectors of equal size are subtracting corresponding values 1-to-1 to generate a final vector of identical size.</td>
</tr>
<tr>
<td class="tg-4kyx">x.dot(y)</td>
<td class="tg-4kyz">If x and y are vectors, this is a dot product. If both are matrices, it's a matrix-matrix multiplication. If only one is a matrix, then it's vector matrix multiplication.</td>
</tr>
</table>
</center>
<p>As you can see in the "Output After Training", it works!!! Before I describe processes, I recommend playing around with the code to get an intuitive feel for how it works. You should be able to run it "as is" in an <a href="http://ipython.org/notebook.html">ipython notebook</a> (or a script if you must, but I HIGHLY recommend the notebook). Here are some good places to look in the code: <br />
<div style="padding-left:20px">
• Compare l1 after the first iteration and after the last iteration. <br />
• Check out the "nonlin" function. This is what gives us a probability as output.<br />
• Check out how l1_error changes as you iterate. <br />
• Take apart line 36. Most of the secret sauce is here. <br />
• Check out line 39. Everything in the network prepares for this operation. <br />
<br />
</div>
<p>
Let's walk through the code line by line.
</p>
<p><b>Recommendation:</b> open this blog in two screens so you can see the code while you read it. That's kinda what I did while I wrote it. :)</p>
<p><b>Line 01:</b>
This imports numpy, which is a linear algebra library. This is our only dependency.
</p>
<p><b>Line 04:</b>
This is our "nonlinearity". While it can be several kinds of functions, this nonlinearity maps a function called a "sigmoid". A <a href="https://en.wikipedia.org/wiki/Sigmoid_function">sigmoid function</a> maps any value to a value between 0 and 1. We use it to convert numbers to probabilities. It also has several other desirable properties for training neural networks.
</p>
<img class="img-responsive" width="100%" src="/img/sigmoid.png" alt="" />
<p><b>Line 05:</b>
Notice that this function can also generate the derivative of a sigmoid (when deriv=True). One of the desirable properties of a sigmoid function is that its output can be used to create its derivative. If the sigmoid's output is a variable "out", then the derivative is simply out * (1-out). This is very efficient. <br /><br />
If you're unfamililar with derivatives, just think about it as the slope of the sigmoid function at a given point (as you can see above, different points have different slopes). For more on derivatives, check out this <a href="https://www.khanacademy.org/math/differential-calculus/taking-derivatives/derivative_intro/v/calculus-derivatives-1"> derivatives tutorial</a> from Khan Academy.
<p><b>Line 10:</b>
This initializes our input dataset as a numpy matrix. Each row is a single "training example". Each column corresponds to one of our input nodes. Thus, we have 3 input nodes to the network and 4 training examples.
</p>
<p><b>Line 16:</b>
This initializes our output dataset. In this case, I generated the dataset horizontally (with a single row and 4 columns) for space. ".T" is the transpose function. After the transpose, this y matrix has 4 rows with one column. Just like our input, each row is a training example, and each column (only one) is an output node. So, our network has 3 inputs and 1 output.
</p>
<p><b>Line 20:</b>
It's good practice to seed your random numbers. Your numbers will still be randomly distributed, but they'll be randomly distributed in <b>exactly the same way</b> each time you train. This makes it easier to see how your changes affect the network.
</p>
<p><b>Line 23:</b>
This is our weight matrix for this neural network. It's called "syn0" to imply "synapse zero". Since we only have 2 layers (input and output), we only need one matrix of weights to connect them. Its dimension is (3,1) because we have 3 inputs and 1 output. Another way of looking at it is that l0 is of size 3 and l1 is of size 1. Thus, we want to connect every node in l0 to every node in l1, which requires a matrix of dimensionality (3,1). :)
<br /><br />
Also notice that it is initialized randomly with a mean of zero. There is quite a bit of theory that goes into weight initialization. For now, just take it as a best practice that it's a good idea to have a mean of zero in weight initialization.
<br /><br />
Another note is that the "neural network" is really just this matrix. We have "layers" l0 and l1 but they are transient values based on the dataset. We don't save them. All of the learning is stored in the syn0 matrix.
</p>
<p><b>Line 25:</b>
This begins our actual network training code. This for loop "iterates" multiple times over the training code to optimize our network to the dataset.
</p>
<p><b>Line 28:</b>
Since our first layer, l0, is simply our data. We explicitly describe it as such at this point. Remember that X contains 4 training examples (rows). We're going to process all of them at the same time in this implementation. This is known as "full batch" training. Thus, we have 4 different l0 rows, but you can think of it as a single training example if you want. It makes no difference at this point. (We could load in 1000 or 10,000 if we wanted to without changing any of the code).
</p>
<p><b>Line 29:</b>
This is our prediction step. Basically, we first let the network "try" to predict the output given the input. We will then study how it performs so that we can adjust it to do a bit better for each iteration. <br /><br />
This line contains 2 steps. The first matrix multiplies l0 by syn0. The second passes our output through the sigmoid function. Consider the dimensions of each:<br /><br />
(4 x 3) dot (3 x 1) = (4 x 1) <br /><br />
Matrix multiplication is ordered, such the dimensions in the middle of the equation must be the same. The final matrix generated is thus the number of rows of the first matrix and the number of columns of the second matrix.<br /><br />
Since we loaded in 4 training examples, we ended up with 4 guesses for the correct answer, a (4 x 1) matrix. Each output corresponds with the network's guess for a given input. Perhaps it becomes intuitive why we could have "loaded in" an arbitrary number of training examples. The matrix multiplication would still work out. :)
</p>
<p><b>Line 32:</b>
So, given that l1 had a "guess" for each input. We can now compare how well it did by subtracting the true answer (y) from the guess (l1). l1_error is just a vector of positive and negative numbers reflecting how much the network missed.
</p>
<p><b>Line 36:</b>
Now we're getting to the good stuff! This is the secret sauce! There's a lot going on in this line, so let's further break it into two parts.
<h4>First Part: The Derivative</h4>
<pre class="brush:python">
nonlin(l1,True)
</pre>
</p>
<p>
If l1 represents these three dots, the code above generates the slopes of the lines below. Notice that very high values such as x=2.0 (green dot) and very low values such as x=-1.0 (purple dot) have rather shallow slopes. The highest slope you can have is at x=0 (blue dot). This plays an important role. Also notice that all derivatives are between 0 and 1.
</p>
<img class="img-responsive" width="100%" src="/img/sigmoid-deriv-2.png" alt="" />
<h4>Entire Statement: The Error Weighted Derivative</h4>
<pre class="brush:python">
l1_delta = l1_error * nonlin(l1,True)
</pre>
<p>There are more "mathematically precise" ways than "The Error Weighted Derivative" but I think that this captures the intuition. l1_error is a (4,1) matrix. nonlin(l1,True) returns a (4,1) matrix. What we're doing is multiplying them <a href="http://nl.mathworks.com/help/matlab/ref/times.html">"elementwise"</a>. This returns a (4,1) matrix <b>l1_delta</b> with the multiplied values. <br /><br />
When we multiply the "slopes" by the error, we are <b>reducing the error of high confidence predictions</b>. Look at the sigmoid picture again! If the slope was really shallow (close to 0), then the network either had a very high value, or a very low value. This means that the network was quite confident one way or the other. However, if the network guessed something close to (x=0, y=0.5) then it isn't very confident. We update these "wishy-washy" predictions most heavily, and we tend to leave the confident ones alone by multiplying them by a number close to 0.
<p><b>Line 39:</b>
We are now ready to update our network! Let's take a look at a single training example.
<img class="img-responsive" width="100%" src="/img/toy_network_deriv.png" alt="" />
In this training example, we're all setup to update our weights. Let's update the far left weight (9.5).<br /><br />
<b>weight_update = input_value * l1_delta</b>
<br /><br />
For the far left weight, this would multiply 1.0 * the l1_delta. Presumably, this would increment 9.5 ever so slightly. Why only a small ammount? Well, the prediction was already very confident, and the prediction was largely correct. A small error and a small slope means a VERY small update. Consider all the weights. It would ever so slightly increase all three.
</p>
<img class="img-responsive" width="100%" src="/img/toy_network_batch.png" alt="" />
<p>
However, because we're using a "full batch" configuration, we're doing the above step on all four training examples. So, it looks a lot more like the image above. So, what does line 39 do? It computes the weight updates for each weight for each training example, sums them, and updates the weights, all in a simple line. Play around with the matrix multiplication and you'll see it do this!
</p>
<p><h3>Takeaways:</h3>
So, now that we've looked at how the network updates, let's look back at our training data and reflect. When both an input and a output are 1, we increase the weight between them. When an input is 1 and an output is 0, we decrease the weight between them. </p>
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px;}
.tg .tg-4kyz{font-size:20px;text-align:center;}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="3">Inputs</th>
<th class="tg-5rcs">Output</th>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
</table>
</center>
<p>
Thus, in our four training examples below, the weight from the first input to the output would <b>consistently increment or remain unchanged</b>, whereas the other two weights would find themselves <b>both increasing and decreasing across training examples</b> (cancelling out progress). This phenomenon is what causes our network to learn based on correlations between the input and output.
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 2 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="3842123822"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 2: A Slightly Harder Problem</h2>
<br />
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px;}
.tg .tg-4kyz{font-size:20px;text-align:center}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="3">Inputs</th>
<th class="tg-5rcs">Output</th>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
</tr>
</table>
</center>
<p>Consider trying to predict the output column given the two input columns. A key takeway should be that neither columns have any correlation to the output. Each column has a 50% chance of predicting a 1 and a 50% chance of predicting a 0. </p>
<p>
So, what's the pattern? It appears to be completely unrelated to column three, which is always 1. However, columns 1 and 2 give more clarity. If either column 1 or 2 are a 1 (but not both!) then the output is a 1. This is our pattern.
</p>
<p>
This is considered a "nonlinear" pattern because there isn't a direct one-to-one relationship between the input and output. Instead, there is a <b>one-to-one relationship between a combination of inputs</b>, namely columns 1 and 2.
</p>
<div id="pic1" style="float:left;width:50%"><img class="img-responsive" width="100%" src="/img/rcnn.png" alt="" /><br /></div>
<div id="pic2" style="float:right;width:50%;"><img class="img-responsive" width="100%" src="/img/margritti-this-is-not-a-pipe.jpg" alt="" /><br /></div>
<p>Believe it or not, image recognition is a similar problem. If one had 100 identically sized images of pipes and bicycles, no individual pixel position would directly correlate with the presence of a bicycle or pipe. The pixels might as well be random from a purely statistical point of view. However, certain <b>combinations of pixels</b> are not random, namely the combination that forms the image of a bicycle or a person.</p>
<h3>Our Strategy</h3>
<p> In order to first combine pixels into something that can then have a one-to-one relationship with the output, we need to add another layer. Our first layer will combine the inputs, and our second layer will then map them to the output using the output of the first layer as input. Before we jump into an implementation though, take a look at this table.</p>
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px;}
.tg .tg-4kyz{font-size:20px;text-align:center}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="3">Inputs (l0)</th>
<th class="tg-5rcs" colspan="4">Hidden Weights (l1)</th>
<th class="tg-5rcs">Output (l2)</th>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0.1</td>
<td class="tg-4kyz">0.2</td>
<td class="tg-4kyz">0.5</td>
<td class="tg-4kyz">0.2</td>
<td class="tg-4kyz">0</td>
</tr>
<tr>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0.2</td>
<td class="tg-4kyz">0.6</td>
<td class="tg-4kyz">0.7</td>
<td class="tg-4kyz">0.1</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0.3</td>
<td class="tg-4kyz">0.2</td>
<td class="tg-4kyz">0.3</td>
<td class="tg-4kyz">0.9</td>
<td class="tg-4kyz">1</td>
</tr>
<tr>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">1</td>
<td class="tg-4kyz">0.2</td>
<td class="tg-4kyz">0.1</td>
<td class="tg-4kyz">0.3</td>
<td class="tg-4kyz">0.8</td>
<td class="tg-4kyz">0</td>
</tr>
</table>
</center>
<p>
If we randomly initialize our weights, we will get hidden state values for layer 1. Notice anything? <b>The second column (second hidden node), has a slight correlation with the output already!</b> It's not perfect, but it's there. Believe it or not, this is a huge part of how neural networks train. (Arguably, it's the only way that neural networks train.) What the training below is going to do is amplify that correlation. It's both going to update syn1 to map it to the output, and update syn0 to be better at producing it from the input!
</p>
<p>
Note: The field of adding more layers to model more combinations of relationships such as this is known as <a href="https://en.wikipedia.org/wiki/Deep_learning">"deep learning"</a> because of the increasingly deep layers being modeled.</p>
<h3>3 Layer Neural Network:</h3>
<pre class="brush: python">
import numpy as np
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],
[1],
[1],
[0]])
np.random.seed(1)
# randomly initialize our weights with mean 0
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
for j in xrange(60000):
# Feed forward through layers 0, 1, and 2
l0 = X
l1 = nonlin(np.dot(l0,syn0))
l2 = nonlin(np.dot(l1,syn1))
# how much did we miss the target value?
l2_error = y - l2
if (j% 10000) == 0:
print "Error:" + str(np.mean(np.abs(l2_error)))
# in what direction is the target value?
# were we really sure? if so, don't change too much.
l2_delta = l2_error*nonlin(l2,deriv=True)
# how much did each l1 value contribute to the l2 error (according to the weights)?
l1_error = l2_delta.dot(syn1.T)
# in what direction is the target l1?
# were we really sure? if so, don't change too much.
l1_delta = l1_error * nonlin(l1,deriv=True)
syn1 += l1.T.dot(l2_delta)
syn0 += l0.T.dot(l1_delta)
</pre>
<!-- <h3>Runtime Output:</h3> -->
<pre>
Error:0.496410031903
Error:0.00858452565325
Error:0.00578945986251
Error:0.00462917677677
Error:0.00395876528027
Error:0.00351012256786
</pre>
<center>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-5rcs{font-weight:bold;font-size:20px; text-align:center; padding-left:20px; padding-right: 20px;}
.tg .tg-4kyx{font-size:20px;text-align:center;font-weight:italic; padding-left:20px; padding-right: 20px;}
.tg .tg-4kyz{font-size:20px;text-align:left; padding-left: 20px;}
</style>
<table class="tg">
<tr>
<th class="tg-5rcs" colspan="1">Variable</th>
<th class="tg-5rcs">Definition</th>
</tr>
<tr>
<td class="tg-4kyx">X</td>
<td class="tg-4kyz">Input dataset matrix where each row is a training example</td>
</tr>
<tr>
<td class="tg-4kyx">y</td>
<td class="tg-4kyz">Output dataset matrix where each row is a training example</td>
</tr>
<tr>
<td class="tg-4kyx">l0</td>
<td class="tg-4kyz">First Layer of the Network, specified by the input data</td>
</tr>
<tr>
<td class="tg-4kyx">l1</td>
<td class="tg-4kyz">Second Layer of the Network, otherwise known as the hidden layer</td>
</tr>
<tr>
<td class="tg-4kyx">l2</td>
<td class="tg-4kyz">Final Layer of the Network, which is our hypothesis, and should approximate the correct answer as we train.</td>
</tr>
<tr>
<td class="tg-4kyx">syn0</td>
<td class="tg-4kyz">First layer of weights, Synapse 0, connecting l0 to l1.</td>
</tr>
<tr>
<td class="tg-4kyx">syn1</td>
<td class="tg-4kyz">Second layer of weights, Synapse 1 connecting l1 to l2.</td>
</tr>
<tr>
<td class="tg-4kyx">l2_error</td>
<td class="tg-4kyz">This is the amount that the neural network "missed".</td>
</tr>
<tr>
<td class="tg-4kyx">l2_delta</td>
<td class="tg-4kyz">This is the error of the network scaled by the confidence. It's almost identical to the error except that very confident errors are muted.</td>
</tr>
<tr>
<td class="tg-4kyx">l1_error</td>
<td class="tg-4kyz">Weighting l2_delta by the weights in syn1, we can calculate the error in the middle/hidden layer.</td>
</tr>
<tr>
<td class="tg-4kyx">l1_delta</td>
<td class="tg-4kyz">This is the l1 error of the network scaled by the confidence. Again, it's almost identical to the l1_error except that confident errors are muted.</td>
</tr>
</table>
</center>
<p><b>Recommendation:</b> open this blog in two screens so you can see the code while you read it. That's kinda what I did while I wrote it. :)</p>
<p>
Everything should look very familiar! It's really just 2 of the previous implementation stacked on top of each other. The output of the first layer (l1) is the input to the second layer. The only new thing happening here is on line 43.
</p>
<p><b>Line 43:</b> uses the "confidence weighted error" from l2 to establish an error for l1. To do this, it simply sends the error across the weights from l2 to l1. This gives what you could call a "contribution weighted error" because we learn how much each node value in l1 "contributed" to the error in l2. This step is called "backpropagating" and is the namesake of the algorithm. We then update syn0 using the same steps we did in the 2 layer implementation.
</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 3 -->
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px;text-align:center" data-ad-client="ca-pub-6751104560361558" data-ad-slot="5318857026"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<hr />
<h2 class="section-heading">Part 3: Conclusion and Future Work</h2>
<br />
<p><h3>My Recommendation:</h3>
If you're serious about neural networks, I have one recommendation. <b>Try to rebuild this network from memory.</b> I know that might sound a bit crazy, but it seriously helps. If you want to be able to create arbitrary architectures based on new academic papers or read and understand sample code for these different architectures, I think that it's a killer exercise. I think it's useful even if you're using frameworks like <a href="http://torch.ch/">Torch</a>, <a href="http://caffe.berkeleyvision.org/">Caffe</a>, or <a href="http://deeplearning.net/software/theano/">Theano</a>. I worked with neural networks for a couple years before performing this exercise, and it was the best investment of time I've made in the field (and it didn't take long).
</p>
<p><h3>Future Work</h3>
This toy example still needs quite a few bells and whistles to really approach the state-of-the-art architectures. Here's a few things you can look into if you want to further improve your network. (Perhaps I will in a followup post.)</p>
<p style="padding-left:20px">
• Alpha <br />
• <a href="http://stackoverflow.com/questions/2480650/role-of-bias-in-neural-networks">Bias Units</a><br />
• <a href="https://class.coursera.org/ml-003/lecture/106">Mini-Batches</a><br />
• Delta Trimming <br />
• <a href="https://www.youtube.com/watch?v=XqRUHEeiyCs">Parameterized Layer Sizes</a><br />
• <a href="https://class.coursera.org/ml-003/lecture/63">Regularization</a><br />
• <a href="http://videolectures.net/nips2012_hinton_networks/">Dropout</a><br />
• <a href="https://www.youtube.com/watch?v=XqRUHEeiyCs">Momentum</a><br />
• <a href="http://arxiv.org/abs/1502.03167">Batch Normalization</a> <br />
• GPU Compatability<br />
• Other Awesomeness You Implement<br />
</p>
<hr />
<h2 class="section-heading">Want to Work in Machine Learning?</h2>
<p>
One of the best things you can do to learn Machine Learning is to have a job where you're <b>practicing Machine Learning professionally</b>. I'd encourage you to check out the <a href="https://www.linkedin.com/vsearch/j?page_num=1&locationType=Y&f_C=74158&trk=jobs_biz_prem_all_header">positions at Digital Reasoning</a> in your job hunt. If you have questions about any of the positions or about life at Digital Reasoning, feel free to send me a message on <a href="https://www.linkedin.com/profile/view?id=226572677&trk=nav_responsive_tab_profile">my LinkedIn</a>. I'm happy to hear about where you want to go in life, and help you evaluate whether Digital Reasoning could be a good fit.
</p>
<p>If none of the positions above feel like a good fit. Continue your search! Machine Learning expertise is one of the <b>most valuable skills in the job market today</b>, and there are many firms looking for practitioners. Perhaps some of these services below will help you in your hunt.
<style type="text/css">#indJobContent{padding-bottom: 5px;}#indJobContent .company_location{font-size: 11px;overflow: hidden;display:block;}#indJobContent.wide .job{display:block;float:left;margin-right: 5px;width: 135px;overflow: hidden}#indeed_widget_wrapper{position: relative;font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;font-size: 13px;font-weight: normal;line-height: 18px;padding: 10px;height: auto;overflow: hidden;}#indeed_widget_header{font-size:18px; padding-bottom: 5px; }#indeed_search_wrapper{clear: both;font-size: 12px;margin-top: 5px;padding-top: 5px;}#indeed_search_wrapper label{font-size: 12px;line-height: inherit;text-align: left; margin-right: 5px;}#indeed_search_wrapper input[type='text']{width: 100px; font-size: 11px; }#indeed_search_wrapper #qc{float:left;}#indeed_search_wrapper #lc{float:right;}#indeed_search_wrapper.stacked #qc, #indeed_search_wrapper.stacked #lc{float: none; clear: both;}#indeed_search_wrapper.stacked input[type='text']{width: 150px;}#indeed_search_wrapper.stacked label{display: block;padding-bottom: 5px;}#indeed_search_footer{width:295px; padding-top: 5px; clear: both;}#indeed_link{position: absolute;bottom: 1px;right: 5px;clear: both;font-size: 11px; }#indeed_link a{text-decoration: none;}#results .job{padding: 1px 0px;}#pagination { clear: both; }</style><style type="text/css">
#indeed_widget_wrapper{ width: 50%; height: 600px; background: #FFFFFF;}
#indeed_widget_wrapper{ border: 1px solid #DDDDDD; }
#indeed_widget_wrapper, #indeed_link a{ color: #000000;}
#indJobContent, #indeed_search_wrapper{ border-top: 1px solid #DDDDDD; }
#indJobContent a { color: #00c; }
#indeed_widget_header{ color: #000000; }
</style>
<script type="text/javascript">
var ind_pub = '9172611916208179';
var ind_el = 'indJobContent';
var ind_pf = '';
var ind_q = 'Machine Learning';
var ind_l = '';
var ind_chnl = 'none';
var ind_n = 15;
var ind_d = 'http://www.indeed.com';
var ind_t = 40;
var ind_c = 30;
</script>
<script type="text/javascript" src="http://www.indeed.com/ads/jobroll-widget-v3.js"></script>
<div id="indeed_widget_wrapper" style="">
<div id="indeed_widget_header">Machine Learning Jobs</div>
<div id="indJobContent" class=""></div>
<div id="indeed_search_wrapper">
<script type="text/javascript">
function clearDefaults() {
var formInputs = document.getElementById('indeed_jobform').elements;
for(var i = 0; i < formInputs.length; i++) {
if(formInputs[i].value == 'title, keywords' || formInputs[i].value == 'city, state, or zip') {
formInputs[i].value = '';
}
}
}
</script>
<form onsubmit="clearDefaults();" method="get" action="http://www.indeed.com/jobs" id="indeed_jobform" target="_new">
<div id="qc"><label>What:</label><input type="text" onfocus="this.value=""" value="title, keywords" name="q" id="q" /></div>
<div id="lc"><label>Where:</label><input type="text" onfocus="this.value=""" value="city, state, or zip" name="l" id="l" /></div>
<div id="indeed_search_footer">
<div style="float:left"><input type="submit" value="Find Jobs" class="findjobs" /></div>
</div>
<input type="hidden" name="indpubnum" id="indpubnum" value="9172611916208179" />
</form>
</div>
<div id="indeed_link">
<a title="Job Search" href="http://www.indeed.com/" target="_new">jobs by <img alt="Indeed" src="http://www.indeed.com/p/jobsearch.gif" style="border: 0;vertical-align: bottom;" />
</a>
</div>
</div>
<div style="position:absolute; margin-top:-600px; margin-left:400px" id="MonsterJobSearchResultPlaceHolderNXAAAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQUeLsOxB7mqhf97nwIpkVXQ--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkNXAAAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/jobs/?q=Machine-Learning">View More Job Search Results</a>
<link rel="stylesheet" type="text/css" href="/css/shCore.css" />
<link rel="stylesheet" type="text/css" href="/css/shThemeDefault.css" />
<script src="/js/shCore.js"></script>
<script src="/js/shLegacy.js"></script>
<script src="/js/shBrushPython.js"></script>
<script type="text/javascript">
// SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.toolbar = true;
SyntaxHighlighter.all();
</script>
</p></p></p></p>
Sun, 12 Jul 2015 12:00:00 +0000
https://iamtrask.github.io/2015/07/12/basic-python-network/
https://iamtrask.github.io/2015/07/12/basic-python-network/Word2Vec Analysis of Harry Potter<p>Word2vec is a very cool algorithm that uses neural networks to map words to feature vectors. Those vectors then have interesting properties. You can use these vectors to cluster words into groups… find words that are most similar in an unsupervised fashion.</p>
<p>I ran <a href="https://code.google.com/p/word2vec/">word2vec</a> on the 7 harry potter books and ran some cosine similarities on words i thought might be interesting. (using the open source <a href="http://radimrehurek.com/gensim/">Gensim</a> library I love) My favorite is the word “password” below… which revealed a list of passwords to the Gryffendor Common Room.</p>
<p>The top word of each list is the focus word… and then a list of the most similar words thereafter.</p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<expecto</b> <br />
0.8790060473734644:<patronum <br />
0.755879251292692:<pettigrews <br />
0.6931649914220047:<scabbers <br />
0.6921019768155199:<pettigrew <br />
0.6854965539870754:<lumos <br />
0.6800035990521911:<groped <br />
0.664763725362591:<buckbeaks <br />
0.6386204400460198:<lupins <br />
0.6368874336372525:<forcing <br />
<br />
(256 dimensions : 10 epochs)<br />
<b>1.0000000000000002:<expecto</b> <br />
0.881676712172453:<patronum <br />
0.66633365764735:<expec <br />
0.5100899639798923:<patrono <br />
0.4183506799917183:<poppy <br />
0.4151233329572086:<wailed <br />
0.4093665595659816:<nicknamed <br />
0.3973543132151556:<riddikulus <br />
0.3944545196592748:<fistbeating <br />
0.39103755743544927:<bristling <br /></p>
<p>(256 dimensions : 10 epochs)<br />
<b>1.0:<lumos</b> <br />
0.42209239730743003:<imperio <br />
0.40507159450163904:<ignited <br />
0.3758083182732268:<tergeo <br />
0.3744004687853999:<episkey <br />
0.3658264199741773:<portus <br />
0.35926607923955595:<uhoh <br />
0.3574845249683229:<serpensortia <br />
0.35644744188201566:<wandtip <br />
0.3503601500539219:<dissendium <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0:<weasley</b> <br />
0.7899136471577068:<cole <br />
0.7580984973288645:<weasleys <br />
0.704308962845765:<cattermole <br />
0.696147590313737:<figg <br />
0.6615516871288135:<bill <br />
0.5775892972766857:<mr <br />
0.5623844627363042:<mrs <br />
0.547272989628803:<crouch <br />
0.5346744691953205:<brightly <br />
<br />
(256 dimensions : 10 epochs)<br />
<b>1.0:<weasley</b> <br />
0.5571492216402788:<mrs <br />
0.525661506461713:<mr <br />
0.5122609732187181:<redheads <br />
0.47470149235833253:<greatauntie <br />
0.4636894081306857:<basil <br />
0.4615857402277965:<wwhats <br />
0.44954942844918266:<whew <br />
0.44593325992665894:<pranksters <br />
0.4366713328133361:<weasleys <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<potter</b> <br />
0.7040619432963181:<severus <br />
0.6994994807105462:<thank <br />
0.6875348923351211:<sir <br />
0.6822709821434811:<please <br />
0.632136736822497:<may <br />
0.6291806648311767:<cannot <br />
0.6284403688596681:<yes <br />
0.624241093676769:<kindly <br />
0.6217287188964961:<will <br />
<br />
(256 dimensions : 10 epochs)<br />
<b>0.9999999999999999:<potter </b><br />
0.3901893042844876:<humble <br />
0.38913611920424174:<rotter <br />
0.36768347738598195:<heed <br />
0.3666138243923663:<heroworshipped <br />
0.3587120147197108:<woooooooo <br />
0.34933445012876724:<characters <br />
0.3440882110680894:<dunderbore <br />
0.344022635479845:<questionall <br />
0.34103571192794435:<pining <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<gryffindor</b> <br />
0.74139062089133:<team <br />
0.734880573018089:<tower <br />
0.7231970430099021:<slytherin <br />
0.7021615040969098:<common <br />
0.7018928824840882:<ravenclaw <br />
0.6585783668158374:<points <br />
0.6540640450146518:<spinnet <br />
0.64507063817762:<bell <br />
0.6289645923037345:<goal <br />
<br />
(256 dimensions : 10 epochs)<br />
<b>1.0:<gryffindor</b> <br />
0.4581853977277023:<hufflepuff <br />
0.4420478362268596:<tower <br />
0.44149319299048684:<points <br />
0.4410251892894441:<slytherin <br />
0.4188516239321704:<ravenclaw <br />
0.3600329597460896:<gryffindors <br />
0.35418207017889025:<team <br />
0.34891474092816965:<wellearned <br />
0.3404098626732141:<penalty <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>0.9999999999999999:<ravenclaw</b> <br />
0.781214400477696:<hufflepuff <br />
0.7512446691492253:<slytherin <br />
0.7254427881734692:<captain <br />
0.7208340720937167:<oclock <br />
0.7147691706800555:<lee <br />
0.7147331227062966:<montague <br />
0.7018928824840882:<gryffindor <br />
0.697691445889272:<team <br />
0.6839508546137936:<wednesday <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<ravenclaw</b> <br />
0.5732267167869871:<hufflepuff <br />
0.43935832571981465:<slytherin <br />
0.43555165040705907:<rowena <br />
0.4188516239321704:<gryffindor <br />
0.407678924818592:<turpin <br />
0.38709404961590305:<helga <br />
0.3708434204576607:<seeker <br />
0.35874384841804063:<huffepuff <br />
0.35602194786273583:<loses <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0:<hufflepuff</b> <br />
0.7921196174194491:<fifth <br />
0.7848088164254446:<seventh <br />
0.781214400477696:<ravenclaw <br />
0.7780135594276192:<fourth <br />
0.7568581966579454:<hufflepuffs <br />
0.7452088578170768:<slytherin <br />
0.7329618627066322:<slytherins <br />
0.7241609971259948:<thursday <br />
0.7202963910695652:<gryffindors <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<hufflepuff</b> <br />
0.5732267167869871:<ravenclaw <br />
0.560598634502152:<slytherin <br />
0.4581853977277023:<gryffindor <br />
0.41404169865069024:<points <br />
0.41335251749481483:<helga <br />
0.40705600406104697:<pushover <br />
0.3964490683438199:<applauding <br />
0.39567843096475613:<loses <br />
0.39244432848771427:<match <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<slytherin</b> <br />
0.7512446691492253:<ravenclaw <br />
0.7452088578170768:<hufflepuff <br />
0.7238327202395243:<team <br />
0.7231970430099021:<gryffindor <br />
0.7165509326427633:<captain <br />
0.7030698136643037:<bell <br />
0.6922161358648197:<goal <br />
0.6914818449404438:<montague <br />
0.6612854741883617:<pucey <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<slytherin</b> <br />
0.560598634502152:<hufflepuff <br />
0.44370546214405354:<slytherins <br />
0.4410251892894441:<gryffindor <br />
0.43935832571981465:<ravenclaw <br />
0.4111100118874837:<team <br />
0.3960522941982452:<captain <br />
0.3834171440911241:<gains <br />
0.3816636526374869:<pushover <br />
0.37815919943099136:<fen <br /></p>
<p>(64 dimensions : 1 epoch)<br />
1.0:<hermione <br />
<b>0.6373033872867323:<she</b> <br />
0.5360344746735539:<neville <br />
0.5274756001139249:<he <br />
0.5214301504925287:<ginny <br />
0.5109574888160943:<ron <br />
0.4999163834053927:<luna <br />
0.49574563180394704:<harry <br />
0.451967913703171:<romilda <br />
0.446476077232399:<her <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0000000000000002:</b><hermione <br />
0.5042554769286905:<ron <br />
0.4808255935304602:<she <br />
0.3717110232643911:<ginny <br />
0.35913453543144513:<acidly <br />
0.35306516236363134:<ermyknee <br />
0.3515929674760651:<encouragingly <br />
0.35124423149024275:<uhoh <br />
0.3455436053959502:<grabbing <br />
0.34365264010683094:<lavender <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0:<dumbledore</b> <br />
0.7867909396010355:<snape <br />
0.652590036205367:<slughorn <br />
0.6378681113816113:<voldemort <br />
0.6120050198022656:<aberforth <br />
0.6019010767912868:<he <br />
0.5929735071374835:<scrimgeour <br />
0.5840436894354705:<sirius <br />
0.5553253520856778:<dumbledores <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<dumbledore</b> <br />
0.49688884807669753:<snape <br />
0.43320641875023586:<fudge <br />
0.42104734145946027:<voldemort <br />
0.409769764165034:<corpses <br />
0.40586327560858065:<lupin <br />
0.3992514094799346:<dumbledores <br />
0.3984795966379898:<headmaster <br />
0.36481567503440565:<devastating <br />
0.35980117000272555:<riddle <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<spell</b> <br />
0.5705834288105536:<jinx <br />
0.5528068188658538:<clear <br />
0.5308173140619804:<however <br />
0.5256446406146716:<crumplehorned <br />
0.5217704552103746:<hit <br />
0.5214290685798957:<latter <br />
0.5210853653286843:<sectumsempra <br />
0.5204984581955842:<dolohov <br />
0.5172019428367624:<made <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>0.9999999999999999:<spell</b> <br />
0.45622019920423756:<spells <br />
0.38503414331623603:<charm <br />
0.3744579769148505:<retaliate <br />
0.3365386087137521:<stunning <br />
0.31299212123460146:<fourpoint <br />
0.3047318421865308:<defensive <br />
0.3018663449722407:<jinx <br />
0.2986278064898596:<practicing <br />
0.29811271395978733:<hit <br /></p>
<p>(64 dimensions : 1 epoch)<br />
<b>1.0:<chamber</b> <br />
0.7516236239509654:<staffroom <br />
0.7097278407351896:<basilisk <br />
0.6396829682468098:<secrets <br />
0.6303229904669257:<messages <br />
0.6292212718692173:<pages <br />
0.6255458905896577:<gargoyle <br />
0.623691053534629:<stage <br />
0.6189105698380645:<sealed <br />
0.6165084868604697:<hilt <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<chamber</b> <br />
0.527350716695893:<secrets <br />
0.45803538999265264:<forsaken <br />
0.4509279299021009:<fanciful <br />
0.3937455721042796:<unseal <br />
0.3737416685904814:<roosters <br />
0.35312885285278145:<drawingroom <br />
0.3358263562408226:<unleash <br />
0.32925459347667607:<daubed <br />
0.32405200326296857:<runin <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0:<black</b> <br />
0.7090495706356712:<thick <br />
0.6825056469408932:<silver <br />
0.6687549059638025:<white <br />
0.6671827818068091:<thin <br />
0.6595272052625423:<green <br />
0.6559287359085553:<tiny <br />
0.6520876963925315:<glass <br />
0.6499197812776186:<bright <br />
0.6376775975420493:<hair <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0000000000000002:<black</b> <br />
0.4187862746289444:<ravaged <br />
0.41376806599272925:<bald <br />
0.3964342510912526:<silky <br />
0.39399279699897416:<stripes <br />
0.3782092012451359:<broadshouldered <br />
0.3779053329184092:<graying <br />
0.37579439331917774:<paleeyed <br />
0.3734468240600482:<atop <br />
0.37307859100552243:<leathery <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0:<requirement</b> <br />
0.6805251004125765:<common <br />
0.58822928078406:<detail <br />
0.5869718509295418:<gaunts <br />
0.5677933609626798:<portrait <br />
0.5612000668830176:<rest <br />
0.5611572795099765:<space <br />
0.5554348127278043:<marquee <br />
0.5519591805530948:<middle <br />
0.5455370331332081:<slightest <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>0.9999999999999998:<requirement</b> <br />
0.4016798211784335:<unknowable <br />
0.3867069097055046:<jampacked <br />
0.37050061385790234:<room <br />
0.3616482568609007:<partlife <br />
0.3557306897710399:<assaulted <br />
0.35489547684406436:<compression <br />
0.33972003944909956:<common <br />
0.32747964915808203:<upholstery <br />
0.3205128295096265:<reliving <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<voldemort</b> <br />
0.6883758949036237:<voldemorts <br />
0.6882314118148244:<bellatrix <br />
0.6687046547843726:<sirius <br />
0.6456113933094144:<dumbledores <br />
0.6378681113816113:<dumbledore <br />
0.6198750862701423:<lord <br />
0.601800677476979:<prophecy <br />
0.5979378004431092:<connection <br />
0.5976976164728673:<ariana <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<voldemort</b> <br />
0.5231034885732724:<lord <br />
0.4949022273659753:<voldemorts <br />
0.42104734145946027:<dumbledore <br />
0.40269571073980126:<kill <br />
0.39346439983965364:<inindeed <br />
0.3625195714553203:<snape <br />
0.36251702487473614:<elm <br />
0.35635136288239055:<merciful <br />
0.35450715479438577:<prostrate <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0:<snape</b> <br />
0.7867909396010355:<dumbledore <br />
0.7602249542226724:<slughorn <br />
0.6055605238284325:<bellatrix <br />
0.6030688726296658:<mcgonagall <br />
0.5929395283735124:<phineas <br />
0.5913798507548866:<umbridge <br />
0.5626612723245389:<narcissa <br />
0.5592886705523973:<horace <br />
0.5535260402939475:<dumbledores <br />
<br />
(256 dimensions : 10 epochs)<br />
<b>1.0:<snape </b><br />
0.49688884807669753:<dumbledore <br />
0.39141319194131824:<snapes <br />
0.3788874389546836:<severus <br />
0.3625195714553203:<voldemort <br />
0.3602838216909781:<malfoy <br />
0.3495411504557353:<mcgonagall <br />
0.3432543679925834:<heroworshipped <br />
0.3407031113901212:<silkily <br />
0.3385766904895776:<bbbut <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0000000000000002:<password</b> <br />
0.6759946677363984:<lady <br />
0.6260981919566827:<north <br />
0.6258023922269232:<tower <br />
0.6253624288287926:<owlery <br />
0.6189141007115594:<fat <br />
0.6020323426260975:<afterward <br />
0.5984440756682315:<waking <br />
0.5788408987574969:<cave <br />
0.5730507346420423:<heading <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>1.0:<password</b> <br />
0.47446983465719267:<fritters <br />
0.4712847308362276:<lady <br />
0.4654321201001382:<banana <br />
0.4440026686633822:<flibbertigibbet <br />
0.37558294153078775:<ladys <br />
0.3705196683435887:<abstinence <br />
0.36897045258759176:<fat <br />
0.3470203296601344:<portrait <br />
0.3172485840936194:<festive <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0:<chocolate</b> <br />
0.7724365211403441:<frog <br />
0.7337068328667901:<mug <br />
0.7211389912598347:<squeak <br />
0.7203372114689538:<mouthful <br />
0.7123522162102919:<meat <br />
0.7110375068682293:<male <br />
0.7029104114344779:<swig <br />
0.6955470835808224:<drops <br />
0.6901040539654248:<blew <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>0.9999999999999999:<chocolate </b><br />
0.5475055711590749:<frog <br />
0.5431921714687046:<frogs <br />
0.47751803650826924:<cards <br />
0.45420825957039807:<cakes <br />
0.43692834317867524:<marmalade <br />
0.4356386019624927:<tarts <br />
0.43098893267906485:<abbot <br />
0.41999201661912083:<chopped <br />
0.4170767831464866:<pasties <br /></p>
<p>(128 dimensions : 1 epoch)<br />
<b>1.0:<phoenix</b> <br />
0.6477570284902336:<wizengamot <br />
0.611456341909926:<order <br />
0.601307062292621:<recent <br />
0.5894212574676222:<warlock <br />
0.5777717037132631:<educational <br />
0.5672181094594285:<charges <br />
0.5577200810058244:<mysteries <br />
0.5560769924913356:<ministers <br />
0.5528013856762239:<quibbler <br />
<br />
(256 dimensions : 10 epochs) <br />
<b>0.9999999999999998:<phoenix</b> <br />
0.44566492530943996:<feather <br />
0.4307836965454031:<order <br />
0.41943464449038814:<maple <br />
0.34291846139813786:<fawkes <br />
0.33463728125471814:<cuttlebone <br />
0.3323033150650069:<headquarters <br />
0.33116604341560135:<brethren <br />
0.31389382936668453:<tto <br />
0.305949945529935:<cores <br /></p>
Sun, 23 Nov 2014 12:00:00 +0000
https://iamtrask.github.io/2014/11/23/harry-potter/
https://iamtrask.github.io/2014/11/23/harry-potter/Tutorial: when Numpy isn't fast enough...<p><b>Summary:</b> a demo on how to use fortran/blas libraries under the hood of your python program's vector operations to squeeze out extra speed over Numpy.</p>
<p>Yesterday, I posted a on how to use Apache Spark with GPUs from a notebook. To my joy, it reached the first page of Hacker News (while serving the Scala community!!!). Using Spark from one of the iPython notebooks has become a real passion of mine... and whereas yesterday I focused on Scala/JVM/GPU operations, today I want to offer a bit up to the scientific Python community. These discoveries are from studying a wonderful codebase by Radim Rehurek called <a href="https://github.com/piskvorky">Gensim</a>... specifically the word2vec implementation. </p>
<p>You might be wondering why I would cover CPU based speedups following GPU based... and the truth is that sometimes lighter weight optimiations are a better fit... especially when dealing with smaller batches of vectors at a time or when GPUs simply aren't available.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
<h2 class="section-heading">Part 1: iPython-Notebook Cython Magic</h2>
<p>Install <a href="http://stackoverflow.com/questions/2213551/installing-scipy-with-pip">Numpy,Scipy</a>,<a href="http://brewformulas.org/Gfortran">GFortran</a>,<a href="http://docs.cython.org/src/quickstart/install.html">Cython</a>, and <a href="http://scikit-learn.org/stable/install.html">scikit-learn</a> packages. I <i>HIGHLY</i> recommend sticking to easy_install, brew (apt-get), and pip. In my experience, macports has some real trouble with these packages. Also, of course, you need to have ipython notebook installed for these examples to work, but technically it can work for normal cython too.</p>
<p>With Cython you'll get the "Cython" magic as well. The following command should work in your notebook.</p>
<p><img class="img-responsive" src="/img/sampleCython.png" alt="" /></p>
<p>Notice that you load the cython magic using "%load_ext cythonmagic" and then compile cython using "%%cython" at the top of the cell containing cython code. You can then call your cython functions (or classes... etc) from python. It's a neat system. :) </p>
<h2 class="section-heading">Part 2: Scipy Fortran-Blas in Cython</h2>
<p>Below you'll see the core code that we need to get our superfast blas operations. After the first few imports, you'll see a "cdef extern from" import from a file called voidptr.h. This file allows us to cast a numpy array to its pointer without copying any data.... a key part of the code. The contents of that file are also below.</p>
<p><img class="img-responsive" src="/img/fasterThanNumpyCode.png" alt="" /></p>
<p><a href="https://github.com/klb3713/sentence2vec/blob/master/voidptr.h"><b> voidptr.h code on Github</b></a></p>
<p>Next, you'll also see six function types and their implementations. There is a whole suite of these funky-named fortran functions in the <a href="http://docs.scipy.org/doc/scipy-0.12.0/reference/generated/scipy.linalg.blas.html">Scipy Blas/Fortran Documentation</a> I also write a simple dot-product function leveraging the dsdot (double dot product... as opposed to float) called pubDotty.</p>
<p><img class="img-responsive" src="/img/fasterThanNumpyDemo.png" alt="" /></p>
<p>In this example, I create two numpy vectors of length 32. (one full of ones and another full of threes). I then benchmark and show how the cython/fortran version is <b>5.8x faster</b>. It should be noted that this is still passing in a python object... this efficiency gain increases when everything stays in cython for several progressive operations.</p>
<hr />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Part 1 -->
<p><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-6751104560361558" data-ad-slot="2365390629"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<hr />
Sun, 23 Nov 2014 12:00:00 +0000
https://iamtrask.github.io/2014/11/23/cython-blas-fortran/
https://iamtrask.github.io/2014/11/23/cython-blas-fortran/Tutorial: Spark-GPU Cluster Dev in a Notebook<p>Speed, Quality, Dev Time... pick two. This has been an age-old tradeoff in software development. The goal of this blog post is to create a local dev environment for ad-hoc gpu-cluster computing using Apache Spark, iPython Notebook (scala version), and the stock GPU powering your Macbook Pro's display.</p>
<blockquote>Make it work... then make it fast... then make it beautiful -- Matthew Russell</blockquote>
<p>In the spirit of my mentor, we will start by getting each part "working" individually. Fortunately, the second part (speed) sortof falls out of the first (GPU clusters are like that). Then, we'll integrate these parts into something beautiful... a scalable, ad-hoc environment.</p>
<h2 class="section-heading">Part 1: Spark-Notebook</h2>
<p>Apache Spark can be controlled by notebooks from several languages. I'm going with Scala for several reasons. First, it allows me to have access to the full Spark API (Graphx support is a dealbreaker for me). Secondly, the only GPU library that allowed me to compile for the GPU without writing C code myself is in Java (which I can call from scala). Even with these limitations, there were still several to choose from. The options were:</p>
<p>
<a href="http://zeppelin-project.org/">Zeppelin</a> -> buggy API after I imported classes <br />
<a href="https://github.com/andypetrella/spark-notebook">Spark-Notebook</a> -> headache to import dependencies <br />
<a href="https://github.com/hohonuuli/sparknotebook">Sparknotebook</a> -> Winner!!! Killer app. <br /></p>
<p>After cloning the Sparknotebook repo and following its instructions (downloading the IScala.jar...etc), with a single command I could open the notebook on top of a standalone spark cluster... easy peasy... </p>
<p>Please go like the REPO... I'd like to see it get some love....</p>
<h2 class="section-heading">Part 2: GPU on the JVM</h2>
<p>The inspiration for this came from a rather impressive library called <a href="http://www.scalanlp.org/">ScalaNLP</a>. They claimed to have a parser that could parse half a million words per minute on one machine! Given that I work in R&D at a "Big-Data NLP" firm, this peaked my interest. Scalanlp on a 100 node cluster seems.... rather disgustingly awesome.</p>
<p>ScalaNLP Leverages the java opencl library, <a href="https://code.google.com/p/javacl/">JavaCL</a>. The decision to use OpenCL, as opposed to CUDA, means that the code runs on non-NVIDIA graphics cards. All Apple's can use OpenCL. Therefore, I can prototype on my Macbook's GPU. I like that.... i like that a lot. </p>
<p>However, what I don't like is writing C code. It slows me down and isn't portable. I need my code to be both enterprise-ready and, "we don't want to buy GPUs" ready. This is where <a href="https://code.google.com/p/aparapi/">Aparapi</a> comes in. It compiles Java code down to OpenCL, and runs it in a Java Thread Pool if a GPU isn't available. Also, it's made by AMD... which means you can trust it. Those guys are total bosses. <a href="http://www.amd.com/en-us/press-releases/Pages/amd-fx-8370-2014sep02.aspx">AMD Claims New World Record</a></p>
<p>I downloaded the AparaPi Mac OS Zip... although all these are available.</p>
<p><a href="https://code.google.com/p/aparapi/downloads/detail?name=Aparapi_2012_01_23_MacOSX_zip&can=2&q=">Aparapi_2012_01_23_MacOSX_zip</a><br />
<a href="https://code.google.com/p/aparapi/downloads/detail?name=Aparapi_2013_01_23_linux_x86.zip&can=2&q=">Aparapi_2013_01_23_linux_x86.zip</a><br />
<a href="https://code.google.com/p/aparapi/downloads/detail?name=Aparapi_2013_01_23_windows_x86.zip&can=2&q=">Aparapi_2013_01_23_windows_x86.zip</a><br /></p>
<p>I unzipped the download into a folder on my machine, and it created a folder called "Aparapi_2012_01_23_MacOSX_zip". <br /><br />
<b>Executions:</b>
<blockquote>cd Aparapi_2012_01_23_MacOSX_zip/samples/squares/ <br />
sh squares.sh</blockquote>
<b>Output Sample:</b>
<blockquote>Execution mode=GPU<br />
0 0 <br />
1 1<br />
2 4<br />
3 9<br />
4 16<br />
5 25<br />
6 36<br />
7 49<br />
8 64<br />
9 81<br />
10 100
</blockquote></p>
<p> Wallah! Apparently this java code can run on my Macbook's GPU. Feel free to try a few of the other sample programs... the mandlebrot one is super cool!</p>
<h2 class="section-heading">Part 3: Integrating Spark and Aparapi in the Notebook</h2>
<p> So, everything so far has simply been a tutorial on "proper tool selection" for the task. The real challenge is in getting these tools to talk to each other. The first integration step we need to do is to import the aparapi jar into the iscala notebook. This can be done using the following command.</p>
<blockquote>mvn install:install-file -Dfile=aparapi.jar -DgroupId=com.amd.aparapi -DartifactId=aparapi -Dversion=1.0 -Dpackaging=jar</blockquote>
<p>Furthermore, my ~/.ipython/profile_scala/ipython_config.py looks like this at the bottom...</p>
<blockquote>c = get_config() <br /><br />
c.KernelManager.kernel_cmd = ["java","-Djava.library.path=/Users/.. .../Aparapi_2012_01_23_MacOSX_zip","-XX:MaxPermSize=2048m","-Xmx8g", <br /> "-jar",
"/Users/myname/.ipython/profile_scala/lib/IScala.jar","/Users/... .../Aparapi_2012_01_23_MacOSX_zip/aparapi.jar", <br />
"--profile", <br />
"{connection_file}", <br />
"--parent"]</blockquote>
<p>This gets the aparapi jar on our spark cluster classpath.</p>
<p> One more detail, when you're starting ipython notebook, start it with this command (with your aparapi zip directory path instead of mine). I'll go into this in a minute</p>
<blockquote>SPARK_DAEMON_JAVA_OPTS=-Xmx8128m SPARK_WORKER_MEMORY=-Xmx2048m SPARK_DAEMON_MEMORY=-Xmx2048m SPARK_REPL_OPTS=-XX:MaxPermSize=2048m SBT_OPTS=-Xmx8128m SPARK_JAVA_OPTS="-Djava.library.path=/Users/... ..../Aparapi_2012_01_23_MacOSX_zip -Xms512m -Xmx8128m" ipython notebook --profile scala </blockquote>
<p>When I deploy the aparapi jar locally, I can then import aparapi like so...</p>
<p><img class="img-responsive" src="/img/ipythonDep.png" alt="" /></p>
<p><span class="caption text-muted"> GPU, iPython Notebooks, and Apache Spark meeting for the very first time ever…. a moment in history.</span></p>
<p> Assuming no errors in the "upload" command (scroll to the bottom for a list of any import failures), you should be good to go. Also, notice that I'm using the demo scala notebook from the sparknotebook github. I recommend this to make sure that the notebook is working before you start.</p>
<h2 class="section-heading">Part 4: Example Kernel Built in the Notebook (using Scala only)</h2>
<p><img class="img-responsive" src="/img/exampleKernel.png" alt="" /></p>
<p><span class="caption text-muted">Building a kernel and running it… notice the output at the bottom…</span></p>
<p> Notice that i tried to set the kernel to run on the GPU, but because the GPU wasn't available, it switched the version and ran it on the CPU. You might be thinking, "Wait!!! This blog is a hoax!!!". I got a bit discouraged at this point as well, however, debugging later found out that we cannot compile Scala to GPU code. This is acceptable for prototyping kernels and chaining them together. This will even run in the spark context... so to develop and test your kenels (using the Java Thread Pool fallback), feel free to do it this way. </p>
<h2 class="section-heading">Part 5: Executing GPU Kernel on Spark Cluster</h2>
<p>Now the moment we've all been waiting for.... earlier when you installed the aparapi jar into maven, you were actually installing the compiled jar including the "Square" sample code. If we crack open the "squares.sh" script we ran earlier, we'll see that it is calling a program in that jar</p>
<p><b>squares.sh</b></p>
<blockquote>java \ <br />
-Djava.library.path=../.. \ <br />
-Dcom.amd.aparapi.executionMode=%1 \ <br />
-classpath ../../aparapi.jar:squares.jar \ <br />
com.amd.aparapi.sample.squares.Main</blockquote>
<p>This means that the compiled code is already on our classpath... and we can call it from a spark method like so...</p>
<p><img class="img-responsive" src="/img/gpuInSpark.png" alt="" /></p>
<p><span class="caption text-muted">Running the kernel in the ipython notebook via spark</span></p>
<p><img class="img-responsive" src="/img/gpuOutputInTerminal.png" alt="" /></p>
<p><span class="caption text-muted">The logging of the GPU program… showing that it is indeed being run on the GPU (didn’t fallback to JTP)</span></p>
Sat, 22 Nov 2014 12:00:00 +0000
https://iamtrask.github.io/2014/11/22/spark-gpu/
https://iamtrask.github.io/2014/11/22/spark-gpu/