degraded accuracy performance with overfitting when downgrading from tensorflow 2.3.1 to tensorflow 1.14 or 1.15 on multiclass categorization

Viewed 414

I made a script in tensorflow 2.x but I had to downconvert it to tensorflow 1.x (tested in 1.14 and 1.15). However, the tf1 version performs very differently (10% accuracy lower on the test set). See also the plot for train and validation performance (diagram is attached below).

Looking at the operations needed for the migration from tf1 to tf2 it seems that only the Adam learning rate may be a problem but I'm defining it explicitly tensorflow migration

I've reproduced the same behavior both locally on GPU and CPU and on colab. The keras used was the one built-in in tensorflow (tf.keras). I've used the following functions (both for train,validation and test), using a sparse categorization (integers):

train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(    
                        horizontal_flip=horizontal_flip,
                        #rescale=None, #not needed for resnet50
                        preprocessing_function=None, 
                        validation_split=None)

train_dataset = train_datagen.flow_from_directory(
                        directory=train_dir,
                        target_size=image_size,
                        class_mode='sparse',
                        batch_size=batch_size,
                        shuffle=True)    

And the model is a simple resnet50 with a new layer on top:

IMG_SHAPE = img_size+(3,)
inputs = Input(shape=IMG_SHAPE, name='image_input',dtype = tf.uint8)
x = tf.cast(inputs, tf.float32)

# not working in this version of keras. inserted in imageGenerator
x = preprocess_input_resnet50(x)

base_model = tf.keras.applications.ResNet50(
                                include_top=False, 
                                input_shape = IMG_SHAPE,
                                pooling=None,
                                weights='imagenet')
# Freeze the pretrained weights
base_model.trainable = False
x=base_model(x)

# Rebuild top
x = GlobalAveragePooling2D(data_format='channels_last',name="avg_pool")(x)
      
top_dropout_rate = 0.2
x = Dropout(top_dropout_rate, name="top_dropout")(x)
outputs = Dense(num_classes,activation="softmax", name="pred_out")(x)
model = Model(inputs=inputs, outputs=outputs,name="ResNet50_comp")

optimizer = tf.keras.optimizers.Adam(lr=learning_rate)
model.compile(optimizer=optimizer,
        loss="sparse_categorical_crossentropy",
        metrics=['accuracy'])

And then I'm calling the fit function:

history = model.fit_generator(train_dataset, 
                    steps_per_epoch=n_train_batches, 
                    validation_data=validation_dataset, 
                    validation_steps=n_val_batches,
                    epochs=initial_epochs,
                    verbose=1,
                    callbacks=[stopping])

I've reproduced the same behavior for example with the following full script (applied to my dataset and changed to adam and removed intermediate final dense layer): deep learning sandbox

The easiest way to replicate this behavior was to enable or disable the following line on a tf2 environment with the same script and add the following line to it. However, I've tested also on tf1 environments (1.14 and 1.15):

tf.compat.v1.disable_v2_behavior()

Sadly I cannot provide the dataset.

Update 26/11/2020

For full reproducibility I've obtained a similar behaviour by means of the food101 (101 categories) dataset enabling tf1 behaviour with 'tf.compat.v1.disable_v2_behavior()'. The following is the script executed with tensorflow-gpu 2.2.0:

#%% ref https://medium.com/deeplearningsandbox/how-to-use-transfer-learning-and-fine-tuning-in-keras-and-tensorflow-to-build-an-image-recognition-94b0b02444f2
import os
import sys
import glob
import argparse
import matplotlib.pyplot as plt
import tensorflow as tf
# enable and disable this to obtain tf1 behaviour
tf.compat.v1.disable_v2_behavior()
from tensorflow.keras import __version__
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam

# since i'm using resnet50 weights from imagenet, i'm using food101 for 
# similar but different categorization tasks
# pip install tensorflow-datasets if tensorflow_dataset not found
import tensorflow_datasets as tfds
(train_ds,validation_ds),info= tfds.load('food101', split=['train','validation'], shuffle_files=True, with_info=True)

assert isinstance(train_ds, tf.data.Dataset)
print(train_ds)
#%%
IM_WIDTH, IM_HEIGHT = 224, 224 
NB_EPOCHS = 10
BAT_SIZE = 32



def get_nb_files(directory):
  """Get number of files by searching directory recursively"""
  if not os.path.exists(directory):
    return 0
  cnt = 0
  for r, dirs, files in os.walk(directory):
    for dr in dirs:
      cnt += len(glob.glob(os.path.join(r, dr + "/*")))
  return cnt


