Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132926 views
License: OTHER
1
""" Example to demonstrate how to use queues
2
Author: Chip Huyen
3
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
4
cs20si.stanford.edu
5
"""
6
import os
7
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
8
9
import numpy as np
10
import tensorflow as tf
11
12
N_SAMPLES = 1000
13
NUM_THREADS = 4
14
# Generating some simple data
15
# create 1000 random samples, each is a 1D array from the normal distribution (10, 1)
16
data = 10 * np.random.randn(N_SAMPLES, 4) + 1
17
# create 1000 random labels of 0 and 1
18
target = np.random.randint(0, 2, size=N_SAMPLES)
19
20
queue = tf.FIFOQueue(capacity=50, dtypes=[tf.float32, tf.int32], shapes=[[4], []])
21
22
enqueue_op = queue.enqueue_many([data, target])
23
data_sample, label_sample = queue.dequeue()
24
25
# create ops that do something with data_sample and label_sample
26
27
# create NUM_THREADS to do enqueue
28
qr = tf.train.QueueRunner(queue, [enqueue_op] * NUM_THREADS)
29
with tf.Session() as sess:
30
# create a coordinator, launch the queue runner threads.
31
coord = tf.train.Coordinator()
32
enqueue_threads = qr.create_threads(sess, coord=coord, start=True)
33
try:
34
for step in range(100): # do to 100 iterations
35
if coord.should_stop():
36
break
37
data_batch, label_batch = sess.run([data_sample, label_sample])
38
print(data_batch)
39
print(label_batch)
40
except Exception as e:
41
coord.request_stop(e)
42
finally:
43
coord.request_stop()
44
coord.join(enqueue_threads)
45