Logistic Regression in TensorFlow

Credits: Forked from TensorFlow-Examples by Aymeric Damien

Setup

Refer to the setup instructions


In [5]:
# Import MINST data
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)


Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz

In [6]:
import tensorflow as tf

In [7]:
# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

In [8]:
# tf Graph Input
x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes

In [9]:
# Create model

# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

In [10]:
# Construct model
activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax

In [11]:
# Minimize error using cross entropy
# Cross entropy
cost = -tf.reduce_sum(y*tf.log(activation)) 
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

In [12]:
# Initializing the variables
init = tf.initialize_all_variables()

In [13]:
# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            # Fit training using batch data
            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
            # Compute average loss
            avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)

    print "Optimization Finished!"

    # Test model
    correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})


Epoch: 0001 cost= 29.860479714
Epoch: 0002 cost= 22.080549484
Epoch: 0003 cost= 21.237104595
Epoch: 0004 cost= 20.460196280
Epoch: 0005 cost= 20.185128237
Epoch: 0006 cost= 19.940297202
Epoch: 0007 cost= 19.645111119
Epoch: 0008 cost= 19.507218031
Epoch: 0009 cost= 19.389794492
Epoch: 0010 cost= 19.177005816
Epoch: 0011 cost= 19.082493615
Epoch: 0012 cost= 19.072873598
Epoch: 0013 cost= 18.938005402
Epoch: 0014 cost= 18.891806430
Epoch: 0015 cost= 18.839480221
Epoch: 0016 cost= 18.769349510
Epoch: 0017 cost= 18.590865587
Epoch: 0018 cost= 18.623413677
Epoch: 0019 cost= 18.546149085
Epoch: 0020 cost= 18.432274895
Epoch: 0021 cost= 18.358189004
Epoch: 0022 cost= 18.380014628
Epoch: 0023 cost= 18.499993471
Epoch: 0024 cost= 18.386477311
Epoch: 0025 cost= 18.258080609
Optimization Finished!
Accuracy: 0.9048