5
5
# Here, we will show how to implement different unit tests
6
6
# on the MNIST example
7
7
8
+ import sys
8
9
import numpy as np
9
10
import tensorflow as tf
10
- from tensorflow .contrib .learn .python .learn .datasets .mnist import read_data_sets
11
11
from tensorflow .python .framework import ops
12
12
ops .reset_default_graph ()
13
13
16
16
17
17
# Load data
18
18
data_dir = 'temp'
19
- mnist = read_data_sets (data_dir )
20
-
21
- # Convert images into 28x28 (they are downloaded as 1x784)
22
- train_xdata = np .array ([np .reshape (x , (28 ,28 )) for x in mnist .train .images ])
23
- test_xdata = np .array ([np .reshape (x , (28 ,28 )) for x in mnist .test .images ])
24
-
25
- # Convert labels into one-hot encoded vectors
26
- train_labels = mnist .train .labels
27
- test_labels = mnist .test .labels
19
+ mnist = tf .keras .datasets .mnist
20
+ (train_xdata , train_labels ), (test_xdata , test_labels ) = mnist .load_data ()
21
+ train_xdata = train_xdata / 255.0
22
+ test_xdata = test_xdata / 255.0
28
23
29
24
# Set model parameters
30
25
batch_size = 100
67
62
resulting_width = image_width // (max_pool_size1 * max_pool_size2 )
68
63
resulting_height = image_height // (max_pool_size1 * max_pool_size2 )
69
64
full1_input_size = resulting_width * resulting_height * conv2_features
70
- full1_weight = tf .Variable (tf .truncated_normal ([full1_input_size , fully_connected_size1 ],
71
- stddev = 0.1 , dtype = tf .float32 ))
65
+ full1_weight = tf .Variable (tf .truncated_normal ([full1_input_size , fully_connected_size1 ], stddev = 0.1 , dtype = tf .float32 ))
72
66
full1_bias = tf .Variable (tf .truncated_normal ([fully_connected_size1 ], stddev = 0.1 , dtype = tf .float32 ))
73
67
full2_weight = tf .Variable (tf .truncated_normal ([fully_connected_size1 , target_size ],
74
68
stddev = 0.1 , dtype = tf .float32 ))
@@ -103,7 +97,8 @@ def my_conv_net(input_data):
103
97
# Add dropout
104
98
final_model_output = tf .nn .dropout (final_model_output , dropout )
105
99
106
- return (final_model_output )
100
+ return final_model_output
101
+
107
102
108
103
model_output = my_conv_net (x_input )
109
104
test_model_output = my_conv_net (eval_input )
@@ -115,11 +110,13 @@ def my_conv_net(input_data):
115
110
prediction = tf .nn .softmax (model_output )
116
111
test_prediction = tf .nn .softmax (test_model_output )
117
112
113
+
118
114
# Create accuracy function
119
115
def get_accuracy (logits , targets ):
120
116
batch_predictions = np .argmax (logits , axis = 1 )
121
117
num_correct = np .sum (np .equal (batch_predictions , targets ))
122
- return (100. * num_correct / batch_predictions .shape [0 ])
118
+ return 100. * num_correct / batch_predictions .shape [0 ]
119
+
123
120
124
121
# Create an optimizer
125
122
my_optimizer = tf .train .MomentumOptimizer (learning_rate , 0.9 )
@@ -129,23 +126,26 @@ def get_accuracy(logits, targets):
129
126
init = tf .global_variables_initializer ()
130
127
sess .run (init )
131
128
129
+
132
130
# Check values of tensors!
133
131
class drop_out_test (tf .test .TestCase ):
134
132
# Make sure that we don't drop too much
135
133
def dropout_greaterthan (self ):
136
134
with self .test_session ():
137
- self .assertGreater (dropout .eval (), 0.25 )
135
+ self .assertGreater (dropout .eval (), 0.25 )
136
+
138
137
139
138
# Test accuracy function
140
139
class accuracy_test (tf .test .TestCase ):
141
140
# Make sure accuracy function behaves correctly
142
141
def accuracy_exact_test (self ):
143
142
with self .test_session ():
144
- test_preds = [[0.9 , 0.1 ],[0.01 , 0.99 ]]
143
+ test_preds = [[0.9 , 0.1 ], [0.01 , 0.99 ]]
145
144
test_targets = [0 , 1 ]
146
145
test_acc = get_accuracy (test_preds , test_targets )
147
146
self .assertEqual (test_acc .eval (), 100. )
148
147
148
+
149
149
# Test tensorshape
150
150
class shape_test (tf .test .TestCase ):
151
151
# Make sure our model output is size [batch_size, num_classes]
@@ -154,37 +154,46 @@ def output_shape_test(self):
154
154
numpy_array = np .ones ([batch_size , target_size ])
155
155
self .assertShapeEqual (numpy_array , model_output )
156
156
157
- # Perform unit tests
158
- tf .test .main ()
159
-
160
- # Start training loop
161
- train_loss = []
162
- train_acc = []
163
- test_acc = []
164
- for i in range (generations ):
165
- rand_index = np .random .choice (len (train_xdata ), size = batch_size )
166
- rand_x = train_xdata [rand_index ]
167
- rand_x = np .expand_dims (rand_x , 3 )
168
- rand_y = train_labels [rand_index ]
169
- train_dict = {x_input : rand_x , y_target : rand_y , dropout : dropout_prob }
170
-
171
- sess .run (train_step , feed_dict = train_dict )
172
- temp_train_loss , temp_train_preds = sess .run ([loss , prediction ], feed_dict = train_dict )
173
- temp_train_acc = get_accuracy (temp_train_preds , rand_y )
174
-
175
- if (i + 1 ) % eval_every == 0 :
176
- eval_index = np .random .choice (len (test_xdata ), size = evaluation_size )
177
- eval_x = test_xdata [eval_index ]
178
- eval_x = np .expand_dims (eval_x , 3 )
179
- eval_y = test_labels [eval_index ]
180
- test_dict = {eval_input : eval_x , eval_target : eval_y , dropout : 1.0 }
181
- test_preds = sess .run (test_prediction , feed_dict = test_dict )
182
- temp_test_acc = get_accuracy (test_preds , eval_y )
183
-
184
- # Record and print results
185
- train_loss .append (temp_train_loss )
186
- train_acc .append (temp_train_acc )
187
- test_acc .append (temp_test_acc )
188
- acc_and_loss = [(i + 1 ), temp_train_loss , temp_train_acc , temp_test_acc ]
189
- acc_and_loss = [np .round (x ,2 ) for x in acc_and_loss ]
190
- print ('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})' .format (* acc_and_loss ))
157
+
158
+ def main (argv ):
159
+ # Start training loop
160
+ train_loss = []
161
+ train_acc = []
162
+ test_acc = []
163
+ for i in range (generations ):
164
+ rand_index = np .random .choice (len (train_xdata ), size = batch_size )
165
+ rand_x = train_xdata [rand_index ]
166
+ rand_x = np .expand_dims (rand_x , 3 )
167
+ rand_y = train_labels [rand_index ]
168
+ train_dict = {x_input : rand_x , y_target : rand_y , dropout : dropout_prob }
169
+
170
+ sess .run (train_step , feed_dict = train_dict )
171
+ temp_train_loss , temp_train_preds = sess .run ([loss , prediction ], feed_dict = train_dict )
172
+ temp_train_acc = get_accuracy (temp_train_preds , rand_y )
173
+
174
+ if (i + 1 ) % eval_every == 0 :
175
+ eval_index = np .random .choice (len (test_xdata ), size = evaluation_size )
176
+ eval_x = test_xdata [eval_index ]
177
+ eval_x = np .expand_dims (eval_x , 3 )
178
+ eval_y = test_labels [eval_index ]
179
+ test_dict = {eval_input : eval_x , eval_target : eval_y , dropout : 1.0 }
180
+ test_preds = sess .run (test_prediction , feed_dict = test_dict )
181
+ temp_test_acc = get_accuracy (test_preds , eval_y )
182
+
183
+ # Record and print results
184
+ train_loss .append (temp_train_loss )
185
+ train_acc .append (temp_train_acc )
186
+ test_acc .append (temp_test_acc )
187
+ acc_and_loss = [(i + 1 ), temp_train_loss , temp_train_acc , temp_test_acc ]
188
+ acc_and_loss = [np .round (x , 2 ) for x in acc_and_loss ]
189
+ print ('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})' .format (* acc_and_loss ))
190
+
191
+
192
+ if __name__ == '__main__' :
193
+ cmd_args = sys .argv
194
+ if len (cmd_args ) > 1 and cmd_args [1 ] == 'test' :
195
+ # Perform unit tests
196
+ tf .test .main (argv = cmd_args [1 :])
197
+ else :
198
+ # Run TF App
199
+ tf .app .run (main = None , argv = cmd_args )
0 commit comments