📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Starter code 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 iterator30# create training Dataset and batch it31train_data = tf.data.Dataset.from_tensor_slices(train)32train_data = train_data.shuffle(10000) # if you want to shuffle your data33train_data = train_data.batch(batch_size)3435# create testing Dataset and batch it36test_data = None37#############################38########## TO DO ############39#############################404142# create one iterator and initialize it with different datasets43iterator = tf.data.Iterator.from_structure(train_data.output_types,44train_data.output_shapes)45img, label = iterator.get_next()4647train_init = iterator.make_initializer(train_data) # initializer for train_data48test_init = iterator.make_initializer(test_data) # initializer for train_data4950# Step 3: create weights and bias51# w is initialized to random variables with mean of 0, stddev of 0.0152# b is initialized to 053# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)54# shape of b depends on Y55w, b = None, None56#############################57########## TO DO ############58#############################596061# Step 4: build model62# the model that returns the logits.63# this logits will be later passed through softmax layer64logits = None65#############################66########## TO DO ############67#############################686970# Step 5: define loss function71# use cross entropy of softmax of logits as the loss function72loss = None73#############################74########## TO DO ############75#############################767778# Step 6: define optimizer79# using Adamn Optimizer with pre-defined learning rate to minimize loss80optimizer = None81#############################82########## TO DO ############83#############################848586# Step 7: calculate accuracy with test set87preds = tf.nn.softmax(logits)88correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1))89accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))9091writer = tf.summary.FileWriter('./graphs/logreg', tf.get_default_graph())92with tf.Session() as sess:9394start_time = time.time()95sess.run(tf.global_variables_initializer())9697# train the model n_epochs times98for i in range(n_epochs):99sess.run(train_init) # drawing samples from train_data100total_loss = 0101n_batches = 0102try:103while True:104_, l = sess.run([optimizer, loss])105total_loss += l106n_batches += 1107except tf.errors.OutOfRangeError:108pass109print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))110print('Total time: {0} seconds'.format(time.time() - start_time))111112# test the model113sess.run(test_init) # drawing samples from test_data114total_correct_preds = 0115try:116while True:117accuracy_batch = sess.run(accuracy)118total_correct_preds += accuracy_batch119except tf.errors.OutOfRangeError:120pass121122print('Accuracy {0}'.format(total_correct_preds/n_test))123writer.close()124125