Reshape the input for BatchDataset trained model

Viewed 161

I trained my tensorflow model on images after convert it to BatchDataset

  IMG_size = 224
  INPUT_SHAPE = [None, IMG_size, IMG_size, 3] # 4D input

  model.fit(x=train_data,
            epochs=EPOCHES,
            validation_data=test_data,
            validation_freq=1, # check validation metrics every epoch
            callbacks=[tensorboard, early_stopping])


     model.compile(
      loss=tf.keras.losses.CategoricalCrossentropy(), 
      optimizer=tf.keras.optimizers.Adam(), 
      metrics=["accuracy"] 
    )


  model.build(INPUT_SHAPE)

the train_data type is: tensorflow.python.data.ops.dataset_ops.BatchDataset.

I want to run my model on a single numpy array or tensor constant, but it will be 3D input matrix not 4D as the input TensorShape([224, 224, 3]); how can i reshape it?

2 Answers

You can expand the dimensions of your image matrix by using this code:

newImage = tf.expand_dims(Original_Image, axis = 0)

then pass it to the predict function, it will work fine.

target sizes make all input into the same shape.

It is helpful with input shape or you can use the image function to expand the dimension. img_array = tf.expand_dims(image, 0) # Create a batch

Talking about your input INPUT_SHAPE = [None, IMG_size, IMG_size, 3] # 4D input you can arrange those input images by image training dataset and feeds into the model.

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Variables
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
BATCH_SIZE = 16
IMG_SIZE = (160, 160)
PATH = 'F:\\datasets\\downloads\\sample\\cats_dogs\\training'
training_directory = os.path.join(PATH, 'train')
validation_directory = os.path.join(PATH, 'validation')

train_dataset = tf.keras.utils.image_dataset_from_directory(training_directory,
            shuffle=True,
            batch_size=BATCH_SIZE,
            image_size=IMG_SIZE,
            seed=42)
validation_dataset = tf.keras.utils.image_dataset_from_directory(validation_directory,
            shuffle=True,
            batch_size=BATCH_SIZE,
            image_size=IMG_SIZE,
            seed=42)
    
class_names = train_dataset.class_names
print( "class_names: " + str( class_names ) )

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
DataSet
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Model ( examine input layer )
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
inputs = tf.keras.Input(shape=(160, 160, 3))
model = tf.keras.Model(inputs, outputs)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Training
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
history = model.fit(train_dataset, epochs=initial_epochs, validation_data=validation_dataset)

... Sample

Related