Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132927 views
License: OTHER
1
""" Starter code for logistic regression model to solve OCR task
2
with MNIST in TensorFlow
3
MNIST dataset: yann.lecun.com/exdb/mnist/
4
Author: Chip Huyen
5
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
6
cs20si.stanford.edu
7
"""
8
import os
9
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
10
11
import numpy as np
12
import tensorflow as tf
13
from tensorflow.examples.tutorials.mnist import input_data
14
import time
15
16
# Define paramaters for the model
17
learning_rate = 0.01
18
batch_size = 128
19
n_epochs = 10
20
21
# Step 1: Read in data
22
# using TF Learn's built in function to load MNIST data to the folder data/mnist
23
mnist = input_data.read_data_sets('/data/mnist', one_hot=True)
24
25
# Step 2: create placeholders for features and labels
26
# each image in the MNIST data is of shape 28*28 = 784
27
# therefore, each image is represented with a 1x784 tensor
28
# there are 10 classes for each image, corresponding to digits 0 - 9.
29
# Features are of the type float, and labels are of the type int
30
31
32
# Step 3: create weights and bias
33
# weights and biases are initialized to 0
34
# shape of w depends on the dimension of X and Y so that Y = X * w + b
35
# shape of b depends on Y
36
37
38
# Step 4: build model
39
# the model that returns the logits.
40
# this logits will be later passed through softmax layer
41
# to get the probability distribution of possible label of the image
42
# DO NOT DO SOFTMAX HERE
43
44
45
# Step 5: define loss function
46
# use cross entropy loss of the real labels with the softmax of logits
47
# use the method:
48
# tf.nn.softmax_cross_entropy_with_logits(logits, Y)
49
# then use tf.reduce_mean to get the mean loss of the batch
50
51
52
# Step 6: define training op
53
# using gradient descent to minimize loss
54
55
56
with tf.Session() as sess:
57
start_time = time.time()
58
sess.run(tf.global_variables_initializer())
59
n_batches = int(mnist.train.num_examples/batch_size)
60
for i in range(n_epochs): # train the model n_epochs times
61
total_loss = 0
62
63
for _ in range(n_batches):
64
X_batch, Y_batch = mnist.train.next_batch(batch_size)
65
# TO-DO: run optimizer + fetch loss_batch
66
#
67
#
68
total_loss += loss_batch
69
print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))
70
71
print('Total time: {0} seconds'.format(time.time() - start_time))
72
73
print('Optimization Finished!') # should be around 0.35 after 25 epochs
74
75
# test the model
76
preds = tf.nn.softmax(logits)
77
correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))
78
accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32)) # need numpy.count_nonzero(boolarr) :(
79
80
n_batches = int(mnist.test.num_examples/batch_size)
81
total_correct_preds = 0
82
83
for i in range(n_batches):
84
X_batch, Y_batch = mnist.test.next_batch(batch_size)
85
accuracy_batch = sess.run([accuracy], feed_dict={X: X_batch, Y:Y_batch})
86
total_correct_preds += accuracy_batch
87
88
print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))
89
90