Skip to content

Commit 8ebfa0b

Browse files
committed
updated ch 10 and add code-of-conduct
1 parent b77d8ae commit 8ebfa0b

File tree

10 files changed

+535
-97
lines changed

10 files changed

+535
-97
lines changed

10_Taking_TensorFlow_to_Production/01_Implementing_Unit_Tests/01_implementing_unit_tests.py

+59-50
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
# Here, we will show how to implement different unit tests
66
# on the MNIST example
77

8+
import sys
89
import numpy as np
910
import tensorflow as tf
10-
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
1111
from tensorflow.python.framework import ops
1212
ops.reset_default_graph()
1313

@@ -16,15 +16,10 @@
1616

1717
# Load data
1818
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
2823

2924
# Set model parameters
3025
batch_size = 100
@@ -67,8 +62,7 @@
6762
resulting_width = image_width // (max_pool_size1 * max_pool_size2)
6863
resulting_height = image_height // (max_pool_size1 * max_pool_size2)
6964
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))
7266
full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))
7367
full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size1, target_size],
7468
stddev=0.1, dtype=tf.float32))
@@ -103,7 +97,8 @@ def my_conv_net(input_data):
10397
# Add dropout
10498
final_model_output = tf.nn.dropout(final_model_output, dropout)
10599

106-
return(final_model_output)
100+
return final_model_output
101+
107102

108103
model_output = my_conv_net(x_input)
109104
test_model_output = my_conv_net(eval_input)
@@ -115,11 +110,13 @@ def my_conv_net(input_data):
115110
prediction = tf.nn.softmax(model_output)
116111
test_prediction = tf.nn.softmax(test_model_output)
117112

113+
118114
# Create accuracy function
119115
def get_accuracy(logits, targets):
120116
batch_predictions = np.argmax(logits, axis=1)
121117
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+
123120

124121
# Create an optimizer
125122
my_optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9)
@@ -129,23 +126,26 @@ def get_accuracy(logits, targets):
129126
init = tf.global_variables_initializer()
130127
sess.run(init)
131128

129+
132130
# Check values of tensors!
133131
class drop_out_test(tf.test.TestCase):
134132
# Make sure that we don't drop too much
135133
def dropout_greaterthan(self):
136134
with self.test_session():
137-
self.assertGreater(dropout.eval(), 0.25)
135+
self.assertGreater(dropout.eval(), 0.25)
136+
138137

139138
# Test accuracy function
140139
class accuracy_test(tf.test.TestCase):
141140
# Make sure accuracy function behaves correctly
142141
def accuracy_exact_test(self):
143142
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]]
145144
test_targets = [0, 1]
146145
test_acc = get_accuracy(test_preds, test_targets)
147146
self.assertEqual(test_acc.eval(), 100.)
148147

148+
149149
# Test tensorshape
150150
class shape_test(tf.test.TestCase):
151151
# Make sure our model output is size [batch_size, num_classes]
@@ -154,37 +154,46 @@ def output_shape_test(self):
154154
numpy_array = np.ones([batch_size, target_size])
155155
self.assertShapeEqual(numpy_array, model_output)
156156

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)

10_Taking_TensorFlow_to_Production/02_Using_Multiple_Devices/02_using_multiple_devices.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,4 @@
6060
flat_d = tf.reshape(d, [-1])
6161

6262
combined = tf.multiply(c, flat_d)
63-
print(sess.run(combined))
63+
print(sess.run(combined))

10_Taking_TensorFlow_to_Production/03_Parallelizing_TensorFlow/03_parallelizing_tensorflow.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
server = tf.train.Server(cluster, job_name="local", task_index=0)
1515
server = tf.train.Server(cluster, job_name="local", task_index=1)
1616
# Finish and add
17-
#server.join()
17+
# server.join()
1818

1919
# Have each worker do a task
2020
# Worker 0 : create matrices
@@ -39,4 +39,4 @@
3939

