Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96144
License: OTHER
1
""" Starter code for simple logistic regression model for MNIST
2
with tf.data module
3
MNIST dataset: yann.lecun.com/exdb/mnist/
4
Created by Chip Huyen ([email protected])
5
CS20: "TensorFlow for Deep Learning Research"
6
cs20.stanford.edu
7
Lecture 03
8
"""
9
import os
10
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
11
12
import numpy as np
13
import tensorflow as tf
14
import time
15
16
import utils
17
18
# Define paramaters for the model
19
learning_rate = 0.01
20
batch_size = 128
21
n_epochs = 30
22
n_train = 60000
23
n_test = 10000
24
25
# Step 1: Read in data
26
mnist_folder = 'data/mnist'
27
utils.download_mnist(mnist_folder)
28
train, val, test = utils.read_mnist(mnist_folder, flatten=True)
29
30
# Step 2: Create datasets and iterator
31
# create training Dataset and batch it
32
train_data = tf.data.Dataset.from_tensor_slices(train)
33
train_data = train_data.shuffle(10000) # if you want to shuffle your data
34
train_data = train_data.batch(batch_size)
35
36
# create testing Dataset and batch it
37
test_data = None
38
#############################
39
########## TO DO ############
40
#############################
41
42
43
# create one iterator and initialize it with different datasets
44
iterator = tf.data.Iterator.from_structure(train_data.output_types,
45
train_data.output_shapes)
46
img, label = iterator.get_next()
47
48
train_init = iterator.make_initializer(train_data) # initializer for train_data
49
test_init = iterator.make_initializer(test_data) # initializer for train_data
50
51
# Step 3: create weights and bias
52
# w is initialized to random variables with mean of 0, stddev of 0.01
53
# b is initialized to 0
54
# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)
55
# shape of b depends on Y
56
w, b = None, None
57
#############################
58
########## TO DO ############
59
#############################
60
61
62
# Step 4: build model
63
# the model that returns the logits.
64
# this logits will be later passed through softmax layer
65
logits = None
66
#############################
67
########## TO DO ############
68
#############################
69
70
71
# Step 5: define loss function
72
# use cross entropy of softmax of logits as the loss function
73
loss = None
74
#############################
75
########## TO DO ############
76
#############################
77
78
79
# Step 6: define optimizer
80
# using Adamn Optimizer with pre-defined learning rate to minimize loss
81
optimizer = None
82
#############################
83
########## TO DO ############
84
#############################
85
86
87
# Step 7: calculate accuracy with test set
88
preds = tf.nn.softmax(logits)
89
correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1))
90
accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
91
92
writer = tf.summary.FileWriter('./graphs/logreg', tf.get_default_graph())
93
with tf.Session() as sess:
94
95
start_time = time.time()
96
sess.run(tf.global_variables_initializer())
97
98
# train the model n_epochs times
99
for i in range(n_epochs):
100
sess.run(train_init) # drawing samples from train_data
101
total_loss = 0
102
n_batches = 0
103
try:
104
while True:
105
_, l = sess.run([optimizer, loss])
106
total_loss += l
107
n_batches += 1
108
except tf.errors.OutOfRangeError:
109
pass
110
print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))
111
print('Total time: {0} seconds'.format(time.time() - start_time))
112
113
# test the model
114
sess.run(test_init) # drawing samples from test_data
115
total_correct_preds = 0
116
try:
117
while True:
118
accuracy_batch = sess.run(accuracy)
119
total_correct_preds += accuracy_batch
120
except tf.errors.OutOfRangeError:
121
pass
122
123
print('Accuracy {0}'.format(total_correct_preds/n_test))
124
writer.close()
125