Skip to content

Commit

Permalink
Example colab for image model retraining with TF Hub in TensorFlow 2.
Browse files Browse the repository at this point in the history
This requires PIP package tensorflow-hub>=0.3.0dev0, to appear soon.

PiperOrigin-RevId: 236598138
  • Loading branch information
TensorFlow Hub Authors authored and arnoegw committed Mar 4, 2019
1 parent 66eef86 commit cfbbc9d
Showing 1 changed file with 354 additions and 0 deletions.
354 changes: 354 additions & 0 deletions examples/colab/tf2_image_retraining.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,354 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "ScitaPqhKtuW"
},
"source": [
"##### Copyright 2019 The TensorFlow Hub Authors.\n",
"\n",
"Licensed under the Apache License, Version 2.0 (the \"License\");"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "jvztxQ6VsK2k"
},
"outputs": [],
"source": [
"# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.\n",
"#\n",
"# 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",
"# http://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.\n",
"# =============================================================================="
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "oYM61xrTsP5d"
},
"source": [
"# TF Hub for TF2: Image Module Retraining (preview)\n",
"\n",
"\u003ctable align=\"left\"\u003e\n",
"\u003ctd align=\"center\"\u003e\n",
" \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_image_retraining.ipynb\"\u003e\n",
" \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003e\u003cbr\u003eRun in Google Colab\n",
" \u003c/a\u003e\n",
"\u003c/td\u003e\n",
"\u003ctd align=\"center\"\u003e\n",
" \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/hub/blob/master/examples/colab/tf2_image_retraining.ipynb\"\u003e\n",
" \u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003e\u003cbr\u003eView source on GitHub\u003c/a\u003e\n",
"\u003c/td\u003e\n",
"\u003c/table\u003e"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "L1otmJgmbahf"
},
"source": [
"This Colab offers a preview of using TensorFlow Hub modules in the native TF2 format with Keras. It uses a pre-trained image feature vector module for classifying five species of flowers, including fine-tuning of the module.\n",
"\n",
"**NOTE:** No stable versions of TF2 and TF Hub for TF2 have been released at this point. This colab needs PIP package `tensorflow-hub\u003e=0.3.0` to run."
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "bL54LWCHt5q5"
},
"source": [
"## Set up library versions for TF2"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "110fGB18UNJn"
},
"outputs": [],
"source": [
"!pip uninstall tf-nightly tensorflow --yes\n",
"!pip install tf-nightly-2.0-preview --quiet"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "FewOCz59V-bd"
},
"outputs": [],
"source": [
"!pip install 'tensorflow-hub\u003e=0.3'"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "dlauq-4FWGZM"
},
"outputs": [],
"source": [
"from __future__ import absolute_import, division, print_function\n",
"\n",
"import os\n",
"\n",
"import matplotlib.pylab as plt\n",
"import numpy as np\n",
"\n",
"import tensorflow as tf\n",
"import tensorflow_hub as hub\n",
"\n",
"print(\"Version: \", tf.__version__)\n",
"print(\"Eager mode: \", tf.executing_eagerly())\n",
"print(\"Hub version: \", hub.__version__)\n",
"print(\"GPU is\", \"available\" if tf.test.is_gpu_available() else \"NOT AVAILABLE\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "mmaHHH7Pvmth"
},
"source": [
"## Select the Hub/TF2 module to use\n",
"\n",
"Hub modules for TF 1.x won't work here, please use one of the selections provided."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "FlsEcKVeuCnf"
},
"outputs": [],
"source": [
"module_selection = (\"mobilenet_v2\", 224, 1280) #@param [\"(\\\"mobilenet_v2\\\", 224, 1280)\", \"(\\\"inception_v3\\\", 299, 2048)\"] {type:\"raw\", allow-input: true}\n",
"handle_base, pixels, FV_SIZE = module_selection\n",
"MODULE_HANDLE =\"https://tfhub.dev/google/tf2-preview/{}/feature_vector/1\".format(handle_base)\n",
"IMAGE_SIZE = (pixels, pixels)\n",
"print(\"Using {} with input size {} and output dimension {}\".format(\n",
" MODULE_HANDLE, IMAGE_SIZE, FV_SIZE))\n",
"\n",
"BATCH_SIZE = 32 #@param {type:\"integer\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "yTY8qzyYv3vl"
},
"source": [
"## Set up the Flowers dataset\n",
"\n",
"Inputs are suitably resized for the selected module."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "WBtFK1hO8KsO"
},
"outputs": [],
"source": [
"data_dir = tf.keras.utils.get_file(\n",
" 'flower_photos',\n",
" 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\n",
" untar=True)"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "BzysZO58YA8H"
},
"outputs": [],
"source": [
"datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n",
" rescale=1./255, validation_split=.20)\n",
"train_generator = datagen.flow_from_directory(\n",
" data_dir, subset=\"training\",\n",
" target_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\n",
"valid_generator = datagen.flow_from_directory(\n",
" data_dir, subset=\"validation\",\n",
" target_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "FS_gVStowW3G"
},
"source": [
"\n",
"## Defining the model\n",
"\n",
"All it takes is to put a linear classifier on top of the `feature_extractor_layer` with the Hub module.\n",
"\n",
"For speed, we start out with a non-trainable `feature_extractor_layer`, but you can also enable fine-tuning for greater accuracy."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "RaJW3XrPyFiF"
},
"outputs": [],
"source": [
"do_fine_tuning = False #@param {type:\"boolean\"}"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "50FYNIb1dmJH"
},
"outputs": [],
"source": [
"print(\"Building model with\", MODULE_HANDLE)\n",
"model = tf.keras.Sequential([\n",
" hub.KerasLayer(MODULE_HANDLE, output_shape=[FV_SIZE],\n",
" trainable=do_fine_tuning),\n",
" tf.keras.layers.Dense(train_generator.num_classes, activation='softmax')\n",
"])\n",
"model.build((None,)+IMAGE_SIZE+(3,))\n",
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "u2e5WupIw2N2"
},
"source": [
"## Training the model"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "9f3yBUvkd_VJ"
},
"outputs": [],
"source": [
"model.compile(\n",
" optimizer=tf.keras.optimizers.Adam(), \n",
" loss='categorical_crossentropy',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "w_YKX2Qnfg6x"
},
"outputs": [],
"source": [
"steps_per_epoch = train_generator.samples // train_generator.batch_size\n",
"validation_steps = valid_generator.samples // valid_generator.batch_size\n",
"hist = model.fit_generator(\n",
" train_generator,\n",
" epochs=5, steps_per_epoch=steps_per_epoch,\n",
" validation_data=valid_generator,\n",
" validation_steps=validation_steps).history"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "CYOw0fTO1W4x"
},
"outputs": [],
"source": [
"plt.figure()\n",
"plt.ylabel(\"Loss (training and validation)\")\n",
"plt.xlabel(\"Training Steps\")\n",
"plt.ylim([0,2])\n",
"plt.plot(hist[\"loss\"])\n",
"plt.plot(hist[\"val_loss\"])\n",
"\n",
"plt.figure()\n",
"plt.ylabel(\"Accuracy (training and validation)\")\n",
"plt.xlabel(\"Training Steps\")\n",
"plt.ylim([0,1])\n",
"plt.plot(hist[\"accuracy\"])\n",
"plt.plot(hist[\"val_accuracy\"])"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [
"ScitaPqhKtuW"
],
"name": "TF Hub for TF2: Image Module Retraining (preview)",
"provenance": [],
"version": "0.3.2"
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

0 comments on commit cfbbc9d

Please sign in to comment.