forked from lmoroney/dlaicourse
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
271 additions
and
0 deletions.
There are no files selected for viewing
271 changes: 271 additions & 0 deletions
271
TensorFlow Deployment/Course 3 - TensorFlow Datasets/Week 2/Examples/Week2ExerciseQ.ipynb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,271 @@ | ||
{ | ||
"nbformat": 4, | ||
"nbformat_minor": 0, | ||
"metadata": { | ||
"colab": { | ||
"name": "Week 2 Exercise Answer.ipynb", | ||
"provenance": [], | ||
"collapsed_sections": [], | ||
"include_colab_link": true | ||
}, | ||
"kernelspec": { | ||
"name": "python3", | ||
"display_name": "Python 3" | ||
}, | ||
"accelerator": "GPU" | ||
}, | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "view-in-github", | ||
"colab_type": "text" | ||
}, | ||
"source": [ | ||
"<a href=\"https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20Deployment/Course%203%20-%20TensorFlow%20Datasets/Week%202/Examples/Week2ExerciseQ.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "zX4Kg8DUTKWO", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", | ||
"# you may not use this file except in compliance with the License.\n", | ||
"# You may obtain a copy of the License at\n", | ||
"#\n", | ||
"# https://www.apache.org/licenses/LICENSE-2.0\n", | ||
"#\n", | ||
"# Unless required by applicable law or agreed to in writing, software\n", | ||
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n", | ||
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", | ||
"# See the License for the specific language governing permissions and\n", | ||
"# limitations under the License." | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"colab_type": "code", | ||
"id": "ioLbtB3uGKPX", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"try:\n", | ||
" # %tensorflow_version only exists in Colab.\n", | ||
" %tensorflow_version 2.x\n", | ||
"except Exception:\n", | ||
" pass" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "HLSSb7Qly6xf", | ||
"colab_type": "text" | ||
}, | ||
"source": [ | ||
"# TRANSFER LEARNING\n", | ||
"The next code block will download the mobilenet model from TensorFlow Hub, and\n", | ||
"use its learned features, extracted as feature_extractor and set to be \n", | ||
"fine tuned by making them trainable.\n" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "tSW2AcBLuiHv", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"import tensorflow_hub as hub\n", | ||
"model_selection = (\"mobilenet_v2\", 224, 1280) \n", | ||
"\n", | ||
"handle_base, pixels, FV_SIZE = model_selection\n", | ||
"\n", | ||
"IMAGE_SIZE = (pixels, pixels)\n", | ||
"\n", | ||
"MODULE_HANDLE =\"https://tfhub.dev/google/tf2-preview/{}/feature_vector/4\".format(handle_base)\n", | ||
"\n", | ||
"feature_extractor = hub.KerasLayer(MODULE_HANDLE,\n", | ||
" input_shape=IMAGE_SIZE + (3,))\n", | ||
"\n", | ||
"feature_extractor.trainable = True " | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "jZ2qZGehzPgM", | ||
"colab_type": "text" | ||
}, | ||
"source": [ | ||
"## Import libraries and set up the splits" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "QGWOsReCW451", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"import tensorflow as tf\n", | ||
"import tensorflow_datasets as tfds\n" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "QUSLZO8IuEtt", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# Here is where you will write your code\n", | ||
"# You need to use subsets of the original data, which is entirely in the 'train'\n", | ||
"# split. I.E. 'train' contains 25000 records.\n", | ||
"# Split this up so that you get\n", | ||
"# The first 10% is your 'new' training set\n", | ||
"# The last 10% is your validation and test sets, split down the middle \n", | ||
"# (i.e. the first half of the last 10% is validation, the second half is test)\n", | ||
"# These 3 recordsets should be called\n", | ||
"# train_examples, validation_examples and test_examples respectively\n", | ||
"\n", | ||
"splits = ['train[:10%]', 'train[90%:95%]', 'train[95%:]']\n", | ||
"splits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split=splits)\n", | ||
"(train_examples, validation_examples, test_examples) = splits" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "LtSJorjivpS9", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"num_examples = 2500\n", | ||
"num_classes = 2" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "nkh5t21-uZFs", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# This will turn the 3 sets into batches\n", | ||
"# so we can train\n", | ||
"# This code should not be changed\n", | ||
"\n", | ||
"def format_image(image, label):\n", | ||
" image = tf.image.resize(image, IMAGE_SIZE) / 255.0\n", | ||
" return image, label\n", | ||
" \n", | ||
"BATCH_SIZE = 32\n", | ||
"\n", | ||
"train_batches = train_examples.shuffle(num_examples).map(format_image).batch(BATCH_SIZE)\n", | ||
"validation_batches = validation_examples.map(format_image).batch(BATCH_SIZE)\n", | ||
"test_batches = test_examples.map(format_image).batch(BATCH_SIZE)" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "rmyQ207suyGY", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# The new model will take the features from the mobilenet via transfer learning\n", | ||
"# And add a new dense layer at the bottom, with 2 classes -- for cats and dogs\n", | ||
"\n", | ||
"model = tf.keras.Sequential([\n", | ||
" feature_extractor,\n", | ||
" tf.keras.layers.Dense(2, activation='softmax')\n", | ||
"])\n", | ||
"\n", | ||
"model.summary()" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "yVFjq8GHu9iN", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# Compile the model with adam optimizer and sparse categorical crossentropy, \n", | ||
"# and track the accuracy metric\n", | ||
" \n", | ||
"model.compile(optimizer='adam',\n", | ||
" loss='sparse_categorical_crossentropy',\n", | ||
" metrics=['accuracy'])" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "dLIwqtilvBcN", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# Train it for a number of epochs. You should not need many\n", | ||
"# Train on the train_Batches, and validation on the validation_batches\n", | ||
"EPOCHS = 5\n", | ||
"\n", | ||
"history = model.fit(train_batches,\n", | ||
" epochs=EPOCHS,\n", | ||
" validation_data=validation_batches)" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"metadata": { | ||
"id": "3jkG0zBHvEnP", | ||
"colab_type": "code", | ||
"colab": {} | ||
}, | ||
"source": [ | ||
"# Evaluate the model on the test batches\n", | ||
"eval_results = model.evaluate(test_batches, verbose=0)\n", | ||
"\n", | ||
"# And print the results. You should have >93% accuracy\n", | ||
"for metric, value in zip(model.metrics_names, eval_results):\n", | ||
" print(metric + ': {:.4}'.format(value))" | ||
], | ||
"execution_count": 0, | ||
"outputs": [] | ||
} | ||
] | ||
} |