📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Solution for simple logistic regression model for MNIST1with tf.data module2MNIST 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 tf13import time1415import utils1617# Define paramaters for the model18learning_rate = 0.0119batch_size = 12820n_epochs = 3021n_train = 6000022n_test = 100002324# Step 1: Read in data25mnist_folder = 'data/mnist'26utils.download_mnist(mnist_folder)27train, val, test = utils.read_mnist(mnist_folder, flatten=True)2829# Step 2: Create datasets and iterator30train_data = tf.data.Dataset.from_tensor_slices(train)31train_data = train_data.shuffle(10000) # if you want to shuffle your data32train_data = train_data.batch(batch_size)3334test_data = tf.data.Dataset.from_tensor_slices(test)35test_data = test_data.batch(batch_size)3637iterator = tf.data.Iterator.from_structure(train_data.output_types,38train_data.output_shapes)39img, label = iterator.get_next()4041train_init = iterator.make_initializer(train_data) # initializer for train_data42test_init = iterator.make_initializer(test_data) # initializer for train_data4344# Step 3: create weights and bias45# w is initialized to random variables with mean of 0, stddev of 0.0146# b is initialized to 047# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)48# shape of b depends on Y49w = tf.get_variable(name='weights', shape=(784, 10), initializer=tf.random_normal_initializer(0, 0.01))50b = tf.get_variable(name='bias', shape=(1, 10), initializer=tf.zeros_initializer())5152# Step 4: build model53# the model that returns the logits.54# this logits will be later passed through softmax layer55logits = tf.matmul(img, w) + b5657# Step 5: define loss function58# use cross entropy of softmax of logits as the loss function59entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=label, name='entropy')60loss = tf.reduce_mean(entropy, name='loss') # computes the mean over all the examples in the batch6162# Step 6: define training op63# using gradient descent with learning rate of 0.01 to minimize loss64optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)6566# Step 7: calculate accuracy with test set67preds = tf.nn.softmax(logits)68correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1))69accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))7071writer = tf.summary.FileWriter('./graphs/logreg', tf.get_default_graph())72with tf.Session() as sess:7374start_time = time.time()75sess.run(tf.global_variables_initializer())7677# train the model n_epochs times78for i in range(n_epochs):79sess.run(train_init) # drawing samples from train_data80total_loss = 081n_batches = 082try:83while True:84_, l = sess.run([optimizer, loss])85total_loss += l86n_batches += 187except tf.errors.OutOfRangeError:88pass89print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))90print('Total time: {0} seconds'.format(time.time() - start_time))9192# test the model93sess.run(test_init) # drawing samples from test_data94total_correct_preds = 095try:96while True:97accuracy_batch = sess.run(accuracy)98total_correct_preds += accuracy_batch99except tf.errors.OutOfRangeError:100pass101102print('Accuracy {0}'.format(total_correct_preds/n_test))103writer.close()104105106