The error you're encountering is due to the dimensions of the input to one of the MaxPooling3D layers becoming too small for the specified pooling operation. In your network architecture, this is happening because the depth (first dimension in the spatial dimensions of the input shape) is being reduced to the point that it becomes less than the pool size, which is 2 in all the spatial dimensions for the last MaxPooling3D layer.
Here's how to resolve this issue:
-
Ensure that the input shape is large enough to support all the pooling operations. Since you are using 'same' padding and your strides for the depth dimension are (2,2,1) for the first MaxPooling3D and (2,2,2) for the subsequent ones, the depth dimension should not be reduced too quickly.
-
Adjust the pool size and strides of the MaxPooling3D layers to prevent the depth dimension from becoming too small. If the depth dimension becomes 1 after a certain layer, you should avoid further pooling in the depth dimension.
Let's adjust the architecture to ensure that the depth dimension remains greater than or equal to the pool size. Since the input shape's depth dimension is 8, after three MaxPooling3D operations with a pool size of (2,2,2), the depth will be 1 ((8/2)/2)/2 = 1). Hence, the fourth MaxPooling3D layer should not pool across the depth dimension.
Here's the fixed architecture:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv3D, BatchNormalization, LeakyReLU, MaxPooling3D, Flatten, Dropout, Dense
model = Sequential()
model.add(Conv3D(32, (3,3,3), strides=(1,1,1), padding='same', input_shape=(8,120,120,3)))
model.add(BatchNormalization())
model.add(LeakyReLU())
model.add(MaxPooling3D(pool_size=(2,2,2), strides=(2,2,2)))
model.add(Conv3D(64, (3,3,3), strides=(1,1,1), padding='same'))
model.add(BatchNormalization())
model.add(LeakyReLU())
model.add(MaxPooling3D(pool_size=(2,2,2), strides=(2,2,2)))
model.add(Conv3D(128, (3,3,3), strides=(1,1,1), padding='same'))
model.add(BatchNormalization())
model.add(LeakyReLU())
model.add(MaxPooling3D(pool_size=(2,2,2), strides=(2,2,2)))
# At this point, the depth dimension has become 1, so we will not pool across the depth anymore.
model.add(Conv3D(128, (3,3,3), strides=(1,1,1), padding='same'))
model.add(BatchNormalization())
model.add(LeakyReLU())
# Change the pool size to (1,2,2) to avoid pooling in the depth dimension.
model.add(MaxPooling3D(pool_size=(1,2,2), strides=(1,2,2)))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(256, activation='elu'))
model.add(Dropout(0.5))
model.add(Dense(5, activation='softmax'))
Now, the last MaxPooling3D layer has a pool size of (1,2,2), which means it will not reduce the size of the depth dimension anymore, preventing the error you encountered.