{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Using gpu device 0: Tesla K80 (CNMeM is disabled, cuDNN 5103)\n", "/home/ubuntu/anaconda2/lib/python2.7/site-packages/theano/sandbox/cuda/__init__.py:600: UserWarning: Your cuDNN version is more recent than the one Theano officially supports. If you see any problems, try updating Theano or downgrading cuDNN to version 5.\n", " warnings.warn(warn)\n", "Using Theano backend.\n" ] } ], "source": [ "from utils import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Ok notebook, import a bunch of libraries that we're going to use to build this model\". \n", "\n", "If we look in the [utils.py file](https://github.com/theianchan/keras_linear_model/blob/master/utils.py), we can see that utils has over 50 import lines, including a bunch for different parts of Keras:\n", "\n", "```\n", "import keras\n", "from keras import backend as K\n", "from keras.utils.data_utils import get_file\n", "from keras.utils import np_utils\n", "[...]\n", "```\n", "\n", "For now, we don't need to know what they all are." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = random((30,2))\n", "y = np.dot(x, [2, 3]) + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is our data - x is our input, and y is our desired output.\n", "\n", "Notice that, like in our [spreadsheet](https://docs.google.com/spreadsheets/d/1HrX-KdsO-d0czy3Z1Ry7BIw5PHVfBaCoE17mi_TNRxE/edit?usp=sharing), x is a collection of arbitrarily selected random numbers.\n", "\n", "Unlike in our spreadsheet, where y was also just random numbers, we've actually defined a relationship between x and y, and **we're going to provide our model with the values of x and y, but not the relationship between them (y = x [2, 3] + 1) and ask it for its best guess of what that relationship could be**." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([[ 0.2006, 0.7571],\n", " [ 0.5218, 0.4857],\n", " [ 0.0908, 0.3997],\n", " [ 0.5502, 0.6391],\n", " [ 0.6486, 0.505 ]])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Ok notebook, show me the first 5 values of x.\"" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 3.6724, 3.5005, 2.3805, 4.0178, 3.8122])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y[:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Ok notebook, do the same thing but for y.\"" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "lm = Sequential([Dense(1, input_dim=2)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "lm is our linear model. It can be written as\n", "\n", "```\n", "lm = Sequential()\n", "lm.add(Dense(x, y))\n", "```\n", "\n", "or\n", "\n", "```\n", "lm = Sequential([Dense(x, input_shape=(y,)])\n", "```\n", "\n", "or \n", "\n", "```\n", "lm = Sequential([Dense(x, input_dim=y])\n", "```\n", "\n", "\"dim\" stands for \"dimensions\" by the way, because it took me a while. \n", "\n", "The docs describe Dense() as \"just your fully connected NN layer\". The model we create here will take as an input any array of shape (\\*, y), and output an array of shape (\\*, x).\n", "\n", "So all we're saying here is,\n", "\n", "**\"Ok notebook, create a linear model that takes an array with any number of rows and two columns and returns an array with the same number of rows and one column.\"**" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(30, 2)\n", "(30,)\n" ] } ], "source": [ "print(x.shape)\n", "print(y.shape)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Oh look - what a coincidence.\n", "\n", "We now have a linear model that takes the right sized inputs and produces the right sized outputs. \n", "\n", "Recall that at the end of our spreadsheet neural network implementation, we identified two things we could do to improve the output it was giving us:\n", "\n", "1. Make changes to the way we initialize our weights, making the random numbers in our matrices less random\n", "2. Build in some kind of optimization process so the network can adjust its weights in response to the difference between our activations and desired outputs\n", "\n", "I *believe* that our linear model is at the \"just throw some random numbers at the problem and see what happens\" stage of the problem, which was as far as we got yesterday, but with one major difference: **our spreadsheet neural network didn't have any kind of strategy for weight initialization, and I *believe* that Keras has weight initialization methods built in**. \n", "\n", "So that's the first step taken care of." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lm.compile(optimizer=SGD(lr=0.1), loss=\"mse\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**\"Ok model, adjust your weights and improve your guesses using stochastic gradient descent with a learning rate of 0.1. To keep track of whether your guesses are getting better or worse, use mean squared error.\"**\n", "\n", "We'll cover both stochastic gradient descent and mean squared error later on, but that's the second step taken care of." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "20.332971572875977" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.evaluate(x, y, verbose=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**\"Ok model, make your first guesses based on x, compare them against the actual values of y, and tell us how you did.\"**\n", "\n", "Is this good or bad? The Wikipedia page for mean squared error says \"values closer to zero are better\" so I'm going to take that as \"could be improved\".\n", "\n", "This shouldn't be surprising though - if you've been paying attention you'll realize that our model hasn't actually been trained." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/5\n", "30/30 [==============================] - 0s - loss: 1.8488 \n", "Epoch 2/5\n", "30/30 [==============================] - 0s - loss: 0.2749 \n", "Epoch 3/5\n", "30/30 [==============================] - 0s - loss: 0.1266 \n", "Epoch 4/5\n", "30/30 [==============================] - 0s - loss: 0.0485 \n", "Epoch 5/5\n", "30/30 [==============================] - 0s - loss: 0.0194 \n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.fit(x, y, nb_epoch=5, batch_size=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**\"Ok model, make a guess, check your guess against our desired output, and improve the weights you're using to make the guess - and do it five times.\"**\n", "\n", "Again, we'll cover the gradient descent method used to actually improve the our model weights later on, but notice the diminishing loss function after each epoch (an epoch is a complete pass through our data)." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0.011976789683103561" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.evaluate(x, y, verbose=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's a lot closer to zero!" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/5\n", "30/30 [==============================] - 0s - loss: 0.0092 \n", "Epoch 2/5\n", "30/30 [==============================] - 0s - loss: 0.0036 \n", "Epoch 3/5\n", "30/30 [==============================] - 0s - loss: 0.0018 \n", "Epoch 4/5\n", "30/30 [==============================] - 0s - loss: 9.1857e-04 \n", "Epoch 5/5\n", "30/30 [==============================] - 0s - loss: 4.3288e-04 \n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.fit(x, y, nb_epoch=5, batch_size=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**\"Ok model, do it five more times.\"**" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0.00023057886573951691" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.evaluate(x, y, verbose=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's a **lot** closer to zero." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[array([[ 2.0156],\n", " [ 2.9427]], dtype=float32), array([ 1.0263], dtype=float32)]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lm.get_weights()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**\"Ok model, what weights did you use to produce this output?\"**\n", "\n", "Remember our original function for y?\n", "\n", "```\n", "y = np.dot(x, [2, 3]) + 1\n", "```\n", "\n", "The weights used by our model turned out pretty close to 2, 3, and 1!" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [conda root]", "language": "python", "name": "conda-root-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 1 }