I was working with Emotion Detection Dataset having 7 classes and while fitting the model ``generator yielded an element that did not match the expected structure. The expected structure was (tf.float32, tf.float32, tf.float32), but the yielded element was (array([[[[
error is persistent i tried every possible change but nothing happens.
# Hyper Parameters
img_height, img_width = 224, 224
BATCH_SIZE = 64
EPOCHS = 100
NUM_CLASSES = 7
img_gen = ImageDataGenerator(
rescale = 1./255,
rotation_range = 10,
width_shift_range = 0.1,
height_shift_range = 0.1,
horizontal_flip = True,
fill_mode = 'nearest'
)
test_gen = ImageDataGenerator(
rescale = 1./255
)
train_generator = img_gen.flow_from_directory(directory = train_dir, target_size = (img_width, img_height), batch_size = BATCH_SIZE, class_mode = 'categorical', color_mode = 'rgb', subset = 'training', shuffle = True)
test_generator = test_gen.flow_from_directory(directory = test_dir, target_size = (img_width, img_height), batch_size = BATCH_SIZE, class_mode = 'categorical', color_mode = 'rgb')
# Extract class labels for all instances in the training dataset
classes = np.array(train_generator.classes)
# Calculating class weights to handle imbalances in the training data
class_weights = compute_class_weight(
class_weight = 'balanced',
classes = np.unique(classes),
y = classes
)
# Creating a dictionary mapping class indices to their calculated weights
class_weights_dict = dict(enumerate(class_weights))
print("Class Weights : ", class_weights_dict)
tf.keras.backend.clear_session()
vgg = VGG16(input_shape = (224, 224, 3), weights = 'imagenet', include_top = False)
for layer in vgg.layers[:-3]:
layer.trainable = False
vgg.summary()
# Flattening the Layer
x = tf.keras.layers.Flatten()(vgg.output)
# Adding Dense Relu activation layer
x = tf.keras.layers.Dense(1024, activation = 'relu', kernel_initializer = 'he_normal')(x)
x = tf.keras.layers.Dropout(.5)(x)
x = tf.keras.layers.Dense(512, activation = 'relu', kernel_initializer = 'he_normal')(x)
x = tf.keras.layers.Dropout(0.5)(x)
output = tf.keras.layers.Dense(7, activation = 'softmax', kernel_initializer = 'he_normal')(x)
# Creating Model
model = tf.keras.Model(inputs = vgg.input, outputs = output)
# Compile the model
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
# Model summary to see all layers
model.summary()
train_steps_per_epochs = train_generator.samples // train_generator.batch_size + 1
test_steps_per_epochs = test_generator.samples // test_generator.batch_size + 1
try:
history = model.fit(
train_generator,
steps_per_epoch = train_steps_per_epochs,
epochs = EPOCHS,
validation_data = test_generator,
validation_steps = test_steps_per_epochs,
class_weight = class_weights_dict,
callbacks = callbacks
)
except Exception as e:
print(f'Error Occured {e}')