每次迭代后处理时间越来越长TensorFlow

问题描述

您在每次迭代中都调用代码,因此,每次迭代都将这些操作添加到图形中。你不想那样做。您想在开始时构建图,并且在训练循环中仅执行它。另外,为什么您以后需要再次转换为ndimage,而不是一次将其放入TF图并仅使用张量?

解决方法

我正在使用TensorFlow训练用于医学图像应用的CNN。

由于我没有大量数据,因此我尝试在训练循环中对训练批次进行随机修改,以人为地增加训练数据集。我用其他脚本编写了以下函数,并在我的培训批次中调用它:

def randomly_modify_training_batch(images_train_batch,batch_size):

    for i in range(batch_size):
        image = images_train_batch[i]
        image_tensor = tf.convert_to_tensor(image)

        distorted_image = tf.image.random_flip_left_right(image_tensor)
        distorted_image = tf.image.random_flip_up_down(distorted_image)
        distorted_image = tf.image.random_brightness(distorted_image,max_delta=60)
        distorted_image = tf.image.random_contrast(distorted_image,lower=0.2,upper=1.8)

        with tf.Session():
            images_train_batch[i] = distorted_image.eval()  # .eval() is used to reconvert the image from Tensor type to ndarray

return images_train_batch

该代码很好地适用于对我的图像进行修改。

问题是 :

在我的训练循环的每个迭代(前馈+反向传播)之后,将相同的功能稳定地应用到我的下一个训练批次中,将比上一次稳定地花费5秒。

处理大约需要1秒钟,经过10次以上的迭代后才需要一分钟以上的处理时间。

是什么原因导致速度变慢?我该如何预防?

(我怀疑带有,distorted_image.eval()但我不太确定。每次打开一个新会话吗?Te​​nsorFlow不应像我在“ with
tf.Session()”块中使用的那样自动关闭该会话吗?)