在 tf.keras.utils.Sequence 中调整批处理大小时出错

问题描述

我在 Tensorflow 2.4.1 上学习使用 tf.keras.utils.Sequence。我使用了 API 文档 (https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence) 中 Sequence 中的示例代码,并通过添加 on_epoch_end 函数进行了微调,以在每个 epoch 上自适应地更改 batch_size 值。

from skimage.io import imread
from skimage.transform import resize
import numpy as np
import random
import math

# Here,`x_set` is list of path to the images
# and `y_set` are the associated classes.

class CIFAR10Sequence(tensorflow.keras.utils.Sequence):

    def __init__(self,x_set,y_set,batch_size):
        self.x,self.y = x_set,y_set
        self.batch_size = batch_size

    def __len__(self):
        return math.ceil(len(self.x) / self.batch_size)

    def on_epoch_end(self):
        print(self.batch_size)
        self.batch_size = int(random.randint(10,100))

    def __getitem__(self,idx):
        batch_x = self.x[idx * self.batch_size:(idx + 1) *
        self.batch_size]
        batch_y = self.y[idx * self.batch_size:(idx + 1) *
        self.batch_size]

        return np.array([
            resize(imread(file_name),(200,200))
               for file_name in batch_x]),np.array(batch_y)

然而,在实践中,每个 epoch 的步数(预计会根据批次数而变化)保持不变。实际上,Tensorflow 返回一个 WARNING,通知他们数据用完,并立即停止训练。当初始化 batch_size 小于当前 self.batch_size 时会发生此问题。

WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches

这是我的猜测,Tensorflow 确实在每个 epoch 之后调整了批量大小,但不知何故模型仍然保持初始值。这个问题在 Keras 版本 1 中从未发生过。到目前为止,我对解决这个问题一无所知。 编辑 1:训练数据的数量远大于批次数量。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...