<jupyter_start><jupyter_text>**Setup**<jupyter_code>import itertools
import os
import matplotlib.pylab as plt

import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
import numpy as np<jupyter_output><empty_output><jupyter_text>**Load DataSet**<jupyter_code>data_dir = tf.keras.utils.get_file(
    'flower_photos',
    'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
    untar=True)<jupyter_output>Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz
228818944/228813984 [==============================] - 4s 0us/step<jupyter_text>**Pre-processing Data**<jupyter_code>IMAGE_SIZE = (224, 224)
BATCH_SIZE = 32
datagen_kwargs = dict(rescale=1./255, validation_split=.20)
dataflow_kwargs = dict(target_size=IMAGE_SIZE, batch_size=BATCH_SIZE,
                   interpolation="bilinear")

valid_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    **datagen_kwargs)
valid_generator = valid_datagen.flow_from_directory(
    data_dir, subset="validation", shuffle=False, **dataflow_kwargs)

do_data_augmentation = True 
if do_data_augmentation:
  train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
      rotation_range=40,
      horizontal_flip=True,
      width_shift_range=0.2, height_shift_range=0.2,
      shear_range=0.2, zoom_range=0.2,
      **datagen_kwargs)
else:
  train_datagen = valid_datagen
train_generator = train_datagen.flow_from_directory(
    data_dir, subset="training", shuffle=True, **dataflow_kwargs)<jupyter_output>Found 731 images belonging to 5 classes.
Found 2939 images belonging to 5 classes.<jupyter_text>**Transfer Learning to Build Model**<jupyter_code>model = Sequential()
model.add(MobileNetV2(include_top = False, weights="imagenet", input_shape=(224, 224, 3)))
model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(Dense(1, activation = 'softmax'))
model.layers[0].trainable = False<jupyter_output>Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top.h5
9412608/9406464 [==============================] - 0s 0us/step<jupyter_text>**Summary of Updated Model**<jupyter_code>model.summary()<jupyter_output>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
mobilenetv2_1.00_224 (Functi (None, 7, 7, 1280)        2257984   
_________________________________________________________________
global_average_pooling2d (Gl (None, 1280)              0         
_________________________________________________________________
dense (Dense)                (None, 1)                 1281      
=================================================================
Total params: 2,259,265
Trainable params: 1,281
Non-trainable params: 2,257,984
_________________________________________________________________<jupyter_text>**Compile the Model**<jupyter_code>from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras import optimizers


model.compile(optimizer=RMSprop(lr=0.005), loss = 'categorical_crossentropy', metrics = 'accuracy')<jupyter_output><empty_output><jupyter_text>**Train the Model**<jupyter_code>steps_per_epoch = train_generator.samples // train_generator.batch_size
validation_steps = valid_generator.samples // valid_generator.batch_size
hist = model.fit(
    train_generator,
    epochs=5, steps_per_epoch=steps_per_epoch,
    validation_data=valid_generator,
    validation_steps=validation_steps).history<jupyter_output>Epoch 1/5
91/91 [==============================] - 83s 565ms/step - loss: 1.2431 - accuracy: 0.8342 - val_loss: 0.6834 - val_accuracy: 0.9148
Epoch 2/5
91/91 [==============================] - 51s 559ms/step - loss: 0.5575 - accuracy: 0.9297 - val_loss: 0.6170 - val_accuracy: 0.9202
Epoch 3/5
91/91 [==============================] - 51s 561ms/step - loss: 0.4656 - accuracy: 0.9378 - val_loss: 0.5212 - val_accuracy: 0.9480
Epoch 4/5
91/91 [==============================] - 51s 559ms/step - loss: 0.4775 - accuracy: 0.9405 - val_loss: 0.5768 - val_accuracy: 0.9369
Epoch 5/5
91/91 [==============================] - 51s 559ms/step - loss: 0.4205 - accuracy: 0.9474 - val_loss: 0.5294 - val_accuracy: 0.9466<jupyter_text>**Test Accuracy of Model  on the validation data**<jupyter_code>model.evaluate(valid_generator)<jupyter_output>23/23 [==============================] - 4s 179ms/step - loss: 0.5225 - accuracy: 0.9475<jupyter_text>**Prediction using Model**<jupyter_code>def get_class_string_from_index(index):
   for class_string, class_index in valid_generator.class_indices.items():
      if class_index == index:
         return class_string

x, y = next(valid_generator)
image = x[0, :, :, :]
true_index = np.argmax(y[0])
plt.imshow(image)
plt.axis('off')
plt.show()

# Expand the validation image to (1, 224, 224, 3) before predicting the label
prediction_scores = model.predict(np.expand_dims(image, axis=0))
predicted_index = np.argmax(prediction_scores)
print("True label: " + get_class_string_from_index(true_index))
print("Predicted label: " + get_class_string_from_index(predicted_index))<jupyter_output><empty_output><jupyter_text>**Save the Model**<jupyter_code>saved_model_path = f"/content"
tf.saved_model.save(model, saved_model_path)<jupyter_output>INFO:tensorflow:Assets written to: /content/assets
StarcoderdataJupyterStructuredCleanDedup