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

Processing time gets longer and longer after each iteration (TensorFlow)

我正在使用 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 不应该像我在 [=30= 中使用的那样自动关闭会话]块?)

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