{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Logistic Regression in TensorFlow\n", "\n", "### Updated for Python 3.6+\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": 1, "metadata": {}, "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 tensorflow as tf\n", "from tensorflow.examples.tutorials.mnist import input_data\n", "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Parameters\n", "learning_rate = 0.01\n", "training_epochs = 25\n", "batch_size = 100\n", "display_step = 1" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# tf Graph Input\n", "x = tf.placeholder(\"float\", [None, 784]) # mnist data image of shape 28*28=784\n", "y = tf.placeholder(\"float\", [None, 10]) # 0-9 digits recognition => 10 classes" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Create model\n", "\n", "# Set model weights\n", "W = tf.Variable(tf.zeros([784, 10]))\n", "b = tf.Variable(tf.zeros([10]))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Construct model\n", "activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Minimize error using cross entropy\n", "# Cross entropy\n", "cost = -tf.reduce_sum(y*tf.log(activation)) \n", "# Gradient Descent\n", "optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# Initializing the variables\n", "init = tf.global_variables_initializer()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch: 0001 cost= 30.201449143\n", "Epoch: 0002 cost= 22.036444135\n", "Epoch: 0003 cost= 21.054862718\n", "Epoch: 0004 cost= 20.597353284\n", "Epoch: 0005 cost= 20.190342429\n", "Epoch: 0006 cost= 19.786361580\n", "Epoch: 0007 cost= 19.593195786\n", "Epoch: 0008 cost= 19.423822853\n", "Epoch: 0009 cost= 19.390960660\n", "Epoch: 0010 cost= 19.237225328\n", "Epoch: 0011 cost= 19.129154354\n", "Epoch: 0012 cost= 19.068082945\n", "Epoch: 0013 cost= 18.961399286\n", "Epoch: 0014 cost= 18.836373898\n", "Epoch: 0015 cost= 18.799891092\n", "Epoch: 0016 cost= 18.727478255\n", "Epoch: 0017 cost= 18.591258308\n", "Epoch: 0018 cost= 18.676952642\n", "Epoch: 0019 cost= 18.548722290\n", "Epoch: 0020 cost= 18.484304102\n", "Epoch: 0021 cost= 18.437379690\n", "Epoch: 0022 cost= 18.387524192\n", "Epoch: 0023 cost= 18.353106305\n", "Epoch: 0024 cost= 18.252915604\n", "Epoch: 0025 cost= 18.257536320\n", "Optimization Finished!\n", "Accuracy: 0.9233\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(activation, 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}))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 1 }