我有这种方法拍摄图像并将其转换为张量。我在一个循环中调用它,转换的执行时间开始很小并且不断增长。
def read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255):
input_name = "file_reader"
output_name = "normalized"
file_reader = tf.read_file(file_name, input_name)
image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
name='jpeg_reader')
float_caster = tf.cast(image_reader, tf.float32)
dims_expander = tf.expand_dims(float_caster, 0)
resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
sess = tf.Session()
result = sess.run(normalized)
return result
如何优化此功能?
答案 0 :(得分:7)
问题几乎可以肯定是由于在tf.Graph
函数的多次调用中使用了相同的默认read_tensor_from_image_file()
。解决此问题的最简单方法是在函数体周围添加with tf.Graph().as_default():
块,如下所示:
def read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255):
with tf.Graph().as_default():
input_name = "file_reader"
output_name = "normalized"
file_reader = tf.read_file(file_name, input_name)
image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
name='jpeg_reader')
float_caster = tf.cast(image_reader, tf.float32)
dims_expander = tf.expand_dims(float_caster, 0)
resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
sess = tf.Session()
result = sess.run(normalized)
return result
通过此更改,对函数的每次调用都将创建一个新图形,而不是向节点添加默认图形(随后会随着时间的推移而增长,泄漏内存,并且每次使用时都会花费更长的时间)。
更高效的版本将使用tf.placeholder()
作为文件名,构造单个图形,并在TensorFlow会话中移动for循环 。以下内容可行:
def read_tensors_from_image_files(file_names, input_height=299, input_width=299, input_mean=0, input_std=255):
with tf.Graph().as_default():
input_name = "file_reader"
output_name = "normalized"
file_name_placeholder = tf.placeholder(tf.string, shape=[])
file_reader = tf.read_file(file_name_placeholder, input_name)
image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
name='jpeg_reader')
float_caster = tf.cast(image_reader, tf.float32)
dims_expander = tf.expand_dims(float_caster, 0)
resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
with tf.Session() as sess:
for file_name in file_names:
yield sess.run(normalized, {file_name_placeholder: file_name})