{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "TBFXQGKYUc4X" }, "source": [ "##### Copyright 2022 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "1z4xy2gTUc4a" }, "outputs": [], "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." ] }, { "cell_type": "markdown", "metadata": { "id": "KwQtSOz0VrVX" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " View on TensorFlow.org\n", " \n", " Run in Google Colab\n", " \n", " View source on GitHub\n", " \n", " Download notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "L2MHy42s5wl6" }, "source": [ "# Video classification with a 3D convolutional neural network\n", "\n", "This tutorial demonstrates training a 3D convolutional neural network (CNN) for video classification using the [UCF101](https://www.crcv.ucf.edu/data/UCF101.php) action recognition dataset. A 3D CNN uses a three-dimensional filter to perform convolutions. The kernel is able to slide in three directions, whereas in a 2D CNN it can slide in two dimensions. The model is based on the work published in [A Closer Look at Spatiotemporal Convolutions for Action Recognition](https://arxiv.org/abs/1711.11248v3) by D. Tran et al. (2017). In this tutorial, you will:\n", "\n", "* Build an input pipeline\n", "* Build a 3D convolutional neural network model with residual connections using Keras functional API\n", "* Train the model\n", "* Evaluate and test the model\n", "\n", "This video classification tutorial is the second part in a series of TensorFlow video tutorials. Here are the other three tutorials:\n", "\n", "- [Load video data](https://www.tensorflow.org/tutorials/load_data/video): This tutorial explains much of the code used in this document.\n", "- [MoViNet for streaming action recognition](https://www.tensorflow.org/hub/tutorials/movinet): Get familiar with the MoViNet models that are available on TF Hub.\n", "- [Transfer learning for video classification with MoViNet](https://www.tensorflow.org/tutorials/video/transfer_learning_with_movinet): This tutorial explains how to use a pre-trained video classification model trained on a different dataset with the UCF-101 dataset." ] }, { "cell_type": "markdown", "metadata": { "id": "_Ih_df2q0kw4" }, "source": [ "## Setup\n", "\n", "Begin by installing and importing some necessary libraries, including:\n", "[remotezip](https://github.com/gtsystem/python-remotezip) to inspect the contents of a ZIP file, [tqdm](https://github.com/tqdm/tqdm) to use a progress bar, [OpenCV](https://opencv.org/) to process video files, [einops](https://github.com/arogozhnikov/einops/tree/master/docs) for performing more complex tensor operations, and [`tensorflow_docs`](https://github.com/tensorflow/docs/tree/master/tools/tensorflow_docs) for embedding data in a Jupyter notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KEbL4Mwi01PV" }, "outputs": [], "source": [ "!pip install remotezip tqdm opencv-python einops \n", "!pip install -U tensorflow keras" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gg0otuqb0hIf" }, "outputs": [], "source": [ "import tqdm\n", "import random\n", "import pathlib\n", "import itertools\n", "import collections\n", "\n", "import cv2\n", "import einops\n", "import numpy as np\n", "import remotezip as rz\n", "import seaborn as sns\n", "import matplotlib.pyplot as plt\n", "\n", "import tensorflow as tf\n", "import keras\n", "from keras import layers" ] }, { "cell_type": "markdown", "metadata": { "id": "Ctk9A57-6ABq" }, "source": [ "## Load and preprocess video data\n", "\n", "The hidden cell below defines helper functions to download a slice of data from the UCF-101 dataset, and load it into a `tf.data.Dataset`. You can learn more about the specific preprocessing steps in the [Loading video data tutorial](../load_data/video.ipynb), which walks you through this code in more detail.\n", "\n", "The `FrameGenerator` class at the end of the hidden block is the most important utility here. It creates an iterable object that can feed data into the TensorFlow data pipeline. Specifically, this class contains a Python generator that loads the video frames along with its encoded label. The generator (`__call__`) function yields the frame array produced by `frames_from_video_file` and a one-hot encoded vector of the label associated with the set of frames." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nB2aOTU35r9_" }, "outputs": [], "source": [ "#@title\n", "\n", "def list_files_per_class(zip_url):\n", " \"\"\"\n", " List the files in each class of the dataset given the zip URL.\n", "\n", " Args:\n", " zip_url: URL from which the files can be unzipped. \n", "\n", " Return:\n", " files: List of files in each of the classes.\n", " \"\"\"\n", " files = []\n", " with rz.RemoteZip(URL) as zip:\n", " for zip_info in zip.infolist():\n", " files.append(zip_info.filename)\n", " return files\n", "\n", "def get_class(fname):\n", " \"\"\"\n", " Retrieve the name of the class given a filename.\n", "\n", " Args:\n", " fname: Name of the file in the UCF101 dataset.\n", "\n", " Return:\n", " Class that the file belongs to.\n", " \"\"\"\n", " return fname.split('_')[-3]\n", "\n", "def get_files_per_class(files):\n", " \"\"\"\n", " Retrieve the files that belong to each class. \n", "\n", " Args:\n", " files: List of files in the dataset.\n", "\n", " Return:\n", " Dictionary of class names (key) and files (values).\n", " \"\"\"\n", " files_for_class = collections.defaultdict(list)\n", " for fname in files:\n", " class_name = get_class(fname)\n", " files_for_class[class_name].append(fname)\n", " return files_for_class\n", "\n", "def download_from_zip(zip_url, to_dir, file_names):\n", " \"\"\"\n", " Download the contents of the zip file from the zip URL.\n", "\n", " Args:\n", " zip_url: Zip URL containing data.\n", " to_dir: Directory to download data to.\n", " file_names: Names of files to download.\n", " \"\"\"\n", " with rz.RemoteZip(zip_url) as zip:\n", " for fn in tqdm.tqdm(file_names):\n", " class_name = get_class(fn)\n", " zip.extract(fn, str(to_dir / class_name))\n", " unzipped_file = to_dir / class_name / fn\n", "\n", " fn = pathlib.Path(fn).parts[-1]\n", " output_file = to_dir / class_name / fn\n", " unzipped_file.rename(output_file,)\n", "\n", "def split_class_lists(files_for_class, count):\n", " \"\"\"\n", " Returns the list of files belonging to a subset of data as well as the remainder of\n", " files that need to be downloaded.\n", " \n", " Args:\n", " files_for_class: Files belonging to a particular class of data.\n", " count: Number of files to download.\n", "\n", " Return:\n", " split_files: Files belonging to the subset of data.\n", " remainder: Dictionary of the remainder of files that need to be downloaded.\n", " \"\"\"\n", " split_files = []\n", " remainder = {}\n", " for cls in files_for_class:\n", " split_files.extend(files_for_class[cls][:count])\n", " remainder[cls] = files_for_class[cls][count:]\n", " return split_files, remainder\n", "\n", "def download_ufc_101_subset(zip_url, num_classes, splits, download_dir):\n", " \"\"\"\n", " Download a subset of the UFC101 dataset and split them into various parts, such as\n", " training, validation, and test. \n", "\n", " Args:\n", " zip_url: Zip URL containing data.\n", " num_classes: Number of labels.\n", " splits: Dictionary specifying the training, validation, test, etc. (key) division of data \n", " (value is number of files per split).\n", " download_dir: Directory to download data to.\n", "\n", " Return:\n", " dir: Posix path of the resulting directories containing the splits of data.\n", " \"\"\"\n", " files = list_files_per_class(zip_url)\n", " for f in files:\n", " tokens = f.split('/')\n", " if len(tokens) <= 2:\n", " files.remove(f) # Remove that item from the list if it does not have a filename\n", " \n", " files_for_class = get_files_per_class(files)\n", "\n", " classes = list(files_for_class.keys())[:num_classes]\n", "\n", " for cls in classes:\n", " new_files_for_class = files_for_class[cls]\n", " random.shuffle(new_files_for_class)\n", " files_for_class[cls] = new_files_for_class\n", " \n", " # Only use the number of classes you want in the dictionary\n", " files_for_class = {x: files_for_class[x] for x in list(files_for_class)[:num_classes]}\n", "\n", " dirs = {}\n", " for split_name, split_count in splits.items():\n", " print(split_name, \":\")\n", " split_dir = download_dir / split_name\n", " split_files, files_for_class = split_class_lists(files_for_class, split_count)\n", " download_from_zip(zip_url, split_dir, split_files)\n", " dirs[split_name] = split_dir\n", "\n", " return dirs\n", "\n", "def format_frames(frame, output_size):\n", " \"\"\"\n", " Pad and resize an image from a video.\n", " \n", " Args:\n", " frame: Image that needs to resized and padded. \n", " output_size: Pixel size of the output frame image.\n", "\n", " Return:\n", " Formatted frame with padding of specified output size.\n", " \"\"\"\n", " frame = tf.image.convert_image_dtype(frame, tf.float32)\n", " frame = tf.image.resize_with_pad(frame, *output_size)\n", " return frame\n", "\n", "def frames_from_video_file(video_path, n_frames, output_size = (224,224), frame_step = 15):\n", " \"\"\"\n", " Creates frames from each video file present for each category.\n", "\n", " Args:\n", " video_path: File path to the video.\n", " n_frames: Number of frames to be created per video file.\n", " output_size: Pixel size of the output frame image.\n", "\n", " Return:\n", " An NumPy array of frames in the shape of (n_frames, height, width, channels).\n", " \"\"\"\n", " # Read each video frame by frame\n", " result = []\n", " src = cv2.VideoCapture(str(video_path)) \n", "\n", " video_length = src.get(cv2.CAP_PROP_FRAME_COUNT)\n", "\n", " need_length = 1 + (n_frames - 1) * frame_step\n", "\n", " if need_length > video_length:\n", " start = 0\n", " else:\n", " max_start = video_length - need_length\n", " start = random.randint(0, max_start + 1)\n", "\n", " src.set(cv2.CAP_PROP_POS_FRAMES, start)\n", " # ret is a boolean indicating whether read was successful, frame is the image itself\n", " ret, frame = src.read()\n", " result.append(format_frames(frame, output_size))\n", "\n", " for _ in range(n_frames - 1):\n", " for _ in range(frame_step):\n", " ret, frame = src.read()\n", " if ret:\n", " frame = format_frames(frame, output_size)\n", " result.append(frame)\n", " else:\n", " result.append(np.zeros_like(result[0]))\n", " src.release()\n", " result = np.array(result)[..., [2, 1, 0]]\n", "\n", " return result\n", "\n", "class FrameGenerator:\n", " def __init__(self, path, n_frames, training = False):\n", " \"\"\" Returns a set of frames with their associated label. \n", "\n", " Args:\n", " path: Video file paths.\n", " n_frames: Number of frames. \n", " training: Boolean to determine if training dataset is being created.\n", " \"\"\"\n", " self.path = path\n", " self.n_frames = n_frames\n", " self.training = training\n", " self.class_names = sorted(set(p.name for p in self.path.iterdir() if p.is_dir()))\n", " self.class_ids_for_name = dict((name, idx) for idx, name in enumerate(self.class_names))\n", "\n", " def get_files_and_class_names(self):\n", " video_paths = list(self.path.glob('*/*.avi'))\n", " classes = [p.parent.name for p in video_paths] \n", " return video_paths, classes\n", "\n", " def __call__(self):\n", " video_paths, classes = self.get_files_and_class_names()\n", "\n", " pairs = list(zip(video_paths, classes))\n", "\n", " if self.training:\n", " random.shuffle(pairs)\n", "\n", " for path, name in pairs:\n", " video_frames = frames_from_video_file(path, self.n_frames) \n", " label = self.class_ids_for_name[name] # Encode labels\n", " yield video_frames, label" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OYY7PkdJFM4Z" }, "outputs": [], "source": [ "URL = 'https://storage.googleapis.com/thumos14_files/UCF101_videos.zip'\n", "download_dir = pathlib.Path('./UCF101_subset/')\n", "subset_paths = download_ufc_101_subset(URL, \n", " num_classes = 10, \n", " splits = {\"train\": 30, \"val\": 10, \"test\": 10},\n", " download_dir = download_dir)" ] }, { "cell_type": "markdown", "metadata": { "id": "C0O3ttIzpFZJ" }, "source": [ "Create the training, validation, and test sets (`train_ds`, `val_ds`, and `test_ds`)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "lq86IyGDJjTX" }, "outputs": [], "source": [ "n_frames = 10\n", "batch_size = 8\n", "\n", "output_signature = (tf.TensorSpec(shape = (None, None, None, 3), dtype = tf.float32),\n", " tf.TensorSpec(shape = (), dtype = tf.int16))\n", "\n", "train_ds = tf.data.Dataset.from_generator(FrameGenerator(subset_paths['train'], n_frames, training=True),\n", " output_signature = output_signature)\n", "\n", "\n", "# Batch the data\n", "train_ds = train_ds.batch(batch_size)\n", "\n", "val_ds = tf.data.Dataset.from_generator(FrameGenerator(subset_paths['val'], n_frames),\n", " output_signature = output_signature)\n", "val_ds = val_ds.batch(batch_size)\n", "\n", "test_ds = tf.data.Dataset.from_generator(FrameGenerator(subset_paths['test'], n_frames),\n", " output_signature = output_signature)\n", "\n", "test_ds = test_ds.batch(batch_size)" ] }, { "cell_type": "markdown", "metadata": { "id": "nzogoGA4pQW0" }, "source": [ "## Create the model\n", "\n", "The following 3D convolutional neural network model is based off the paper [A Closer Look at Spatiotemporal Convolutions for Action Recognition](https://arxiv.org/abs/1711.11248v3) by D. Tran et al. (2017). The paper compares several versions of 3D ResNets. Instead of operating on a single image with dimensions `(height, width)`, like standard ResNets, these operate on video volume `(time, height, width)`. The most obvious approach to this problem would be replace each 2D convolution (`layers.Conv2D`) with a 3D convolution (`layers.Conv3D`).\n", "\n", "This tutorial uses a (2 + 1)D convolution with [residual connections](https://arxiv.org/abs/1512.03385). The (2 + 1)D convolution allows for the decomposition of the spatial and temporal dimensions, therefore creating two separate steps. An advantage of this approach is that factorizing the convolutions into spatial and temporal dimensions saves parameters. \n", "\n", "For each output location a 3D convolution combines all the vectors from a 3D patch of the volume to create one vector in the output volume.\n", "\n", "![3D convolutions](https://www.tensorflow.org/images/tutorials/video/3DCNN.png)\n", "\n", "This operation is takes `time * height * width * channels` inputs and produces `channels` outputs (assuming the number of input and output channels are the same. So a 3D convolution layer with a kernel size of `(3 x 3 x 3)` would need a weight-matrix with `27 * channels ** 2` entries. The reference paper found that a more effective & efficient approach was to factorize the convolution. Instead of a single 3D convolution to process the time and space dimensions, they proposed a \\\"(2+1)D\\\" convolution which processes the space and time dimensions separately. The figure below shows the factored spatial and temporal convolutions of a (2 + 1)D convolution.\n", "\n", "![(2+1)D convolutions](https://www.tensorflow.org/images/tutorials/video/2plus1CNN.png)\n", "\n", "The main advantage of this approach is that it reduces the number of parameters. In the (2 + 1)D convolution the spatial convolution takes in data of the shape `(1, width, height)`, while the temporal convolution takes in data of the shape `(time, 1, 1)`. For example, a (2 + 1)D convolution with kernel size `(3 x 3 x 3)` would need weight matrices of size `(9 * channels**2) + (3 * channels**2)`, less than half as many as the full 3D convolution. This tutorial implements (2 + 1)D ResNet18, where each convolution in the resnet is replaced by a (2+1)D convolution." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GZcB_7dg-EZJ" }, "outputs": [], "source": [ "# Define the dimensions of one frame in the set of frames created\n", "HEIGHT = 224\n", "WIDTH = 224" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yD_sDIBlNu7K" }, "outputs": [], "source": [ "class Conv2Plus1D(keras.layers.Layer):\n", " def __init__(self, filters, kernel_size, padding):\n", " \"\"\"\n", " A sequence of convolutional layers that first apply the convolution operation over the\n", " spatial dimensions, and then the temporal dimension. \n", " \"\"\"\n", " super().__init__()\n", " self.seq = keras.Sequential([ \n", " # Spatial decomposition\n", " layers.Conv3D(filters=filters,\n", " kernel_size=(1, kernel_size[1], kernel_size[2]),\n", " padding=padding),\n", " # Temporal decomposition\n", " layers.Conv3D(filters=filters, \n", " kernel_size=(kernel_size[0], 1, 1),\n", " padding=padding)\n", " ])\n", " \n", " def call(self, x):\n", " return self.seq(x)" ] }, { "cell_type": "markdown", "metadata": { "id": "I-fCAddqEORZ" }, "source": [ "A ResNet model is made from a sequence of residual blocks.\n", "A residual block has two branches. The main branch performs the calculation, but is difficult for gradients to flow through.\n", "The residual branch bypasses the main calculation and mostly just adds the input to the output of the main branch.\n", "Gradients flow easily through this branch.\n", "Therefore, an easy path from the loss function to any of the residual block's main branch will be present.\n", "This avoids the vanishing gradient problem.\n", "\n", "Create the main branch of the residual block with the following class. In contrast to the standard ResNet structure this uses the custom `Conv2Plus1D` layer instead of `layers.Conv2D`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "tjxAKHwn6mTJ" }, "outputs": [], "source": [ "class ResidualMain(keras.layers.Layer):\n", " \"\"\"\n", " Residual block of the model with convolution, layer normalization, and the\n", " activation function, ReLU.\n", " \"\"\"\n", " def __init__(self, filters, kernel_size):\n", " super().__init__()\n", " self.seq = keras.Sequential([\n", " Conv2Plus1D(filters=filters,\n", " kernel_size=kernel_size,\n", " padding='same'),\n", " layers.LayerNormalization(),\n", " layers.ReLU(),\n", " Conv2Plus1D(filters=filters, \n", " kernel_size=kernel_size,\n", " padding='same'),\n", " layers.LayerNormalization()\n", " ])\n", " \n", " def call(self, x):\n", " return self.seq(x)" ] }, { "cell_type": "markdown", "metadata": { "id": "CevmZ9qsdpWC" }, "source": [ "To add the residual branch to the main branch it needs to have the same size. The `Project` layer below deals with cases where the number of channels is changed on the branch. In particular, a sequence of densely-connected layer followed by normalization is added. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "znrk5BrL6kuq" }, "outputs": [], "source": [ "class Project(keras.layers.Layer):\n", " \"\"\"\n", " Project certain dimensions of the tensor as the data is passed through different \n", " sized filters and downsampled. \n", " \"\"\"\n", " def __init__(self, units):\n", " super().__init__()\n", " self.seq = keras.Sequential([\n", " layers.Dense(units),\n", " layers.LayerNormalization()\n", " ])\n", "\n", " def call(self, x):\n", " return self.seq(x)" ] }, { "cell_type": "markdown", "metadata": { "id": "S8zycXGvfnak" }, "source": [ "Use `add_residual_block` to introduce a skip connection between the layers of the model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "urjVgqvw-TlB" }, "outputs": [], "source": [ "def add_residual_block(input, filters, kernel_size):\n", " \"\"\"\n", " Add residual blocks to the model. If the last dimensions of the input data\n", " and filter size does not match, project it such that last dimension matches.\n", " \"\"\"\n", " out = ResidualMain(filters, \n", " kernel_size)(input)\n", " \n", " res = input\n", " # Using the Keras functional APIs, project the last dimension of the tensor to\n", " # match the new filter size\n", " if out.shape[-1] != input.shape[-1]:\n", " res = Project(out.shape[-1])(res)\n", "\n", " return layers.add([res, out])" ] }, { "cell_type": "markdown", "metadata": { "id": "bozog_0hFKrD" }, "source": [ "Resizing the video is necessary to perform downsampling of the data. In particular, downsampling the video frames allow for the model to examine specific parts of frames to detect patterns that may be specific to a certain action. Through downsampling, non-essential information can be discarded. Moreoever, resizing the video will allow for dimensionality reduction and therefore faster processing through the model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "lQOWuc2I-QqK" }, "outputs": [], "source": [ "class ResizeVideo(keras.layers.Layer):\n", " def __init__(self, height, width):\n", " super().__init__()\n", " self.height = height\n", " self.width = width\n", " self.resizing_layer = layers.Resizing(self.height, self.width)\n", "\n", " def call(self, video):\n", " \"\"\"\n", " Use the einops library to resize the tensor. \n", " \n", " Args:\n", " video: Tensor representation of the video, in the form of a set of frames.\n", " \n", " Return:\n", " A downsampled size of the video according to the new height and width it should be resized to.\n", " \"\"\"\n", " # b stands for batch size, t stands for time, h stands for height, \n", " # w stands for width, and c stands for the number of channels.\n", " old_shape = einops.parse_shape(video, 'b t h w c')\n", " images = einops.rearrange(video, 'b t h w c -> (b t) h w c')\n", " images = self.resizing_layer(images)\n", " videos = einops.rearrange(\n", " images, '(b t) h w c -> b t h w c',\n", " t = old_shape['t'])\n", " return videos" ] }, { "cell_type": "markdown", "metadata": { "id": "Z9IqzCq--Uu9" }, "source": [ "Use the [Keras functional API](https://www.tensorflow.org/guide/keras/functional) to build the residual network." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_bROfh_K-Wxs" }, "outputs": [], "source": [ "input_shape = (None, 10, HEIGHT, WIDTH, 3)\n", "input = layers.Input(shape=(input_shape[1:]))\n", "x = input\n", "\n", "x = Conv2Plus1D(filters=16, kernel_size=(3, 7, 7), padding='same')(x)\n", "x = layers.BatchNormalization()(x)\n", "x = layers.ReLU()(x)\n", "x = ResizeVideo(HEIGHT // 2, WIDTH // 2)(x)\n", "\n", "# Block 1\n", "x = add_residual_block(x, 16, (3, 3, 3))\n", "x = ResizeVideo(HEIGHT // 4, WIDTH // 4)(x)\n", "\n", "# Block 2\n", "x = add_residual_block(x, 32, (3, 3, 3))\n", "x = ResizeVideo(HEIGHT // 8, WIDTH // 8)(x)\n", "\n", "# Block 3\n", "x = add_residual_block(x, 64, (3, 3, 3))\n", "x = ResizeVideo(HEIGHT // 16, WIDTH // 16)(x)\n", "\n", "# Block 4\n", "x = add_residual_block(x, 128, (3, 3, 3))\n", "\n", "x = layers.GlobalAveragePooling3D()(x)\n", "x = layers.Flatten()(x)\n", "x = layers.Dense(10)(x)\n", "\n", "model = keras.Model(input, x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TiO0WylG-ZHM" }, "outputs": [], "source": [ "frames, label = next(iter(train_ds))\n", "model.build(frames)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GAsKrM8r-bKM" }, "outputs": [], "source": [ "# Visualize the model\n", "keras.utils.plot_model(model, expand_nested=True, dpi=60, show_shapes=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "1yvJJPnY-dMP" }, "source": [ "## Train the model\n", "\n", "For this tutorial, choose the `tf.keras.optimizers.Adam` optimizer and the `tf.keras.losses.SparseCategoricalCrossentropy` loss function. Use the `metrics` argument to the view the accuracy of the model performance at every step." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ejrbyebDp2tA" }, "outputs": [], "source": [ "model.compile(loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True), \n", " optimizer = keras.optimizers.Adam(learning_rate = 0.0001), \n", " metrics = ['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "id": "nZT1Xlx9stP2" }, "source": [ "Train the model for 50 epoches with the Keras `Model.fit` method.\n", "\n", "Note: This example model is trained on fewer data points (300 training and 100 validation examples) to keep training time reasonable for this tutorial. Moreover, this example model may take over one hour to train." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "VMrMUl2hOqMs" }, "outputs": [], "source": [ "history = model.fit(x = train_ds,\n", " epochs = 50, \n", " validation_data = val_ds)" ] }, { "cell_type": "markdown", "metadata": { "id": "KKUfMNVns2hu" }, "source": [ "### Visualize the results\n", "\n", "Create plots of the loss and accuracy on the training and validation sets:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Cd5tpNrtOrs7" }, "outputs": [], "source": [ "def plot_history(history):\n", " \"\"\"\n", " Plotting training and validation learning curves.\n", "\n", " Args:\n", " history: model history with all the metric measures\n", " \"\"\"\n", " fig, (ax1, ax2) = plt.subplots(2)\n", "\n", " fig.set_size_inches(18.5, 10.5)\n", "\n", " # Plot loss\n", " ax1.set_title('Loss')\n", " ax1.plot(history.history['loss'], label = 'train')\n", " ax1.plot(history.history['val_loss'], label = 'test')\n", " ax1.set_ylabel('Loss')\n", " \n", " # Determine upper bound of y-axis\n", " max_loss = max(history.history['loss'] + history.history['val_loss'])\n", "\n", " ax1.set_ylim([0, np.ceil(max_loss)])\n", " ax1.set_xlabel('Epoch')\n", " ax1.legend(['Train', 'Validation']) \n", "\n", " # Plot accuracy\n", " ax2.set_title('Accuracy')\n", " ax2.plot(history.history['accuracy'], label = 'train')\n", " ax2.plot(history.history['val_accuracy'], label = 'test')\n", " ax2.set_ylabel('Accuracy')\n", " ax2.set_ylim([0, 1])\n", " ax2.set_xlabel('Epoch')\n", " ax2.legend(['Train', 'Validation'])\n", "\n", " plt.show()\n", "\n", "plot_history(history)" ] }, { "cell_type": "markdown", "metadata": { "id": "EJrGF0Sss8E0" }, "source": [ "## Evaluate the model\n", "\n", "Use Keras `Model.evaluate` to get the loss and accuracy on the test dataset. \n", "\n", "Note: The example model in this tutorial uses a subset of the UCF101 dataset to keep training time reasonable. The accuracy and loss can be improved with further hyperparameter tuning or more training data. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Hev0hMCxOtfy" }, "outputs": [], "source": [ "model.evaluate(test_ds, return_dict=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "-F73GxD1-yc8" }, "source": [ "To visualize model performance further, use a [confusion matrix](https://www.tensorflow.org/api_docs/python/tf/math/confusion_matrix). The confusion matrix allows you to assess the performance of the classification model beyond accuracy. In order to build the confusion matrix for this multi-class classification problem, get the actual values in the test set and the predicted values. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Yw-6rG5V-0L-" }, "outputs": [], "source": [ "def get_actual_predicted_labels(dataset): \n", " \"\"\"\n", " Create a list of actual ground truth values and the predictions from the model.\n", "\n", " Args:\n", " dataset: An iterable data structure, such as a TensorFlow Dataset, with features and labels.\n", "\n", " Return:\n", " Ground truth and predicted values for a particular dataset.\n", " \"\"\"\n", " actual = [labels for _, labels in dataset.unbatch()]\n", " predicted = model.predict(dataset)\n", "\n", " actual = tf.stack(actual, axis=0)\n", " predicted = tf.concat(predicted, axis=0)\n", " predicted = tf.argmax(predicted, axis=1)\n", "\n", " return actual, predicted" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "aln6qWW_-2dk" }, "outputs": [], "source": [ "def plot_confusion_matrix(actual, predicted, labels, ds_type):\n", " cm = tf.math.confusion_matrix(actual, predicted)\n", " ax = sns.heatmap(cm, annot=True, fmt='g')\n", " sns.set(rc={'figure.figsize':(12, 12)})\n", " sns.set(font_scale=1.4)\n", " ax.set_title('Confusion matrix of action recognition for ' + ds_type)\n", " ax.set_xlabel('Predicted Action')\n", " ax.set_ylabel('Actual Action')\n", " plt.xticks(rotation=90)\n", " plt.yticks(rotation=0)\n", " ax.xaxis.set_ticklabels(labels)\n", " ax.yaxis.set_ticklabels(labels)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "tfQ3VAGd-4Az" }, "outputs": [], "source": [ "fg = FrameGenerator(subset_paths['train'], n_frames, training=True)\n", "labels = list(fg.class_ids_for_name.keys())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1ucGpbiA-5qi" }, "outputs": [], "source": [ "actual, predicted = get_actual_predicted_labels(train_ds)\n", "plot_confusion_matrix(actual, predicted, labels, 'training')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Mfr7AT5T-7ZD" }, "outputs": [], "source": [ "actual, predicted = get_actual_predicted_labels(test_ds)\n", "plot_confusion_matrix(actual, predicted, labels, 'test')" ] }, { "cell_type": "markdown", "metadata": { "id": "FefzeIZz-9aI" }, "source": [ "The precision and recall values for each class can also be calculated using a confusion matrix." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "dq95-56Z-_E2" }, "outputs": [], "source": [ "def calculate_classification_metrics(y_actual, y_pred, labels):\n", " \"\"\"\n", " Calculate the precision and recall of a classification model using the ground truth and\n", " predicted values. \n", "\n", " Args:\n", " y_actual: Ground truth labels.\n", " y_pred: Predicted labels.\n", " labels: List of classification labels.\n", "\n", " Return:\n", " Precision and recall measures.\n", " \"\"\"\n", " cm = tf.math.confusion_matrix(y_actual, y_pred)\n", " tp = np.diag(cm) # Diagonal represents true positives\n", " precision = dict()\n", " recall = dict()\n", " for i in range(len(labels)):\n", " col = cm[:, i]\n", " fp = np.sum(col) - tp[i] # Sum of column minus true positive is false negative\n", " \n", " row = cm[i, :]\n", " fn = np.sum(row) - tp[i] # Sum of row minus true positive, is false negative\n", " \n", " precision[labels[i]] = tp[i] / (tp[i] + fp) # Precision \n", " \n", " recall[labels[i]] = tp[i] / (tp[i] + fn) # Recall\n", " \n", " return precision, recall" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4jSEonYQ_BZt" }, "outputs": [], "source": [ "precision, recall = calculate_classification_metrics(actual, predicted, labels) # Test dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hXvTW1Df_DV8" }, "outputs": [], "source": [ "precision" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "be1yrQl5_EYF" }, "outputs": [], "source": [ "recall" ] }, { "cell_type": "markdown", "metadata": { "id": "d4WsP4Z2HZ6L" }, "source": [ "## Next steps\n", "\n", "To learn more about working with video data in TensorFlow, check out the following tutorials:\n", "\n", "* [Load video data](https://www.tensorflow.org/tutorials/load_data/video)\n", "* [MoViNet for streaming action recognition](https://www.tensorflow.org/hub/tutorials/movinet)\n", "* [Transfer learning for video classification with MoViNet](https://www.tensorflow.org/tutorials/video/transfer_learning_with_movinet)" ] } ], "metadata": { "accelerator": "GPU", "colab": { "name": "video_classification.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }