09.05.2023 Views

pdfcoffee

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5

IMG_SIZE = 160 # All images will be resized to 160x160

def format_example(image, label):

image = tf.cast(image, tf.float32)

image = (image/127.5) - 1

image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))

return image, label

train = raw_train.map(format_example)

validation = raw_validation.map(format_example)

test = raw_test.map(format_example)

Then, we shuffle and batch the training set, and batch the validation set and test set:

BATCH_SIZE = 32

SHUFFLE_BUFFER_SIZE = 2000

train_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)

validation_batches = validation.batch(BATCH_SIZE)

test_batches = test.batch(BATCH_SIZE)

Now, we can use MobileNet with input (160, 160, 3) where 3 is the number of color

channels. The top layers are omitted (include_top=False) since we are going to use

our own top layer, and all the internal layers are frozen because we use the weights

pretrained on ImageNet:

IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)

base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,

include_top=False,

weights='imagenet')

base_model.trainable = False

base_model.summary()

Let's inspect a batch and see if the shape is correct:

for image_batch, label_batch in train_batches.take(1):

pass

print (image_batch.shape)

(32, 160, 160, 3)

(32, 160, 160, 3) is the correct shape!

MobileNetV2 transforms each 160×160×3 image into a 5×5×1280 block of features.

For instance, let's see the transformation applied to the batch:

feature_batch = base_model(image_batch)

print(feature_batch.shape)

(32, 5, 5, 1280)

[ 155 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!