Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96145
License: OTHER
1
""" Solution 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
train_data = tf.data.Dataset.from_tensor_slices(train)
32
train_data = train_data.shuffle(10000) # if you want to shuffle your data
33
train_data = train_data.batch(batch_size)
34
35
test_data = tf.data.Dataset.from_tensor_slices(test)
36
test_data = test_data.batch(batch_size)
37
38
iterator = tf.data.Iterator.from_structure(train_data.output_types,
39
train_data.output_shapes)
40
img, label = iterator.get_next()
41
42
train_init = iterator.make_initializer(train_data) # initializer for train_data
43
test_init = iterator.make_initializer(test_data) # initializer for train_data
44
45
# Step 3: create weights and bias
46
# w is initialized to random variables with mean of 0, stddev of 0.01
47
# b is initialized to 0
48
# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)
49
# shape of b depends on Y
50
w = tf.get_variable(name='weights', shape=(784, 10), initializer=tf.random_normal_initializer(0, 0.01))
51
b = tf.get_variable(name='bias', shape=(1, 10), initializer=tf.zeros_initializer())
52
53
# Step 4: build model
54
# the model that returns the logits.
55
# this logits will be later passed through softmax layer
56
logits = tf.matmul(img, w) + b
57
58
# Step 5: define loss function
59
# use cross entropy of softmax of logits as the loss function
60
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=label, name='entropy')
61
loss = tf.reduce_mean(entropy, name='loss') # computes the mean over all the examples in the batch
62
63
# Step 6: define training op
64
# using gradient descent with learning rate of 0.01 to minimize loss
65
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
66
67
# Step 7: calculate accuracy with test set
68
preds = tf.nn.softmax(logits)
69
correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1))
70
accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
71
72
writer = tf.summary.FileWriter('./graphs/logreg', tf.get_default_graph())
73
with tf.Session() as sess:
74
75
start_time = time.time()
76
sess.run(tf.global_variables_initializer())
77
78
# train the model n_epochs times
79
for i in range(n_epochs):
80
sess.run(train_init) # drawing samples from train_data
81
total_loss = 0
82
n_batches = 0
83
try:
84
while True:
85
_, l = sess.run([optimizer, loss])
86
total_loss += l
87
n_batches += 1
88
except tf.errors.OutOfRangeError:
89
pass
90
print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))
91
print('Total time: {0} seconds'.format(time.time() - start_time))
92
93
# test the model
94
sess.run(test_init) # drawing samples from test_data
95
total_correct_preds = 0
96
try:
97
while True:
98
accuracy_batch = sess.run(accuracy)
99
total_correct_preds += accuracy_batch
100
except tf.errors.OutOfRangeError:
101
pass
102
103
print('Accuracy {0}'.format(total_correct_preds/n_test))
104
writer.close()
105
106