Home > Enterprise >  I get this Error while trying to Train a Model, Tensorflow ValueError: Unexpected result of `train_f
I get this Error while trying to Train a Model, Tensorflow ValueError: Unexpected result of `train_f

Time:03-18

I'm trying to train my model to read some x-ray Images, I'm using Jupyter Notebook, I imported the Libraries, Defined the image properties, Prepared the dataset, Created the neural net model, Defined callbacks... and Managed the Data, But while trying to train my model this is the error I get :

ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

Here's creation of the neural net model :

model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(Image_Width,Image_Height,Image_Channels)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2,activation='softmax'))
model.compile(loss='categorical_crossentropy',
  optimizer='rmsprop',metrics=['accuracy'])

And the training and validation of the data generator:

base_dir = "C:/Users/lenovo/PneumoniaClassification/chest_xray"
train_dir = os.path.join(base_dir, 'train')
test_dir = os.path.join(base_dir, 'test')
validation_dir = os.path.join(base_dir, 'val')


train_datagen = ImageDataGenerator(rotation_range=15,
                                    rescale=1./255,
                                    shear_range=0.1,
                                    zoom_range=0.2,
                                    horizontal_flip=True,
                                    width_shift_range=0.1,
                                    height_shift_range=0.1
                                    )
train_generator = train_datagen.flow_from_directory(
        train_dir,  # This is the source directory for training images
        target_size=Image_Size,  # All images will be resized 
        batch_size= 50,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')

test_datagen = ImageDataGenerator(rotation_range=15,
                                    rescale=1./255,
                                    shear_range=0.1,
                                    zoom_range=0.2,
                                    horizontal_flip=True,
                                    width_shift_range=0.1,
                                    height_shift_range=0.1)

test_generator = test_datagen.flow_from_directory(
        test_dir,
        target_size=Image_Size,
        batch_size= 50,
        class_mode='binary')

validation_datagen = ImageDataGenerator(rescale=1./255)

validation_generator = test_datagen.flow_from_directory(
        validation_dir,
        target_size=Image_Size,
        batch_size= 50,
        class_mode='binary')

But here when I try to train the Model I get the error Unexpected result of train_function..... using this Code :

epochs=10
model.fit(
    train_generator, 
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=total_validate//batch_size,
    steps_per_epoch=total_train//batch_size,
    callbacks=callbacks
)

This is the full error :

ValueError                                Traceback (most recent call last)
Input In [33], in <cell line: 2>()
      1 epochs=10
----> 2 model.fit(
      3     train_generator, 
      4     epochs=epochs,
      5     validation_data=validation_generator,
      6     validation_steps=total_validate//batch_size,
      7     steps_per_epoch=total_train//batch_size,
      8     callbacks=callbacks
      9 )

File ~\AppData\Roaming\Python\Python39\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File ~\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:1395, in Model.fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1393 logs = tf_utils.sync_to_numpy_or_python_type(logs)
   1394 if logs is None:
-> 1395   raise ValueError('Unexpected result of `train_function` '
   1396                    '(Empty logs). Please use '
   1397                    '`Model.compile(..., run_eagerly=True)`, or '
   1398                    '`tf.config.run_functions_eagerly(True)` for more '
   1399                    'information of where went wrong, or file a '
   1400                    'issue/bug to `tf.keras`.')
   1401 epoch_logs = copy.copy(logs)
   1403 # Run validation.

ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

CodePudding user response:

Can you try a dense layer with a single neuron with sigmoid activation as output (and binary crossentropy as loss)?

  • Related