def setup_to_transfer_learn(model, base_model):
  """Freeze all layers and compile the model"""
  for layer in base_model.layers:
    layer.trainable = False
  model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])


def add_new_last_layer(base_model, nb_classes):
  """Add last layer to the convnet
  Args:
    base_model: keras model excluding top
    nb_classes: # of classes
  Returns:
    new keras model with last layer
  """
  x = base_model.output
  x = GlobalAveragePooling2D()(x)
  #x = Dense(FC_SIZE, activation='relu')(x) #new FC layer, random init
  predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer
  model = Model(inputs=base_model.input, outputs=predictions)
  return model

def train(nb_epoch, batch_size):
  """Use transfer learning and fine-tuning to train a network on a new dataset"""

  #nb_train_samples = train_ds.cardinality().numpy()
  nb_train_samples=info.splits['train'].num_examples
  nb_classes = info.features['label'].num_classes
  classes_names = info.features['label'].names
  #nb_val_samples = validation_ds.cardinality().numpy()
  nb_val_samples = info.splits['validation'].num_examples
  #nb_epoch = int(args.nb_epoch)
  #batch_size = int(args.batch_size)

  def preprocess(features):
      #print(features['image'], features['label'])
      image = tf.image.resize(features['image'], [224,224])
      #image = tf.divide(image, 255)
      #print(image)
      # data augmentation
      image=tf.image.random_flip_left_right(image)

      image = preprocess_input(image)
      label = features['label']
      # for categorical crossentropy
      #label = tf.one_hot(label,101,axis=-1)
      #return image, tf.cast(label, tf.float32)
      return image, label
  #pre-processing the dataset to fit a specific image size and 2D labelling
  train_generator = train_ds.map(preprocess).batch(batch_size).repeat()
  validation_generator = validation_ds.map(preprocess).batch(batch_size).repeat()

  #train_generator=train_ds
  #validation_generator=validation_ds
  #fig = tfds.show_examples(validation_generator, info)
  # setup model
  base_model = ResNet50(weights='imagenet', include_top=False) #include_top=False excludes final FC layer
  model = add_new_last_layer(base_model, nb_classes)

  # transfer learning
  setup_to_transfer_learn(model, base_model)

  history = model.fit(
    train_generator,
    epochs=nb_epoch,
    steps_per_epoch=nb_train_samples//BAT_SIZE,
    validation_data=validation_generator,
    validation_steps=nb_val_samples//BAT_SIZE)
    #class_weight='auto')
#execute
history = train(nb_epoch=NB_EPOCHS, batch_size=BAT_SIZE)

And the performance on food101 dataset: acc performance on food101 on differet tf versions

update 27/11/2020

It's possible to see the discrepancy also in the way smaller oxford_flowers102 dataset:

(train_ds,validation_ds,test_ds),info= tfds.load('oxford_flowers102', split=['train','validation','test'], shuffle_files=True, with_info=True)

oxford_flowers

Nb: the above plot shows confidences given by running the same training multiple times and evaluatind mean and std to check for the effects on random weights initialization and data augmentation.

Moreover I've tried some hyperparameter tuning on tf2 resulting in the following picture:

  • changing optimizer (adam and rmsprop)
  • not applying horizontal flipping aumgentation
  • deactivating keras resnet50 preprocess_input

enter image description here

Thanks in advance for every suggestion. Here are the accuracy and validation performance on tf1 and tf2 on my dataset:

Update 14/12/2020

I'm sharing the colab for reproducibility on oxford_flowers at the clic of a button: colab script

1 Answers

I came across something similar, when doing the opposite migration (from TF1+Keras to TF2).

Running this code below:

# using TF2
import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50 
fe = ResNet50(include_top=False, pooling="avg")
out = fe.predict(np.ones((1,224,224,3))).flatten()
sum(out)
>>> 212.3205274187726

# using TF1+Keras
import numpy as np 
from keras.applications.resnet50 import ResNet50 
fe = ResNet50(include_top=False, pooling="avg") 
out = fe.predict(np.ones((1,224,224,3))).flatten() 
sum(out) 
>>> 187.23898954353717

you can see the same model from the same library on different versions does not return the same value (using sum as a quick check-up). I found the answer to this mysterious behavior in this other SO answer: ResNet model in keras and tf.keras give different output for the same image

Another recommendation I'd give you is, try using pooling from inside applications.resnet50.ResNet50 class, instead of the additional layer in your function, for simplicity, and to remove possible problem-generators :)

Related