Angad Sandhu
Search
Browse
On this page

Week2ExerciseA

Open In Colab

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass

TRANSFER LEARNING

The next code block will download the mobilenet model from TensorFlow Hub, and use its learned features, extracted as feature_extractor and set to be fine tuned by making them trainable.

import tensorflow_hub as hub
model_selection = ("mobilenet_v2", 224, 1280) 

handle_base, pixels, FV_SIZE = model_selection

IMAGE_SIZE = (pixels, pixels)

MODULE_HANDLE ="https://tfhub.dev/google/tf2-preview/{}/feature_vector/4".format(handle_base)

feature_extractor = hub.KerasLayer(MODULE_HANDLE,
                                   input_shape=IMAGE_SIZE + (3,))

feature_extractor.trainable = True  

Import libraries and set up the splits

import tensorflow as tf
import tensorflow_datasets as tfds
# Here is where you will write your code
# You need to use subsets of the original data, which is entirely in the 'train'
# split. I.E. 'train' contains 25000 records.
# Split this up so that you get
# The first 10% is your 'new' training set
# The last 10% is your validation and test sets, split down the middle 
# (i.e. the first half of the last 10% is validation, the second half is test)
# These 3 recordsets should be called
# train_examples, validation_examples and test_examples respectively

splits = ['train[:10%]', 'train[90%:95%]', 'train[95%:]']
splits, info = tfds.load('cats_vs_dogs', split = splits, with_info=True)
(train_examples, validation_examples, test_examples) = splits
num_examples = 2500
num_classes = 2
# This will turn the 3 sets into batches
# so we can train
# This code should not be changed

def format_image(features):
  image = features['image']
  image = tf.image.resize(image, IMAGE_SIZE) / 255.0
  return  image, features['label']
    
BATCH_SIZE =  32

train_batches = train_examples.shuffle(num_examples).map(format_image).batch(BATCH_SIZE)
validation_batches = validation_examples.map(format_image).batch(BATCH_SIZE)
test_batches = test_examples.map(format_image).batch(BATCH_SIZE)
# The new model will take the features from the mobilenet via transfer learning
# And add a new dense layer at the bottom, with 2 classes -- for cats and dogs

model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(2, activation='softmax')
])

model.summary()
# Compile the model with adam optimizer and sparse categorical crossentropy, 
# and track the accuracy metric
    
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])
# Train it for a number of epochs. You should not need many
# Train on the train_Batches, and validation on the validation_batches
EPOCHS = 10

history = model.fit(train_batches, epochs=EPOCHS, validation_data=validation_batches)
# Evaluate the model on the test batches
eval_results = model.evaluate(test_batches)

# And print the results. You should have >93% accuracy
for metric, value in zip(model.metrics_names, eval_results):
    print(metric + ': {:.4}'.format(value))

Browse the library