0% found this document useful (0 votes)
2 views

AAIEXP7 (1)

The document outlines a Python notebook for image classification using TensorFlow, specifically focusing on a dataset of cats and dogs. It includes steps for unzipping the dataset, loading training and validation datasets, and applying data augmentation techniques. Additionally, it utilizes the MobileNet V2 model for feature extraction and provides details on the model architecture.

Uploaded by

mactrader99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

AAIEXP7 (1)

The document outlines a Python notebook for image classification using TensorFlow, specifically focusing on a dataset of cats and dogs. It includes steps for unzipping the dataset, loading training and validation datasets, and applying data augmentation techniques. Additionally, it utilizes the MobileNet V2 model for feature extraction and provides details on the model architecture.

Uploaded by

mactrader99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

2/20/25, 7:14 PM AAIEXP7.

ipynb - Colab

import matplotlib.pyplot as plt


import numpy as np
import os
import tensorflow as tf

import os
import zipfile

# Define dataset path in Google Drive


zip_path = "/content/drive/MyDrive/aai LAB/cats_and_dogs_filtered.zip"

# Define the extraction path


extract_path = "/content/cats_and_dogs_filtered"

# Unzip the dataset


with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall("/content/")

print("Dataset extracted successfully.")

Dataset extracted successfully.

import tensorflow as tf
import os

# Set dataset paths


train_dir = os.path.join(extract_path, 'train')
validation_dir = os.path.join(extract_path, 'validation')

# Define batch size and image size


BATCH_SIZE = 32
IMG_SIZE = (160, 160)

# Load train dataset


train_dataset = tf.keras.utils.image_dataset_from_directory(
train_dir,
shuffle=True,
batch_size=BATCH_SIZE,
image_size=IMG_SIZE
)

# Load validation dataset


validation_dataset = tf.keras.utils.image_dataset_from_directory(
validation_dir,
shuffle=True,
batch_size=BATCH_SIZE,
image_size=IMG_SIZE
)

# Show dataset info


class_names = train_dataset.class_names
print("Class Names:", class_names)

Found 2000 files belonging to 2 classes.


Found 1000 files belonging to 2 classes.
Class Names: ['cats', 'dogs']

class_names = train_dataset.class_names

plt.figure(figsize=(10, 10))
for images, labels in train_dataset.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 1/12
2/20/25, 7:14 PM AAIEXP7.ipynb - Colab

val_batches = tf.data.experimental.cardinality(validation_dataset)
test_dataset = validation_dataset.take(val_batches // 5)
validation_dataset = validation_dataset.skip(val_batches // 5)

print('Number of validation batches: %d' % tf.data.experimental.cardinality(validation_dataset))


print('Number of test batches: %d' % tf.data.experimental.cardinality(test_dataset))

Number of validation batches: 26


Number of test batches: 6

AUTOTUNE = tf.data.AUTOTUNE

train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)
validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE)
test_dataset = test_dataset.prefetch(buffer_size=AUTOTUNE)

data_augmentation = tf.keras.Sequential([
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.2),
])

for image, _ in train_dataset.take(1):


plt.figure(figsize=(10, 10))
first_image = image[0]
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
augmented_image = data_augmentation(tf.expand_dims(first_image, 0))
plt.imshow(augmented_image[0] / 255)
plt.axis('off')

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 2/12
2/20/25, 7:14 PM AAIEXP7.ipynb - Colab

preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input

rescale = tf.keras.layers.Rescaling(1./127.5, offset=-1)

# Create the base model from the pre-trained model MobileNet V2


IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
include_top=False,
weights='imagenet')

image_batch, label_batch = next(iter(train_dataset))


feature_batch = base_model(image_batch)
print(feature_batch.shape)

(32, 5, 5, 1280)

base_model.trainable = False

# Let's take a look at the base model architecture


base_model.summary()

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 3/12
AAIEXP7.ipynb - Colab

