-
Notifications
You must be signed in to change notification settings - Fork 1
/
EP11_ReInitializable_Iterator_Switch.py
119 lines (99 loc) · 4.08 KB
/
EP11_ReInitializable_Iterator_Switch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# -*- coding: utf-8 -*-
"""
| **@created on:** 08/06/18,
| **@author:** prathyushsp,
| **@version:** v0.0.1
|
| **Description:**
|
|
| **Sphinx Documentation Status:** --
|
..todo::
"""
import os
import sys
import json
if len(sys.argv) <= 1:
sys.argv.append('cpu')
USE_GPU = True if sys.argv[1] == 'gpu' else False
os.environ["CUDA_VISIBLE_DEVICES"] = "0" if USE_GPU else ""
from benchmark.benchmark import BenchmarkUtil
from benchmark.system_monitors import CPUMonitor, MemoryMonitor, GPUMonitor
butil = BenchmarkUtil(model_name='EP11 Reinitializable_iterator_switch {}'.format(sys.argv[1]),
stats_save_path='/tmp/stats/',
monitors=[CPUMonitor, MemoryMonitor, GPUMonitor])
@butil.monitor
def main():
# Imports
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
# Global Variables
EPOCH = 100
BATCH_SIZE = 32
DISPLAY_STEP = 1
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Create Dataset
# Create Dataset
train_features_dataset = tf.data.Dataset.from_tensor_slices(mnist.train.images)
train_label_dataset = tf.data.Dataset.from_tensor_slices(mnist.train.labels)
train_dataset = tf.data.Dataset.zip((train_features_dataset, train_label_dataset)).repeat(EPOCH).batch(BATCH_SIZE)
# Create Valid Dataset
valid_features_dataset = tf.data.Dataset.from_tensor_slices(mnist.test.images)
valid_label_dataset = tf.data.Dataset.from_tensor_slices(mnist.test.labels)
valid_dataset = tf.data.Dataset.zip((valid_features_dataset, valid_label_dataset)).batch(
batch_size=mnist.train.num_examples)
# Create Dataset Iterator
iterator = tf.data.Iterator.from_structure(train_dataset.output_types,
train_dataset.output_shapes)
# Create features and labels
features, labels = iterator.get_next()
# Create Initialization Op
train_init_op = iterator.make_initializer(train_dataset)
valid_init_op = iterator.make_initializer(valid_dataset)
# Deeplearning Model
def nn_model(features, labels):
bn = tf.layers.batch_normalization(features)
fc1 = tf.layers.dense(bn, 50)
fc2 = tf.layers.dense(fc1, 50)
fc2 = tf.layers.dropout(fc2)
fc3 = tf.layers.dense(fc2, 10)
loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=fc3))
optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)
return optimizer, loss
# Create elements from iterator
training_op, loss_op = nn_model(features=features, labels=labels)
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
config_proto = tf.ConfigProto(log_device_placement=True)
config_proto.gpu_options.allow_growth = True
start = time.time()
with tf.train.MonitoredTrainingSession(config=config_proto) as sess:
sess.run(init_op)
sess.run(train_init_op)
batch_id, epoch_id, total_batches, avg_cost = 0, 0, int(mnist.train.num_examples / BATCH_SIZE), 0
while True:
try:
_, c = sess.run([training_op, loss_op])
avg_cost += c / total_batches
if batch_id == total_batches:
if epoch_id % DISPLAY_STEP == 0:
print("Epoch:", '%04d' % (epoch_id + 1), "cost={:.9f}".format(avg_cost))
batch_id, avg_cost, cost = 0, 0, []
epoch_id += 1
batch_id += 1
except tf.errors.OutOfRangeError:
break
print("Optimization Finished!")
sess.run(valid_init_op)
while True:
try:
c = sess.run(loss_op)
avg_cost += c / total_batches
except tf.errors.OutOfRangeError:
break
print("Validation :", "cost={:.9f}".format(avg_cost))
print('Total Time Elapsed: {} secs'.format(time.time() - start))
json.dump({'internal_time': time.time() - start}, open('/tmp/time.json', 'w'))
if __name__ == '__main__':
main()