InvalidArgumentError: slice index 5 of dimension 0 out of bounds. [Op:StridedSlice] name: strided_slice/

Viewed 1940

I'm working on a project on Image Classification. Here I've 30 images and when I try to plot those images it gives me following error,

InvalidArgumentError: slice index 5 of dimension 0 out of bounds.
[Op:StridedSlice] name: strided_slice/

Below is my code:

BATCH_SIZE = 5
IMAGE_SIZE = 256
CHANNELS=3  
EPOCHS=10

train_ds = tf.keras.utils.image_dataset_from_directory(
path_to_data,
validation_split=0.2,
subset="training",
seed=123,
image_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE)

val_ds = tf.keras.utils.image_dataset_from_directory(
path_to_data,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE)

for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
   for i in range(9):
       ax = plt.subplot(3, 3, i + 1)
       plt.imshow(images[i].numpy().astype('uint8'))
       plt.title(class_names[labels[i]])
       plt.axis("off")

Error:

InvalidArgumentError: slice index 5 of dimension 0 out of bounds. [Op:StridedSlice] 
name: strided_slice/

Traceback:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-74-385157730873> in <module>()
  5   for i in range(9):
  6     ax = plt.subplot(3, 3, i + 1)
----> 7     plt.imshow(images[i].numpy().astype('uint8'))
  8     plt.title(class_names[labels[i]])
  9     plt.axis("off")
1 Answers

The problem is that you are using train_ds.take(1) to take exactly one batch from your dataset, which has the BATCH_SIZE = 5. If you want to display 9 images in a 3x3 plot, then simply change your BATCH_SIZE to 9. Alternatively, you can adjust the number of subplots you want to create like this:

BATCH_SIZE = 5
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
   for i in range(BATCH_SIZE):
       ax = plt.subplot(1, 5, i + 1)
       plt.imshow(images[i].numpy().astype('uint8'))
       plt.title(class_names[labels[i]])
       plt.axis("off")
Related