{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "'''\n", "A Multilayer Perceptron implementation example using TensorFlow library.\n", "This example is using the MNIST database of handwritten digits\n", "(http://yann.lecun.com/exdb/mnist/)\n", "\n", "Author: Aymeric Damien\n", "Project: https://github.com/aymericdamien/TensorFlow-Examples/\n", "'''" ] }, { "cell_type": "code", "execution_count": 1, "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", "from tensorflow.examples.tutorials.mnist import input_data\n", "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n", "\n", "import tensorflow as tf" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Parameters\n", "learning_rate = 0.001\n", "training_epochs = 15\n", "batch_size = 100\n", "display_step = 1\n", "\n", "# Network Parameters\n", "n_hidden_1 = 256 # 1st layer number of features\n", "n_hidden_2 = 256 # 2nd layer number of features\n", "n_input = 784 # MNIST data input (img shape: 28*28)\n", "n_classes = 10 # MNIST total classes (0-9 digits)\n", "\n", "# tf Graph input\n", "x = tf.placeholder(\"float\", [None, n_input])\n", "y = tf.placeholder(\"float\", [None, n_classes])" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Create model\n", "def multilayer_perceptron(x, weights, biases):\n", " # Hidden layer with RELU activation\n", " layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n", " layer_1 = tf.nn.relu(layer_1)\n", " # Hidden layer with RELU activation\n", " layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n", " layer_2 = tf.nn.relu(layer_2)\n", " # Output layer with linear activation\n", " out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n", " return out_layer" ] }, { "cell_type": "code", "execution_count": 4, "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", "}\n", "\n", "# Construct model\n", "pred = multilayer_perceptron(x, weights, biases)\n", "\n", "# Define loss and optimizer\n", "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))\n", "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n", "\n", "# Initializing the variables\n", "init = tf.initialize_all_variables()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch: 0001 cost= 185.342230390\n", "Epoch: 0002 cost= 44.266946572\n", "Epoch: 0003 cost= 27.999560453\n", "Epoch: 0004 cost= 19.655567043\n", "Epoch: 0005 cost= 14.284429696\n", "Epoch: 0006 cost= 10.640310403\n", "Epoch: 0007 cost= 7.904047886\n", "Epoch: 0008 cost= 5.989115090\n", "Epoch: 0009 cost= 4.689374613\n", "Epoch: 0010 cost= 3.455884229\n", "Epoch: 0011 cost= 2.733002625\n", "Epoch: 0012 cost= 2.101091420\n", "Epoch: 0013 cost= 1.496508092\n", "Epoch: 0014 cost= 1.245452015\n", "Epoch: 0015 cost= 0.912072906\n", "Optimization Finished!\n", "Accuracy: 0.9422\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_x, batch_y = mnist.train.next_batch(batch_size)\n", " # Run optimization op (backprop) and cost op (to get loss value)\n", " _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,\n", " y: batch_y})\n", " # Compute average loss\n", " avg_cost += c / total_batch\n", " # Display logs per epoch step\n", " if epoch % display_step == 0:\n", " print \"Epoch:\", '%04d' % (epoch+1), \"cost=\", \\\n", " \"{:.9f}\".format(avg_cost)\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.0 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }