tensorflow2 ValueError: slice index 0 of dimension 0 out of bounds.

问题描述

Traceback (most recent call last):
  File "E:\PythonProjects\cotton5\main.py", line 19, in <module>
    train.start()
  File "E:\PythonProjects\cotton5\train.py", line 38, in start
    self.start_train()
  File "E:\PythonProjects\cotton5\train.py", line 80, in start_train
    history = self.model_3.fit(
  File "D:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1189, in fit
    tmp_logs = self.train_function(iterator)
  File "D:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "D:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1147, in autograph_handler
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:


    ValueError: slice index 0 of dimension 0 out of bounds. for '{{node strided_slice}} = StridedSlice[Index=DT_INT32, T=DT_INT32, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1](Shape, strided_slice/stack, strided_slice/stack_1, strided_slice/stack_2)' with input shapes: [0], [1], [1], [1] and with computed input tensors: input[1] = <0>, input[2] = <1>, input[3] = <1>.

(初学tensorflow,选择学习tensorflow2,折腾来去,遇到问题一大把,突然想到可以记录一下。)

寻找相关

在github上找到相关问题,链接:Error: slice index 0 of dimension 0 out of bounds #34850

经过仔细查看,受到如下图的一个回复启发:
tensorflow2 ValueError: slice index 0 of dimension 0 out of bounds._第1张图片
得知该错误可能与batch_size有关,才想起来在写初始化数据集时删掉了类似方法调用.batch(batch_size),所以当前代码如下:

self.ds_train = ds_train.map(preprocess).shuffle(1000).prefetch(AUTOTUNE).repeat()

修改过后:

self.ds_train = ds_train.map(preprocess).batch(self.batch_size).shuffle(1000).prefetch(AUTOTUNE).repeat()

这样就解决了。
到目前为止,我只大概知道batch_size与数据集图片有关,反正不能超过各个类别中的最少图片数的最小。

总结

DataSet数据集添加一个.batch(self.batch_size)的调用。

你可能感兴趣的:(笔记,python,tensorflow)