4040
with tf.Session(server.target) as sess:
4141
result = sess.run(summed_out)
42-
print('Summed Values:{}'.format(result))
42+
print('Summed Values:{}'.format(result))

10_Taking_TensorFlow_to_Production/04_Production_Tips/04_production_tips_for_tf.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,11 @@
6363
# to handle running and loading of arguments
6464

6565
# At the beginning of the file, define the flags.
66-
tf.app.flags.DEFINE_string("worker_locations", "", "List of worker addresses.")
67-
tf.app.flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
68-
tf.app.flags.DEFINE_integer('generations', 1000, 'Number of training generations.')
69-
tf.app.flags.DEFINE_boolean('run_unit_tests', False, 'If true, run tests.')
66+
tf.flags.DEFINE_string("worker_locations", "", "List of worker addresses.")
67+
tf.flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
68+
tf.flags.DEFINE_integer('generations', 1000, 'Number of training generations.')
69+
tf.flags.DEFINE_boolean('run_unit_tests', False, 'If true, run tests.')
70+
FLAGS = tf.flags.FLAGS
7071

7172
# Need to define a 'main' function for the app to run
7273
def main(_):
@@ -77,7 +78,10 @@ def main(_):
7778

7879
# Run the TensorFlow app
7980
if __name__ == "__main__":
81+
# The following is looking for a "main()" function to run and will pass.
8082
tf.app.run()
83+
# Can modify this to be more custom:
84+
tf.app.run(main=my_main_function(), argv=my_arguments)
8185

8286

8387
# Use of TensorFlow's built in logging:

10_Taking_TensorFlow_to_Production/05_Production_Example/05_production_ex_eval.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -15,33 +15,33 @@
1515
from tensorflow.python.framework import ops
1616
ops.reset_default_graph()
1717

18-
tf.app.flags.DEFINE_string("storage_folder", "temp", "Where to store model and data.")
19-
tf.app.flags.DEFINE_string('model_file', False, 'Model file location.')
20-
tf.app.flags.DEFINE_boolean('run_unit_tests', False, 'If true, run tests.')
21-
FLAGS = tf.app.flags.FLAGS
18+
tf.flags.DEFINE_string("storage_folder", "temp", "Where to store model and data.")
19+
tf.flags.DEFINE_bool('model_file', False, 'Model file location.')
20+
tf.flags.DEFINE_bool('run_unit_tests', False, 'If true, run tests.')
21+
FLAGS = tf.flags.FLAGS
2222

2323

2424
# Create a text cleaning function
2525
def clean_text(text_string):
2626
text_string = re.sub(r'([^\s\w]|_|[0-9])+', '', text_string)
2727
text_string = " ".join(text_string.split())
2828
text_string = text_string.lower()
29-
return(text_string)
29+
return text_string
3030

3131

3232
# Load vocab processor
3333
def load_vocab():
3434
vocab_path = os.path.join(FLAGS.storage_folder, "vocab")
3535
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor.restore(vocab_path)
36-
return(vocab_processor)
36+
return vocab_processor
3737

3838

3939
# Process input data:
4040
def process_data(input_data, vocab_processor):
4141
input_data = clean_text(input_data)
4242
input_data = input_data.split()
4343
processed_input = np.array(list(vocab_processor.transform(input_data)))
44-
return(processed_input)
44+
return processed_input
4545

4646

4747
# Get input function
@@ -52,7 +52,7 @@ def get_input_data():
5252
"""
5353
input_text = input("Please enter a text message to evaluate: ")
5454
vocab_processor = load_vocab()
55-
return(process_data(input_text, vocab_processor))
55+
return process_data(input_text, vocab_processor)
5656

5757

5858
# Test clean_text function
@@ -95,6 +95,7 @@ def main(args):
9595
# Print output (Or save to file or DB connection?)
9696
print('Probability of Spam: {:.4}'.format(probability_prediction[1]))
9797

98+
9899
# Run main module/tf App
99100
if __name__ == "__main__":
100101
if FLAGS.run_unit_tests:

0 commit comments

Comments
 (0)