{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Multilayer Perceptron in TensorFlow\n", "\n", "Credits: Forked from [TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples) by Aymeric Damien\n", "\n", "## Setup\n", "\n", "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)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting /tmp/data/train-images-idx3-ubyte.gz\n", "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n", "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n", "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n" ] } ], "source": [ "# Import MINST data\n", "import input_data\n", "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import tensorflow as tf" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Parameters\n", "learning_rate = 0.001\n", "training_epochs = 15\n", "batch_size = 100\n", "display_step = 1" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Network Parameters\n", "n_hidden_1 = 256 # 1st layer num features\n", "n_hidden_2 = 256 # 2nd layer num features\n", "n_input = 784 # MNIST data input (img shape: 28*28)\n", "n_classes = 10 # MNIST total classes (0-9 digits)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# tf Graph input\n", "x = tf.placeholder(\"float\", [None, n_input])\n", "y = tf.placeholder(\"float\", [None, n_classes])" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Create model\n", "def multilayer_perceptron(_X, _weights, _biases):\n", " #Hidden layer with RELU activation\n", " layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) \n", " #Hidden layer with RELU activation\n", " layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) \n", " return tf.matmul(layer_2, weights['out']) + biases['out']" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Store layers weight & bias\n", "weights = {\n", " 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n", " 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n", " 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n", "}\n", "biases = {\n", " 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n", " 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n", " 'out': tf.Variable(tf.random_normal([n_classes]))\n", "}" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Construct model\n", "pred = multilayer_perceptron(x, weights, biases)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Define loss and optimizer\n", "# Softmax loss\n", "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) \n", "# Adam Optimizer\n", "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) " ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Initializing the variables\n", "init = tf.global_variables_initializer()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch: 0001 cost= 160.113980416\n", "Epoch: 0002 cost= 38.665780694\n", "Epoch: 0003 cost= 24.118004577\n", "Epoch: 0004 cost= 16.440921303\n", "Epoch: 0005 cost= 11.689460141\n", "Epoch: 0006 cost= 8.469423468\n", "Epoch: 0007 cost= 6.223237230\n", "Epoch: 0008 cost= 4.560174118\n", "Epoch: 0009 cost= 3.250516910\n", "Epoch: 0010 cost= 2.359658795\n", "Epoch: 0011 cost= 1.694081847\n", "Epoch: 0012 cost= 1.167997509\n", "Epoch: 0013 cost= 0.872986831\n", "Epoch: 0014 cost= 0.630616366\n", "Epoch: 0015 cost= 0.487381571\n", "Optimization Finished!\n", "Accuracy: 0.9462\n" ] } ], "source": [ "# Launch the graph\n", "with tf.Session() as sess:\n", " sess.run(init)\n", "\n", " # Training cycle\n", " for epoch in range(training_epochs):\n", " avg_cost = 0.\n", " total_batch = int(mnist.train.num_examples/batch_size)\n", " # Loop over all batches\n", " for i in range(total_batch):\n", " batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n", " # Fit training using batch data\n", " sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n", " # Compute average loss\n", " avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n", " # Display logs per epoch step\n", " if epoch % display_step == 0:\n", " print \"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost)\n", "\n", " print \"Optimization Finished!\"\n", "\n", " # Test model\n", " correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n", " # Calculate accuracy\n", " accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n", " print \"Accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "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": 0 }