|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "metadata": {}, |
| 6 | + "source": [ |
| 7 | + "# Multilayer Perceptron in TensorFlow\n", |
| 8 | + "\n", |
| 9 | + "Credits: Forked from [TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples) by Aymeric Damien\n", |
| 10 | + "\n", |
| 11 | + "## Setup\n", |
| 12 | + "\n", |
| 13 | + "Refer to the [setup instructions](http://nbviewer.ipython.org/github/donnemartin/data-science-ipython-notebooks/blob/master/deep-learning/tensor-flow-examples/Setup_TensorFlow.md)" |
| 14 | + ] |
| 15 | + }, |
| 16 | + { |
| 17 | + "cell_type": "code", |
| 18 | + "execution_count": 2, |
| 19 | + "metadata": { |
| 20 | + "collapsed": false |
| 21 | + }, |
| 22 | + "outputs": [ |
| 23 | + { |
| 24 | + "name": "stdout", |
| 25 | + "output_type": "stream", |
| 26 | + "text": [ |
| 27 | + "Extracting /tmp/data/train-images-idx3-ubyte.gz\n", |
| 28 | + "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n", |
| 29 | + "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n", |
| 30 | + "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n" |
| 31 | + ] |
| 32 | + } |
| 33 | + ], |
| 34 | + "source": [ |
| 35 | + "# Import MINST data\n", |
| 36 | + "import input_data\n", |
| 37 | + "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)" |
| 38 | + ] |
| 39 | + }, |
| 40 | + { |
| 41 | + "cell_type": "code", |
| 42 | + "execution_count": 3, |
| 43 | + "metadata": { |
| 44 | + "collapsed": true |
| 45 | + }, |
| 46 | + "outputs": [], |
| 47 | + "source": [ |
| 48 | + "import tensorflow as tf" |
| 49 | + ] |
| 50 | + }, |
| 51 | + { |
| 52 | + "cell_type": "code", |
| 53 | + "execution_count": 4, |
| 54 | + "metadata": { |
| 55 | + "collapsed": true |
| 56 | + }, |
| 57 | + "outputs": [], |
| 58 | + "source": [ |
| 59 | + "# Parameters\n", |
| 60 | + "learning_rate = 0.001\n", |
| 61 | + "training_epochs = 15\n", |
| 62 | + "batch_size = 100\n", |
| 63 | + "display_step = 1" |
| 64 | + ] |
| 65 | + }, |
| 66 | + { |
| 67 | + "cell_type": "code", |
| 68 | + "execution_count": 5, |
| 69 | + "metadata": { |
| 70 | + "collapsed": true |
| 71 | + }, |
| 72 | + "outputs": [], |
| 73 | + "source": [ |
| 74 | + "# Network Parameters\n", |
| 75 | + "n_hidden_1 = 256 # 1st layer num features\n", |
| 76 | + "n_hidden_2 = 256 # 2nd layer num features\n", |
| 77 | + "n_input = 784 # MNIST data input (img shape: 28*28)\n", |
| 78 | + "n_classes = 10 # MNIST total classes (0-9 digits)" |
| 79 | + ] |
| 80 | + }, |
| 81 | + { |
| 82 | + "cell_type": "code", |
| 83 | + "execution_count": 6, |
| 84 | + "metadata": { |
| 85 | + "collapsed": true |
| 86 | + }, |
| 87 | + "outputs": [], |
| 88 | + "source": [ |
| 89 | + "# tf Graph input\n", |
| 90 | + "x = tf.placeholder(\"float\", [None, n_input])\n", |
| 91 | + "y = tf.placeholder(\"float\", [None, n_classes])" |
| 92 | + ] |
| 93 | + }, |
| 94 | + { |
| 95 | + "cell_type": "code", |
| 96 | + "execution_count": 7, |
| 97 | + "metadata": { |
| 98 | + "collapsed": true |
| 99 | + }, |
| 100 | + "outputs": [], |
| 101 | + "source": [ |
| 102 | + "# Create model\n", |
| 103 | + "def multilayer_perceptron(_X, _weights, _biases):\n", |
| 104 | + " #Hidden layer with RELU activation\n", |
| 105 | + " layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) \n", |
| 106 | + " #Hidden layer with RELU activation\n", |
| 107 | + " layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) \n", |
| 108 | + " return tf.matmul(layer_2, weights['out']) + biases['out']" |
| 109 | + ] |
| 110 | + }, |
| 111 | + { |
| 112 | + "cell_type": "code", |
| 113 | + "execution_count": 8, |
| 114 | + "metadata": { |
| 115 | + "collapsed": true |
| 116 | + }, |
| 117 | + "outputs": [], |
| 118 | + "source": [ |
| 119 | + "# Store layers weight & bias\n", |
| 120 | + "weights = {\n", |
| 121 | + " 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n", |
| 122 | + " 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n", |
| 123 | + " 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n", |
| 124 | + "}\n", |
| 125 | + "biases = {\n", |
| 126 | + " 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n", |
| 127 | + " 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n", |
| 128 | + " 'out': tf.Variable(tf.random_normal([n_classes]))\n", |
| 129 | + "}" |
| 130 | + ] |
| 131 | + }, |
| 132 | + { |
| 133 | + "cell_type": "code", |
| 134 | + "execution_count": 9, |
| 135 | + "metadata": { |
| 136 | + "collapsed": true |
| 137 | + }, |
| 138 | + "outputs": [], |
| 139 | + "source": [ |
| 140 | + "# Construct model\n", |
| 141 | + "pred = multilayer_perceptron(x, weights, biases)" |
| 142 | + ] |
| 143 | + }, |
| 144 | + { |
| 145 | + "cell_type": "code", |
| 146 | + "execution_count": 10, |
| 147 | + "metadata": { |
| 148 | + "collapsed": true |
| 149 | + }, |
| 150 | + "outputs": [], |
| 151 | + "source": [ |
| 152 | + "# Define loss and optimizer\n", |
| 153 | + "# Softmax loss\n", |
| 154 | + "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) \n", |
| 155 | + "# Adam Optimizer\n", |
| 156 | + "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) " |
| 157 | + ] |
| 158 | + }, |
| 159 | + { |
| 160 | + "cell_type": "code", |
| 161 | + "execution_count": 11, |
| 162 | + "metadata": { |
| 163 | + "collapsed": true |
| 164 | + }, |
| 165 | + "outputs": [], |
| 166 | + "source": [ |
| 167 | + "# Initializing the variables\n", |
| 168 | + "init = tf.initialize_all_variables()" |
| 169 | + ] |
| 170 | + }, |
| 171 | + { |
| 172 | + "cell_type": "code", |
| 173 | + "execution_count": 12, |
| 174 | + "metadata": { |
| 175 | + "collapsed": false |
| 176 | + }, |
| 177 | + "outputs": [ |
| 178 | + { |
| 179 | + "name": "stdout", |
| 180 | + "output_type": "stream", |
| 181 | + "text": [ |
| 182 | + "Epoch: 0001 cost= 160.113980416\n", |
| 183 | + "Epoch: 0002 cost= 38.665780694\n", |
| 184 | + "Epoch: 0003 cost= 24.118004577\n", |
| 185 | + "Epoch: 0004 cost= 16.440921303\n", |
| 186 | + "Epoch: 0005 cost= 11.689460141\n", |
| 187 | + "Epoch: 0006 cost= 8.469423468\n", |
| 188 | + "Epoch: 0007 cost= 6.223237230\n", |
| 189 | + "Epoch: 0008 cost= 4.560174118\n", |
| 190 | + "Epoch: 0009 cost= 3.250516910\n", |
| 191 | + "Epoch: 0010 cost= 2.359658795\n", |
| 192 | + "Epoch: 0011 cost= 1.694081847\n", |
| 193 | + "Epoch: 0012 cost= 1.167997509\n", |
| 194 | + "Epoch: 0013 cost= 0.872986831\n", |
| 195 | + "Epoch: 0014 cost= 0.630616366\n", |
| 196 | + "Epoch: 0015 cost= 0.487381571\n", |
| 197 | + "Optimization Finished!\n", |
| 198 | + "Accuracy: 0.9462\n" |
| 199 | + ] |
| 200 | + } |
| 201 | + ], |
| 202 | + "source": [ |
| 203 | + "# Launch the graph\n", |
| 204 | + "with tf.Session() as sess:\n", |
| 205 | + " sess.run(init)\n", |
| 206 | + "\n", |
| 207 | + " # Training cycle\n", |
| 208 | + " for epoch in range(training_epochs):\n", |
| 209 | + " avg_cost = 0.\n", |
| 210 | + " total_batch = int(mnist.train.num_examples/batch_size)\n", |
| 211 | + " # Loop over all batches\n", |
| 212 | + " for i in range(total_batch):\n", |
| 213 | + " batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n", |
| 214 | + " # Fit training using batch data\n", |
| 215 | + " sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n", |
| 216 | + " # Compute average loss\n", |
| 217 | + " avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n", |
| 218 | + " # Display logs per epoch step\n", |
| 219 | + " if epoch % display_step == 0:\n", |
| 220 | + " print \"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost)\n", |
| 221 | + "\n", |
| 222 | + " print \"Optimization Finished!\"\n", |
| 223 | + "\n", |
| 224 | + " # Test model\n", |
| 225 | + " correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n", |
| 226 | + " # Calculate accuracy\n", |
| 227 | + " accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n", |
| 228 | + " print \"Accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})" |
| 229 | + ] |
| 230 | + } |
| 231 | + ], |
| 232 | + "metadata": { |
| 233 | + "kernelspec": { |
| 234 | + "display_name": "Python 3", |
| 235 | + "language": "python", |
| 236 | + "name": "python3" |
| 237 | + }, |
| 238 | + "language_info": { |
| 239 | + "codemirror_mode": { |
| 240 | + "name": "ipython", |
| 241 | + "version": 3 |
| 242 | + }, |
| 243 | + "file_extension": ".py", |
| 244 | + "mimetype": "text/x-python", |
| 245 | + "name": "python", |
| 246 | + "nbconvert_exporter": "python", |
| 247 | + "pygments_lexer": "ipython3", |
| 248 | + "version": "3.4.3" |
| 249 | + } |
| 250 | + }, |
| 251 | + "nbformat": 4, |
| 252 | + "nbformat_minor": 0 |
| 253 | +} |
0 commit comments