[英]TensorFlow: tf.Session.run() fetches and execution dependencies
我有典型/通用TF(r1.3)配置,其中讀取單個tf.record文件並解碼結果以查詢一些記錄值:
import os, tensorflow as tf
# path to TF record file containing single record
record_file_path = os.path.join(os.getcwd(),'tf.record')
# init a finite file queue with num_epochs=1
file_queue = tf.train.string_input_producer([record_file_path],name='file_queue',num_epochs=1)
# init record reader
reader = tf.TFRecordReader()
# read the record file
_, tfrecord_read_op = reader.read(file_queue)
tfrecord = tf.parse_single_example(
tfrecord_read_op,
features={
'image/height' : tf.FixedLenFeature([], tf.int64 ),
'image/width' : tf.FixedLenFeature([], tf.int64 ),
'image/label' : tf.FixedLenFeature([], tf.int64 ),
'image/encoded': tf.FixedLenFeature([], tf.string)
},
name='features'
)
# since exported as tf.int64 there is no need for tf.decode_raw
heightT = tfrecord['image/height']
widthT = tfrecord['image/width' ]
with tf.Session() as sess:
# init vars
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer ())
# Start populating the filename queue
queue_coordinator = tf.train.Coordinator()
queue_worker_threads = tf.train.start_queue_runners(coord=queue_coordinator)
# kaboom!
height = sess.run(heightT)
width = sess.run(widthT )
# why does this work ??
#height, width = sess.run([heightT, widthT])
# close down the queue
queue_coordinator.request_stop()
queue_coordinator.join(queue_worker_threads)
print('image height x width : {}x{}'.format(height,width))
請注意,文件隊列限制為num_epochs=1
因此僅會為TFRecordReader
生成單個文件一次。
在計算圖中, heightT
和widthT
張量heightT
widthT
取決於tfrecord
,后者取決於tfrecord_read_op
因此, tfrecord
評估tfrecord
,計算圖依賴項都應從file_queue
調用另一個出隊。 在單獨的 tf.Session
run()
調用中評估heightT
和widthT
時確實如此。
num_epoch=None
,如果num_epoch=None
(即單個文件的無限出隊),則單獨的調用將成功(!?),並且num_epochs=None
是默認值。
現在,終於有了一個問題: 為什么/為什么多次調用一次run()
成功評估兩個張量運算? 那就是為什么
height,width = sess.run([heightT,widthT])
成功但
height = sess.run(heightT)
width = sess.run(widthT )
失敗了嗎?
確實,使用占位符(dtype = tf.string)來保存tfrecord_read_op的結果並在占位符上執行tf.parse_single_example
減輕這種影響,但並不能真正說明案例圖評估中的情況。上面突出顯示。
當運行height,width = sess.run([heightT,widthT])
TensorFlow將計算heightT, widthT
的依賴關系,得到一個可以一次計算出這兩個Tensor
的運算heightT, widthT
。 然后, Session
運行此操作並存儲計算的結果,然后將其提取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.