📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Solution for simple logistic regression model for MNIST1with placeholder2MNIST dataset: yann.lecun.com/exdb/mnist/3Created by Chip Huyen ([email protected])4CS20: "TensorFlow for Deep Learning Research"5cs20.stanford.edu6Lecture 037"""8import os9os.environ['TF_CPP_MIN_LOG_LEVEL']='2'1011import numpy as np12import tensorflow as tf13from tensorflow.examples.tutorials.mnist import input_data14import time1516import utils1718# Define paramaters for the model19learning_rate = 0.0120batch_size = 12821n_epochs = 302223# Step 1: Read in data24# using TF Learn's built in function to load MNIST data to the folder data/mnist25mnist = input_data.read_data_sets('data/mnist', one_hot=True)26X_batch, Y_batch = mnist.train.next_batch(batch_size)2728# Step 2: create placeholders for features and labels29# each image in the MNIST data is of shape 28*28 = 78430# therefore, each image is represented with a 1x784 tensor31# there are 10 classes for each image, corresponding to digits 0 - 9.32# each lable is one hot vector.33X = tf.placeholder(tf.float32, [batch_size, 784], name='image')34Y = tf.placeholder(tf.int32, [batch_size, 10], name='label')3536# Step 3: create weights and bias37# w is initialized to random variables with mean of 0, stddev of 0.0138# b is initialized to 039# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)40# shape of b depends on Y41w = tf.get_variable(name='weights', shape=(784, 10), initializer=tf.random_normal_initializer())42b = tf.get_variable(name='bias', shape=(1, 10), initializer=tf.zeros_initializer())4344# Step 4: build model45# the model that returns the logits.46# this logits will be later passed through softmax layer47logits = tf.matmul(X, w) + b4849# Step 5: define loss function50# use cross entropy of softmax of logits as the loss function51entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y, name='loss')52loss = tf.reduce_mean(entropy) # computes the mean over all the examples in the batch53# loss = tf.reduce_mean(-tf.reduce_sum(tf.nn.softmax(logits) * tf.log(Y), reduction_indices=[1]))5455# Step 6: define training op56# using gradient descent with learning rate of 0.01 to minimize loss57optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)5859# Step 7: calculate accuracy with test set60preds = tf.nn.softmax(logits)61correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))62accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))6364writer = tf.summary.FileWriter('./graphs/logreg_placeholder', tf.get_default_graph())65with tf.Session() as sess:66start_time = time.time()67sess.run(tf.global_variables_initializer())68n_batches = int(mnist.train.num_examples/batch_size)6970# train the model n_epochs times71for i in range(n_epochs):72total_loss = 07374for j in range(n_batches):75X_batch, Y_batch = mnist.train.next_batch(batch_size)76_, loss_batch = sess.run([optimizer, loss], {X: X_batch, Y:Y_batch})77total_loss += loss_batch78print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))79print('Total time: {0} seconds'.format(time.time() - start_time))8081# test the model82n_batches = int(mnist.test.num_examples/batch_size)83total_correct_preds = 08485for i in range(n_batches):86X_batch, Y_batch = mnist.test.next_batch(batch_size)87accuracy_batch = sess.run(accuracy, {X: X_batch, Y:Y_batch})88total_correct_preds += accuracy_batch8990print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))9192writer.close()939495