Model: "mobilenetv2_1.00_160"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Layer (type) ┃ Output Shape ┃ Param # ┃ Connected to ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━┩
│ input_layer_2 │ (None, 160, 160, 3) │ 0 │ - │
│ (InputLayer) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ Conv1 (Conv2D) │ (None, 80, 80, 32) │ 864 │ input_layer_2[0][0] │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ bn_Conv1 │ (None, 80, 80, 32) │ 128 │ Conv1[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ Conv1_relu (ReLU) │ (None, 80, 80, 32) │ 0 │ bn_Conv1[0][0] │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ expanded_conv_depthwise │ (None, 80, 80, 32) │ 288 │ Conv1_relu[0][0] │
│ (DepthwiseConv2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ expanded_conv_depthwise_… │ (None, 80, 80, 32) │ 128 │ expanded_conv_depthwi… │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ expanded_conv_depthwise_… │ (None, 80, 80, 32) │ 0 │ expanded_conv_depthwi… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ expanded_conv_project │ (None, 80, 80, 16) │ 512 │ expanded_conv_depthwi… │
│ (Conv2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ expanded_conv_project_BN │ (None, 80, 80, 16) │ 64 │ expanded_conv_project… │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_expand (Conv2D) │ (None, 80, 80, 96) │ 1,536 │ expanded_conv_project… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_expand_BN │ (None, 80, 80, 96) │ 384 │ block_1_expand[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_expand_relu │ (None, 80, 80, 96) │ 0 │ block_1_expand_BN[0][… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_pad │ (None, 81, 81, 96) │ 0 │ block_1_expand_relu[0… │
│ (ZeroPadding2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_depthwise │ (None, 40, 40, 96) │ 864 │ block_1_pad[0][0] │
│ (DepthwiseConv2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_depthwise_BN │ (None, 40, 40, 96) │ 384 │ block_1_depthwise[0][… │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_depthwise_relu │ (None, 40, 40, 96) │ 0 │ block_1_depthwise_BN[… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_project (Conv2D) │ (None, 40, 40, 24) │ 2,304 │ block_1_depthwise_rel… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_1_project_BN │ (None, 40, 40, 24) │ 96 │ block_1_project[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_expand (Conv2D) │ (None, 40, 40, 144) │ 3,456 │ block_1_project_BN[0]… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_expand_BN │ (None, 40, 40, 144) │ 576 │ block_2_expand[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_expand_relu │ (None, 40, 40, 144) │ 0 │ block_2_expand_BN[0][… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_depthwise │ (None, 40, 40, 144) │ 1,296 │ block_2_expand_relu[0… │
│ (DepthwiseConv2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_depthwise_BN │ (None, 40, 40, 144) │ 576 │ block_2_depthwise[0][… │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_depthwise_relu │ (None, 40, 40, 144) │ 0 │ block_2_depthwise_BN[… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_project (Conv2D) │ (None, 40, 40, 24) │ 3,456 │ block_2_depthwise_rel… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_project_BN │ (None, 40, 40, 24) │ 96 │ block_2_project[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_2_add (Add) │ (None, 40, 40, 24) │ 0 │ block_1_project_BN[0]… │
│ │ │ │ block_2_project_BN[0]… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_3_expand (Conv2D) │ (None, 40, 40, 144) │ 3,456 │ block_2_add[0][0] │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_3_expand_BN │ (None, 40, 40, 144) │ 576 │ block_3_expand[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_3_expand_relu │ (None, 40, 40, 144) │ 0 │ block_3_expand_BN[0][… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_3_pad │ (None, 41, 41, 144) │ 0 │ block_3_expand_relu[0… │
│ (ZeroPadding2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_3_depthwise │ (None, 20, 20, 144) │ 1,296 │ block_3_pad[0][0] │
│ (DepthwiseConv2D) │ │ │ │

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 4/12
AAIEXP7.ipynb - Colab

├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_14_project_BN │ (None, 5, 5, 160) │ 640 │ block_14_project[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_14_add (Add) │ (None, 5, 5, 160) │ 0 │ block_13_project_BN[0… │
│ │ │ │ block_14_project_BN[0… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_expand (Conv2D) │ (None, 5, 5, 960) │ 153,600 │ block_14_add[0][0] │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_expand_BN │ (None, 5, 5, 960) │ 3,840 │ block_15_expand[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_expand_relu │ (None, 5, 5, 960) │ 0 │ block_15_expand_BN[0]… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_depthwise │ (None, 5, 5, 960) │ 8,640 │ block_15_expand_relu[… │
│ (DepthwiseConv2D) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_depthwise_BN │ (None, 5, 5, 960) │ 3,840 │ block_15_depthwise[0]… │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_depthwise_relu │ (None, 5, 5, 960) │ 0 │ block_15_depthwise_BN… │
│ (ReLU) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_project (Conv2D) │ (None, 5, 5, 160) │ 153,600 │ block_15_depthwise_re… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_project_BN │ (None, 5, 5, 160) │ 640 │ block_15_project[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_15_add (Add) │ (None, 5, 5, 160) │ 0 │ block_14_add[0][0], │
│ │ │ │ block_15_project_BN[0… │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_16_expand (Conv2D) │ (None, 5, 5, 960) │ 153,600 │ block_15_add[0][0] │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_16_expand_BN │ (None, 5, 5, 960) │ 3,840 │ block_16_expand[0][0] │
│ (BatchNormalization) │ │ │ │
├───────────────────────────┼────────────────────────┼────────────────┼────────────────────────┤
│ block_16_expand_relu │ (None, 5, 5, 960) │ 0 │ block_16_expand_BN[0]… │

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 5/12
AAIEXP7.ipynb - Colab

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
feature_batch_average = global_average_layer(feature_batch)
print(feature_batch_average.shape)

(32, 1280)

prediction_layer = tf.keras.layers.Dense(1, activation='sigmoid')


prediction_batch = prediction_layer(feature_batch_average)
print(prediction_batch.shape)

(32, 1)

inputs = tf.keras.Input(shape=(160, 160, 3))


x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x, training=False)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)

model.summary()

Model: "functional_1"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ Layer (type) ┃ Output Shape ┃ Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ input_layer_3 (InputLayer) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ sequential (Sequential) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ true_divide (TrueDivide) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ subtract (Subtract) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ mobilenetv2_1.00_160 (Functional) │ (None, 5, 5, 1280) │ 2,257,984 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ global_average_pooling2d │ (None, 1280) │ 0 │
│ (GlobalAveragePooling2D) │ │ │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ dropout (Dropout) │ (None, 1280) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ dense (Dense) │ (None, 1) │ 1,281 │
└──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
Total params: 2,259,265 (8.62 MB)

len(model.trainable_variables)

tf.keras.utils.plot_model(model, show_shapes=True)

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 6/12
AAIEXP7.ipynb - Colab

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 7/12
AAIEXP7.ipynb - Colab

base_learning_rate = 0.0001
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(threshold=0.5, name='accuracy')])

initial_epochs = 10

loss0, accuracy0 = model.evaluate(validation_dataset)

26/26 ━━━━━━━━━━━━━━━━━━━━ 5s 54ms/step - accuracy: 0.6055 - loss: 0.6777

print("initial loss: {:.2f}".format(loss0))


print("initial accuracy: {:.2f}".format(accuracy0))

initial loss: 0.66


initial accuracy: 0.61

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

Epoch 1/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 10s 73ms/step - accuracy: 0.6468 - loss: 0.6489 - val_accuracy: 0.8243 - val_loss: 0.4441
Epoch 2/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 8s 47ms/step - accuracy: 0.7794 - loss: 0.4936 - val_accuracy: 0.9059 - val_loss: 0.3340
Epoch 3/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 6s 68ms/step - accuracy: 0.8381 - loss: 0.4026 - val_accuracy: 0.9307 - val_loss: 0.2627
Epoch 4/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 47ms/step - accuracy: 0.8631 - loss: 0.3437 - val_accuracy: 0.9431 - val_loss: 0.2213
Epoch 5/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.8945 - loss: 0.2939 - val_accuracy: 0.9592 - val_loss: 0.1904
Epoch 6/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 67ms/step - accuracy: 0.8973 - loss: 0.2758 - val_accuracy: 0.9666 - val_loss: 0.1677
Epoch 7/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 49ms/step - accuracy: 0.9222 - loss: 0.2290 - val_accuracy: 0.9641 - val_loss: 0.1537
Epoch 8/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.9138 - loss: 0.2294 - val_accuracy: 0.9666 - val_loss: 0.1441
Epoch 9/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.9057 - loss: 0.2319 - val_accuracy: 0.9641 - val_loss: 0.1368
Epoch 10/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 5s 49ms/step - accuracy: 0.9155 - loss: 0.2064 - val_accuracy: 0.9678 - val_loss: 0.1206

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')

plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 8/12
AAIEXP7.ipynb - Colab

base_model.trainable = True

# Let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(base_model.layers))

# Fine-tune from this layer onwards


fine_tune_at = 100

# Freeze all the layers before the `fine_tune_at` layer


for layer in base_model.layers[:fine_tune_at]:
layer.trainable = False

Number of layers in the base model: 154

model.compile(loss=tf.keras.losses.BinaryCrossentropy(),
optimizer = tf.keras.optimizers.RMSprop(learning_rate=base_learning_rate/10),
metrics=[tf.keras.metrics.BinaryAccuracy(threshold=0.5, name='accuracy')])

model.summary()

Model: "functional_1"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ Layer (type) ┃ Output Shape ┃ Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ input_layer_3 (InputLayer) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ sequential (Sequential) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ true_divide (TrueDivide) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ subtract (Subtract) │ (None, 160, 160, 3) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ mobilenetv2_1.00_160 (Functional) │ (None, 5, 5, 1280) │ 2,257,984 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ global_average_pooling2d │ (None, 1280) │ 0 │
│ (GlobalAveragePooling2D) │ │ │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ dropout (Dropout) │ (None, 1280) │ 0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ dense (Dense) │ (None, 1) │ 1,281 │
└──────────────────────────────────────┴─────────────────────────────┴─────────────────┘

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 9/12
AAIEXP7.ipynb - Colab

history = model.fit(train_dataset,
epochs=initial_epochs,
validation_data=validation_dataset)
Epoch 1/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 10s 73ms/step - accuracy: 0.6468 - loss:
0.6489 - val_accuracy: 0.8243 - val_loss: 0.4441
Epoch 2/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 8s 47ms/step - accuracy: 0.7794 - loss:
0.4936 - val_accuracy: 0.9059 - val_loss: 0.3340
Epoch 3/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 6s 68ms/step - accuracy: 0.8381 - loss:
0.4026 - val_accuracy: 0.9307 - val_loss: 0.2627
Epoch 4/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 47ms/step - accuracy: 0.8631 - loss:
0.3437 - val_accuracy: 0.9431 - val_loss: 0.2213
Epoch 5/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.8945 - loss:
0.2939 - val_accuracy: 0.9592 - val_loss: 0.1904
Epoch 6/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 67ms/step - accuracy: 0.8973 - loss:
0.2758 - val_accuracy: 0.9666 - val_loss: 0.1677
Epoch 7/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 4s 49ms/step - accuracy: 0.9222 - loss:
0.2290 - val_accuracy: 0.9641 - val_loss: 0.1537
Epoch 8/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.9138 - loss:
0.2294 - val_accuracy: 0.9666 - val_loss: 0.1441
Epoch 9/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 3s 47ms/step - accuracy: 0.9057 - loss:
0.2319 - val_accuracy: 0.9641 - val_loss: 0.1368
Epoch 10/10
63/63 ━━━━━━━━━━━━━━━━━━━━ 5s 49ms/step - accuracy: 0.9155 - loss:
0.2064 - val_accuracy: 0.9678 - val_loss: 0.1206

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')

plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 10/12
AAIEXP7.ipynb - Colab

loss, accuracy = model.evaluate(test_dataset)


print('Test accuracy :', accuracy)

6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 45ms/step - accuracy: 0.9883 - loss:


0.0321
Test accuracy : 0.9947916865348816

# Retrieve a batch of images from the test set


image_batch, label_batch = test_dataset.as_numpy_iterator().next()
predictions = model.predict_on_batch(image_batch).flatten()
predictions = tf.where(predictions < 0.5, 0, 1)

print('Predictions:\n', predictions.numpy())
print('Labels:\n', label_batch)

plt.figure(figsize=(10, 10))
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(image_batch[i].astype("uint8"))
plt.title(class_names[predictions[i]])
https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 11/12
AAIEXP7.ipynb - Colab
plt.axis("off")

Predictions:
[0 1 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0]
Labels:
[0 1 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0]

https://colab.research.google.com/drive/1C3arlGCVFI1ghrNaQua2mb_1m8iSIWCc#printMode=true 12/12

You might also like