Human Pose Classification with MoveNet and TensorFlow Lite

This notebook teaches you how to train a pose classification model using MoveNet and TensorFlow Lite. The result is a new TensorFlow Lite model that accepts the output from the MoveNet model as its input, and outputs a pose classification, such as the name of a yoga pose.

The procedure in this notebook consists of 3 parts:

  • Part 1: Preprocess the pose classification training data into a CSV file that specifies the landmarks (body keypoints) detected by the MoveNet model, along with the ground truth pose labels.
  • Part 2: Build and train a pose classification model that takes the landmark coordinates from the CSV file as input, and outputs the predicted labels.
  • Part 3: Convert the pose classification model to TFLite.

By default, this notebook uses an image dataset with labeled yoga poses, but we've also included a section in Part 1 where you can upload your own image dataset of poses.

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook See TF Hub model

Preparation

In this section, you'll import the necessary libraries and define several functions to preprocess the training images into a CSV file that contains the landmark coordinates and ground truth labels.

Nothing observable happens here, but you can expand the hidden code cells to see the implementation for some of the functions we'll be calling later on.

If you only want to create the CSV file without knowing all the details, just run this section and proceed to Part 1.

pip install -q opencv-python
import csv
import cv2
import itertools
import numpy as np
import pandas as pd
import os
import sys
import tempfile
import tqdm

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

import tensorflow as tf
import tensorflow_hub as hub
from tensorflow import keras

from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

Code to run pose estimation using MoveNet

Functions to run pose estimation with MoveNet

Cloning into 'examples'...
remote: Enumerating objects: 18837, done.[K
remote: Counting objects: 100% (657/657), done.[K
remote: Compressing objects: 100% (394/394), done.[K
remote: Total 18837 (delta 261), reused 531 (delta 160), pack-reused 18180[K
Receiving objects: 100% (18837/18837), 30.47 MiB | 15.88 MiB/s, done.
Resolving deltas: 100% (10355/10355), done.

Functions to visualize the pose estimation results.

Code to load the images, detect pose landmarks and save them into a CSV file

(Optional) Code snippet to try out the Movenet pose estimation logic

--2021-09-01 02:18:11--  https://cdn.pixabay.com/photo/2017/03/03/17/30/yoga-2114512_960_720.jpg
Resolving cdn.pixabay.com (cdn.pixabay.com)... 104.18.21.183, 104.18.20.183, 2606:4700::6812:15b7, ...
Connecting to cdn.pixabay.com (cdn.pixabay.com)|104.18.21.183|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 28665 (28K) [image/jpeg]
Saving to: ‘/tmp/image.jpeg’

/tmp/image.jpeg     100%[===================>]  27.99K  --.-KB/s    in 0s      

2021-09-01 02:18:12 (102 MB/s) - ‘/tmp/image.jpeg’ saved [28665/28665]

png

Part 1: Preprocess the input images

Because the input for our pose classifier is the output landmarks from the MoveNet model, we need to generate our training dataset by running labeled images through MoveNet and then capturing all the landmark data and ground truth labels into a CSV file.

The dataset we've provided for this tutorial is a CG-generated yoga pose dataset. It contains images of multiple CG-generated models doing 5 different yoga poses. The directory is already split into a train dataset and a test dataset.

So in this section, we'll download the yoga dataset and run it through MoveNet so we can capture all the landmarks into a CSV file... However, it takes about 15 minutes to feed our yoga dataset to MoveNet and generate this CSV file. So as an alternative, you can download a pre-existing CSV file for the yoga dataset by setting is_skip_step_1 parameter below to True. That way, you'll skip this step and instead download the same CSV file that will be created in this preprocessing step.

On the other hand, if you want to train the pose classifier with your own image dataset, you need to upload your images and run this preprocessing step (leave is_skip_step_1 False)—follow the instructions below to upload your own pose dataset.

(Optional) Upload your own pose dataset

If you want to train the pose classifier with your own labeled poses (they can be any poses, not just yoga poses), follow these steps:

  1. Set the above use_custom_dataset option to True.

  2. Prepare an archive file (ZIP, TAR, or other) that includes a folder with your images dataset. The folder must include sorted images of your poses as follows.

    If you've already split your dataset into train and test sets, then set dataset_is_split to True. That is, your images folder must include "train" and "test" directories like this:

    yoga_poses/
    |__ train/
        |__ downdog/
            |______ 00000128.jpg
            |______ ...
    |__ test/
        |__ downdog/
            |______ 00000181.jpg
            |______ ...
    

    Or, if your dataset is NOT split yet, then set dataset_is_split to False and we'll split it up based on a specified split fraction. That is, your uploaded images folder should look like this:

    yoga_poses/
    |__ downdog/
        |______ 00000128.jpg
        |______ 00000181.jpg
        |______ ...
    |__ goddess/
        |______ 00000243.jpg
        |______ 00000306.jpg
        |______ ...
    
  3. Click the Files tab on the left (folder icon) and then click Upload to session storage (file icon).

  4. Select your archive file and wait until it finishes uploading before you proceed.

  5. Edit the following code block to specify the name of your archive file and images directory. (By default, we expect a ZIP file, so you'll need to also modify that part if your archive is another format.)

  6. Now run the rest of the notebook.

if use_custom_dataset:
  # ATTENTION:
  # You must edit these two lines to match your archive and images folder name:
  # !tar -xf YOUR_DATASET_ARCHIVE_NAME.tar
  !unzip -q YOUR_DATASET_ARCHIVE_NAME.zip
  dataset_in = 'YOUR_DATASET_DIR_NAME'

  # You can leave the rest alone:
  if not os.path.isdir(dataset_in):
    raise Exception("dataset_in is not a valid directory")
  if dataset_is_split:
    IMAGES_ROOT = dataset_in
  else:
    dataset_out = 'split_' + dataset_in
    split_into_train_test(dataset_in, dataset_out, test_split=0.2)
    IMAGES_ROOT = dataset_out

Download the yoga dataset

if not is_skip_step_1 and not use_custom_dataset:
  !wget -O yoga_poses.zip http://download.tensorflow.org/data/pose_classification/yoga_poses.zip
  !unzip -q yoga_poses.zip -d yoga_cg
  IMAGES_ROOT = "yoga_cg"
--2021-09-01 02:18:22--  http://download.tensorflow.org/data/pose_classification/yoga_poses.zip
Resolving download.tensorflow.org (download.tensorflow.org)... 74.125.204.128, 2404:6800:4008:c04::80
Connecting to download.tensorflow.org (download.tensorflow.org)|74.125.204.128|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 102517581 (98M) [application/zip]
Saving to: ‘yoga_poses.zip’

yoga_poses.zip      100%[===================>]  97.77M  84.9MB/s    in 1.2s    

2021-09-01 02:18:24 (84.9 MB/s) - ‘yoga_poses.zip’ saved [102517581/102517581]

Preprocess the TRAIN dataset

if not is_skip_step_1:
  images_in_train_folder = os.path.join(IMAGES_ROOT, 'train')
  images_out_train_folder = 'poses_images_out_train'
  csvs_out_train_path = 'train_data.csv'

  preprocessor = MoveNetPreprocessor(
      images_in_folder=images_in_train_folder,
      images_out_folder=images_out_train_folder,
      csvs_out_path=csvs_out_train_path,
  )

  preprocessor.process(per_pose_class_limit=None)
Preprocessing chair
100%|██████████| 200/200 [01:01<00:00,  3.23it/s]
Preprocessing cobra
100%|██████████| 200/200 [00:56<00:00,  3.53it/s]
Preprocessing dog
100%|██████████| 200/200 [01:00<00:00,  3.30it/s]
Preprocessing tree
100%|██████████| 200/200 [00:58<00:00,  3.40it/s]
Preprocessing warrior
100%|██████████| 200/200 [00:59<00:00,  3.34it/s]
Skipped yoga_cg/train/cobra/girl1_cobra087.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra088.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra089.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra090.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra091.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra092.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra093.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra094.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra096.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra099.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra102.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra110.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra112.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra115.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra119.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra122.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra128.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra129.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra136.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra137.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl1_cobra140.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl2_cobra069.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl2_cobra078.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl2_cobra108.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl2_cobra117.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl2_cobra120.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra072.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra078.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra079.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra082.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra130.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra134.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/cobra/girl3_cobra138.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree086.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree087.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree088.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree089.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree090.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree094.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree096.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree099.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree100.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl1_tree101.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/tree/girl2_tree085.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/girl3_warrior090.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior134.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior135.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior138.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior143.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior145.jpg. No pose was confidentlly detected.
Skipped yoga_cg/train/warrior/guy1_warrior148.jpg. No pose was confidentlly detected.

Preprocess the TEST dataset

if not is_skip_step_1:
  images_in_test_folder = os.path.join(IMAGES_ROOT, 'test')
  images_out_test_folder = 'poses_images_out_test'
  csvs_out_test_path = 'test_data.csv'

  preprocessor = MoveNetPreprocessor(
      images_in_folder=images_in_test_folder,
      images_out_folder=images_out_test_folder,
      csvs_out_path=csvs_out_test_path,
  )

  preprocessor.process(per_pose_class_limit=None)
Preprocessing chair
100%|██████████| 84/84 [00:25<00:00,  3.34it/s]
Preprocessing cobra
100%|██████████| 116/116 [00:38<00:00,  3.01it/s]
Preprocessing dog
100%|██████████| 90/90 [00:27<00:00,  3.26it/s]
Preprocessing tree
100%|██████████| 96/96 [00:23<00:00,  4.06it/s]
Preprocessing warrior
100%|██████████| 109/109 [00:33<00:00,  3.27it/s]
Skipped yoga_cg/test/tree/guy3_tree089.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree090.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree091.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree092.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree093.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree094.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree095.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree096.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree097.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree098.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree099.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree100.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree101.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree102.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree103.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree104.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree105.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree106.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree107.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree108.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree109.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree110.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree111.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree112.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree113.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree114.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree115.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree116.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree117.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree118.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree119.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree120.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree121.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree122.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree123.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree124.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree125.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree126.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree127.jpg. No pose was confidentlly detected.
Skipped yoga_cg/test/tree/guy3_tree128.jpg. No pose was confidentlly detected.

Part 2: Train a pose classification model that takes the landmark coordinates as input, and output the predicted labels.

You'll build a TensorFlow model that takes the landmark coordinates and predicts the pose class that the person in the input image performs. The model consists of two submodels:

  • Submodel 1 calculates a pose embedding (a.k.a feature vector) from the detected landmark coordinates.
  • Submodel 2 feeds pose embedding through several Dense layer to predict the pose class.

You'll then train the model based on the dataset that were preprocessed in part 1.

(Optional) Download the preprocessed dataset if you didn't run part 1

# Download the preprocessed CSV files which are the same as the output of step 1
if is_skip_step_1:
  !wget -O train_data.csv http://download.tensorflow.org/data/pose_classification/yoga_train_data.csv
  !wget -O test_data.csv http://download.tensorflow.org/data/pose_classification/yoga_test_data.csv

  csvs_out_train_path = 'train_data.csv'
  csvs_out_test_path = 'test_data.csv'
  is_skipped_step_1 = True

Load the preprocessed CSVs into TRAIN and TEST datasets.

def load_pose_landmarks(csv_path):
  """Loads a CSV created by from the MoveNetPreprocessor.

  Returns:
    X: Detected landmark coordinates and scores of shape (N, 17 * 3)
    y: Ground truth labels of shape of shape (N, label_count)
    classes: The list of all class names found in the dataset
    dataframe: The CSV loaded as a Pandas dataframe features (X) and ground
      truth labels (y) to use later to train a pose classification model.
  """

  # Load the CSV file
  dataframe = pd.read_csv(csv_path)
  df_to_process = dataframe.copy()

  # Drop the file_name columns as you don't need it during training.
  df_to_process.drop(columns=['file_name'], inplace=True)

  # Extract the list of class names
  classes = df_to_process.pop('class_name').unique()

  # Extract the labels
  y = df_to_process.pop('class_no')

  # Convert the input features and labels into the correct format for training.
  X = df_to_process.astype('float64')
  y = keras.utils.to_categorical(y)

  return X, y, classes, dataframe

Load and split the original TRAIN dataset into TRAIN (85% of the data) and VALIDATE (the remaining 15%).

# Load the train data
X, y, class_names, _ = load_pose_landmarks(csvs_out_train_path)

# Split training data (X, y) into (X_train, y_train) and (X_val, y_val)
X_train, X_val, y_train, y_val = train_test_split(X, y,
                                                  test_size=0.15)
# Load the test data
X_test, y_test, _, df_test = load_pose_landmarks(csvs_out_test_path)

Define functions to convert the pose landmarks to a pose embedding (a.k.a. feature vector) for pose classification

Next, convert the landmark coordinates to a feature vector by:

  1. Moving the pose center to the origin.
  2. Scaling the pose so that the pose size becomes 1
  3. Flattening these coordinates into a feature vector

Then use this feature vector to train a neural-network based pose classifier.

def get_center_point(landmarks, left_name, right_name):
  """Calculates the center point of the two given landmarks."""

  left = tf.gather(landmarks, utils.KEYPOINT_DICT[left_name], axis=1)
  right = tf.gather(landmarks, utils.KEYPOINT_DICT[right_name], axis=1)
  center = left * 0.5 + right * 0.5
  return center


def get_pose_size(landmarks, torso_size_multiplier=2.5):
  """Calculates pose size.

  It is the maximum of two values:

    * Torso size multiplied by `torso_size_multiplier`
    * Maximum distance from pose center to any pose landmark
  """
  # Hips center
  hips_center = get_center_point(landmarks, "left_hip", "right_hip")

  # Shoulders center
  shoulders_center = get_center_point(landmarks, 
                                      "left_shoulder", "right_shoulder")

  # Torso size as the minimum body size
  torso_size = tf.linalg.norm(shoulders_center - hips_center)

  # Pose center
  pose_center_new = get_center_point(landmarks, "left_hip", "right_hip")
  pose_center_new = tf.expand_dims(pose_center_new, axis=1)
  # Broadcast the pose center to the same size as the landmark vector to
  # perform substraction
  pose_center_new = tf.broadcast_to(pose_center_new,
                                    [tf.size(landmarks) // (17*2), 17, 2])

  # Dist to pose center
  d = tf.gather(landmarks - pose_center_new, 0, axis=0,
                name="dist_to_pose_center")
  # Max dist to pose center
  max_dist = tf.reduce_max(tf.linalg.norm(d, axis=0))

  # Normalize scale
  pose_size = tf.maximum(torso_size * torso_size_multiplier, max_dist)

  return pose_size


def normalize_pose_landmarks(landmarks):
  """Normalizes the landmarks translation by moving the pose center to (0,0) and
  scaling it to a constant pose size.
  """
  # Move landmarks so that the pose center becomes (0,0)
  pose_center = get_center_point(landmarks, "left_hip", "right_hip")
  pose_center = tf.expand_dims(pose_center, axis=1)
  # Broadcast the pose center to the same size as the landmark vector to perform
  # substraction
  pose_center = tf.broadcast_to(pose_center, 
                                [tf.size(landmarks) // (17*2), 17, 2])
  landmarks = landmarks - pose_center

  # Scale the landmarks to a constant pose size
  pose_size = get_pose_size(landmarks)
  landmarks /= pose_size

  return landmarks


def landmarks_to_embedding(landmarks_and_scores):
  """Converts the input landmarks into a pose embedding."""
  # Reshape the flat input into a matrix with shape=(17, 3)
  reshaped_inputs = keras.layers.Reshape((17, 3))(landmarks_and_scores)

  # Normalize landmarks 2D
  landmarks = normalize_pose_landmarks(reshaped_inputs[:, :, :2])

  # Flatten the normalized landmark coordinates into a vector
  embedding = keras.layers.Flatten()(landmarks)

  return embedding

Define a Keras model for pose classification

Our Keras model takes the detected pose landmarks, then calculates the pose embedding and predicts the pose class.

# Define the model
inputs = tf.keras.Input(shape=(51))
embedding = landmarks_to_embedding(inputs)

layer = keras.layers.Dense(128, activation=tf.nn.relu6)(embedding)
layer = keras.layers.Dropout(0.5)(layer)
layer = keras.layers.Dense(64, activation=tf.nn.relu6)(layer)
layer = keras.layers.Dropout(0.5)(layer)
outputs = keras.layers.Dense(5, activation="softmax")(layer)

model = keras.Model(inputs, outputs)
model.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            [(None, 51)]         0                                            
__________________________________________________________________________________________________
reshape (Reshape)               (None, 17, 3)        0           input_1[0][0]                    
__________________________________________________________________________________________________
tf.__operators__.getitem (Slici (None, 17, 2)        0           reshape[0][0]                    
__________________________________________________________________________________________________
tf.compat.v1.gather (TFOpLambda (None, 2)            0           tf.__operators__.getitem[0][0]   
__________________________________________________________________________________________________
tf.compat.v1.gather_1 (TFOpLamb (None, 2)            0           tf.__operators__.getitem[0][0]   
__________________________________________________________________________________________________
tf.math.multiply (TFOpLambda)   (None, 2)            0           tf.compat.v1.gather[0][0]        
__________________________________________________________________________________________________
tf.math.multiply_1 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_1[0][0]      
__________________________________________________________________________________________________
tf.__operators__.add (TFOpLambd (None, 2)            0           tf.math.multiply[0][0]           
                                                                 tf.math.multiply_1[0][0]         
__________________________________________________________________________________________________
tf.compat.v1.size (TFOpLambda)  ()                   0           tf.__operators__.getitem[0][0]   
__________________________________________________________________________________________________
tf.expand_dims (TFOpLambda)     (None, 1, 2)         0           tf.__operators__.add[0][0]       
__________________________________________________________________________________________________
tf.compat.v1.floor_div (TFOpLam ()                   0           tf.compat.v1.size[0][0]          
__________________________________________________________________________________________________
tf.broadcast_to (TFOpLambda)    (None, 17, 2)        0           tf.expand_dims[0][0]             
                                                                 tf.compat.v1.floor_div[0][0]     
__________________________________________________________________________________________________
tf.math.subtract (TFOpLambda)   (None, 17, 2)        0           tf.__operators__.getitem[0][0]   
                                                                 tf.broadcast_to[0][0]            
__________________________________________________________________________________________________
tf.compat.v1.gather_6 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.compat.v1.gather_7 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.math.multiply_6 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_6[0][0]      
__________________________________________________________________________________________________
tf.math.multiply_7 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_7[0][0]      
__________________________________________________________________________________________________
tf.__operators__.add_3 (TFOpLam (None, 2)            0           tf.math.multiply_6[0][0]         
                                                                 tf.math.multiply_7[0][0]         
__________________________________________________________________________________________________
tf.compat.v1.size_1 (TFOpLambda ()                   0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.compat.v1.gather_4 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.compat.v1.gather_5 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.compat.v1.gather_2 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.compat.v1.gather_3 (TFOpLamb (None, 2)            0           tf.math.subtract[0][0]           
__________________________________________________________________________________________________
tf.expand_dims_1 (TFOpLambda)   (None, 1, 2)         0           tf.__operators__.add_3[0][0]     
__________________________________________________________________________________________________
tf.compat.v1.floor_div_1 (TFOpL ()                   0           tf.compat.v1.size_1[0][0]        
__________________________________________________________________________________________________
tf.math.multiply_4 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_4[0][0]      
__________________________________________________________________________________________________
tf.math.multiply_5 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_5[0][0]      
__________________________________________________________________________________________________
tf.math.multiply_2 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_2[0][0]      
__________________________________________________________________________________________________
tf.math.multiply_3 (TFOpLambda) (None, 2)            0           tf.compat.v1.gather_3[0][0]      
__________________________________________________________________________________________________
tf.broadcast_to_1 (TFOpLambda)  (None, 17, 2)        0           tf.expand_dims_1[0][0]           
                                                                 tf.compat.v1.floor_div_1[0][0]   
__________________________________________________________________________________________________
tf.__operators__.add_2 (TFOpLam (None, 2)            0           tf.math.multiply_4[0][0]         
                                                                 tf.math.multiply_5[0][0]         
__________________________________________________________________________________________________
tf.__operators__.add_1 (TFOpLam (None, 2)            0           tf.math.multiply_2[0][0]         
                                                                 tf.math.multiply_3[0][0]         
__________________________________________________________________________________________________
tf.math.subtract_2 (TFOpLambda) (None, 17, 2)        0           tf.math.subtract[0][0]           
                                                                 tf.broadcast_to_1[0][0]          
__________________________________________________________________________________________________
tf.math.subtract_1 (TFOpLambda) (None, 2)            0           tf.__operators__.add_2[0][0]     
                                                                 tf.__operators__.add_1[0][0]     
__________________________________________________________________________________________________
tf.compat.v1.gather_8 (TFOpLamb (17, 2)              0           tf.math.subtract_2[0][0]         
__________________________________________________________________________________________________
tf.compat.v1.norm (TFOpLambda)  ()                   0           tf.math.subtract_1[0][0]         
__________________________________________________________________________________________________
tf.compat.v1.norm_1 (TFOpLambda (2,)                 0           tf.compat.v1.gather_8[0][0]      
__________________________________________________________________________________________________
tf.math.multiply_8 (TFOpLambda) ()                   0           tf.compat.v1.norm[0][0]          
__________________________________________________________________________________________________
tf.math.reduce_max (TFOpLambda) ()                   0           tf.compat.v1.norm_1[0][0]        
__________________________________________________________________________________________________
tf.math.maximum (TFOpLambda)    ()                   0           tf.math.multiply_8[0][0]         
                                                                 tf.math.reduce_max[0][0]         
__________________________________________________________________________________________________
tf.math.truediv (TFOpLambda)    (None, 17, 2)        0           tf.math.subtract[0][0]           
                                                                 tf.math.maximum[0][0]            
__________________________________________________________________________________________________
flatten (Flatten)               (None, 34)           0           tf.math.truediv[0][0]            
__________________________________________________________________________________________________
dense (Dense)                   (None, 128)          4480        flatten[0][0]                    
__________________________________________________________________________________________________
dropout (Dropout)               (None, 128)          0           dense[0][0]                      
__________________________________________________________________________________________________
dense_1 (Dense)                 (None, 64)           8256        dropout[0][0]                    
__________________________________________________________________________________________________
dropout_1 (Dropout)             (None, 64)           0           dense_1[0][0]                    
__________________________________________________________________________________________________
dense_2 (Dense)                 (None, 5)            325         dropout_1[0][0]                  
==================================================================================================
Total params: 13,061
Trainable params: 13,061
Non-trainable params: 0
__________________________________________________________________________________________________
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

# Add a checkpoint callback to store the checkpoint that has the highest
# validation accuracy.
checkpoint_path = "weights.best.hdf5"
checkpoint = keras.callbacks.ModelCheckpoint(checkpoint_path,
                             monitor='val_accuracy',
                             verbose=1,
                             save_best_only=True,
                             mode='max')
earlystopping = keras.callbacks.EarlyStopping(monitor='val_accuracy', 
                                              patience=20)

# Start training
history = model.fit(X_train, y_train,
                    epochs=200,
                    batch_size=16,
                    validation_data=(X_val, y_val),
                    callbacks=[checkpoint, earlystopping])
Epoch 1/200
51/51 [==============================] - 1s 7ms/step - loss: 1.5042 - accuracy: 0.4231 - val_loss: 1.3073 - val_accuracy: 0.5524

Epoch 00001: val_accuracy improved from -inf to 0.55245, saving model to weights.best.hdf5
Epoch 2/200
51/51 [==============================] - 0s 3ms/step - loss: 1.1877 - accuracy: 0.5397 - val_loss: 0.9636 - val_accuracy: 0.6643

Epoch 00002: val_accuracy improved from 0.55245 to 0.66434, saving model to weights.best.hdf5
Epoch 3/200
51/51 [==============================] - 0s 3ms/step - loss: 0.9292 - accuracy: 0.6352 - val_loss: 0.7852 - val_accuracy: 0.7343

Epoch 00003: val_accuracy improved from 0.66434 to 0.73427, saving model to weights.best.hdf5
Epoch 4/200
51/51 [==============================] - 0s 3ms/step - loss: 0.7951 - accuracy: 0.7010 - val_loss: 0.6448 - val_accuracy: 0.8392

Epoch 00004: val_accuracy improved from 0.73427 to 0.83916, saving model to weights.best.hdf5
Epoch 5/200
51/51 [==============================] - 0s 3ms/step - loss: 0.6964 - accuracy: 0.7382 - val_loss: 0.5481 - val_accuracy: 0.8392

Epoch 00005: val_accuracy did not improve from 0.83916
Epoch 6/200
51/51 [==============================] - 0s 3ms/step - loss: 0.6196 - accuracy: 0.7618 - val_loss: 0.4765 - val_accuracy: 0.8462

Epoch 00006: val_accuracy improved from 0.83916 to 0.84615, saving model to weights.best.hdf5
Epoch 7/200
51/51 [==============================] - 0s 3ms/step - loss: 0.5506 - accuracy: 0.7940 - val_loss: 0.4065 - val_accuracy: 0.8531

Epoch 00007: val_accuracy improved from 0.84615 to 0.85315, saving model to weights.best.hdf5
Epoch 8/200
51/51 [==============================] - 0s 3ms/step - loss: 0.4774 - accuracy: 0.8350 - val_loss: 0.3557 - val_accuracy: 0.8601

Epoch 00008: val_accuracy improved from 0.85315 to 0.86014, saving model to weights.best.hdf5
Epoch 9/200
51/51 [==============================] - 0s 3ms/step - loss: 0.4465 - accuracy: 0.8486 - val_loss: 0.3341 - val_accuracy: 0.8671

Epoch 00009: val_accuracy improved from 0.86014 to 0.86713, saving model to weights.best.hdf5
Epoch 10/200
51/51 [==============================] - 0s 3ms/step - loss: 0.3675 - accuracy: 0.8846 - val_loss: 0.2808 - val_accuracy: 0.8741

Epoch 00010: val_accuracy improved from 0.86713 to 0.87413, saving model to weights.best.hdf5
Epoch 11/200
51/51 [==============================] - 0s 3ms/step - loss: 0.3440 - accuracy: 0.8908 - val_loss: 0.2436 - val_accuracy: 0.9371

Epoch 00011: val_accuracy improved from 0.87413 to 0.93706, saving model to weights.best.hdf5
Epoch 12/200
51/51 [==============================] - 0s 3ms/step - loss: 0.3168 - accuracy: 0.9032 - val_loss: 0.2152 - val_accuracy: 0.9371

Epoch 00012: val_accuracy did not improve from 0.93706
Epoch 13/200
51/51 [==============================] - 0s 3ms/step - loss: 0.3061 - accuracy: 0.9069 - val_loss: 0.2231 - val_accuracy: 0.9371

Epoch 00013: val_accuracy did not improve from 0.93706
Epoch 14/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2672 - accuracy: 0.9231 - val_loss: 0.1819 - val_accuracy: 0.9441

Epoch 00014: val_accuracy improved from 0.93706 to 0.94406, saving model to weights.best.hdf5
Epoch 15/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2655 - accuracy: 0.9194 - val_loss: 0.1770 - val_accuracy: 0.9371

Epoch 00015: val_accuracy did not improve from 0.94406
Epoch 16/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2438 - accuracy: 0.9206 - val_loss: 0.1692 - val_accuracy: 0.9441

Epoch 00016: val_accuracy did not improve from 0.94406
Epoch 17/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2339 - accuracy: 0.9268 - val_loss: 0.1547 - val_accuracy: 0.9371

Epoch 00017: val_accuracy did not improve from 0.94406
Epoch 18/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2257 - accuracy: 0.9330 - val_loss: 0.1267 - val_accuracy: 0.9580

Epoch 00018: val_accuracy improved from 0.94406 to 0.95804, saving model to weights.best.hdf5
Epoch 19/200
51/51 [==============================] - 0s 3ms/step - loss: 0.2152 - accuracy: 0.9404 - val_loss: 0.1270 - val_accuracy: 0.9580

Epoch 00019: val_accuracy did not improve from 0.95804
Epoch 20/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1994 - accuracy: 0.9355 - val_loss: 0.1199 - val_accuracy: 0.9580

Epoch 00020: val_accuracy did not improve from 0.95804
Epoch 21/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1766 - accuracy: 0.9516 - val_loss: 0.1052 - val_accuracy: 0.9650

Epoch 00021: val_accuracy improved from 0.95804 to 0.96503, saving model to weights.best.hdf5
Epoch 22/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1667 - accuracy: 0.9516 - val_loss: 0.1097 - val_accuracy: 0.9580

Epoch 00022: val_accuracy did not improve from 0.96503
Epoch 23/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1683 - accuracy: 0.9504 - val_loss: 0.0981 - val_accuracy: 0.9580

Epoch 00023: val_accuracy did not improve from 0.96503
Epoch 24/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1650 - accuracy: 0.9467 - val_loss: 0.0887 - val_accuracy: 0.9720

Epoch 00024: val_accuracy improved from 0.96503 to 0.97203, saving model to weights.best.hdf5
Epoch 25/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1521 - accuracy: 0.9541 - val_loss: 0.0949 - val_accuracy: 0.9720

Epoch 00025: val_accuracy did not improve from 0.97203
Epoch 26/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1511 - accuracy: 0.9578 - val_loss: 0.0938 - val_accuracy: 0.9580

Epoch 00026: val_accuracy did not improve from 0.97203
Epoch 27/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1438 - accuracy: 0.9541 - val_loss: 0.0816 - val_accuracy: 0.9650

Epoch 00027: val_accuracy did not improve from 0.97203
Epoch 28/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1369 - accuracy: 0.9566 - val_loss: 0.0835 - val_accuracy: 0.9580

Epoch 00028: val_accuracy did not improve from 0.97203
Epoch 29/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1281 - accuracy: 0.9665 - val_loss: 0.0669 - val_accuracy: 0.9720

Epoch 00029: val_accuracy did not improve from 0.97203
Epoch 30/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1387 - accuracy: 0.9529 - val_loss: 0.0807 - val_accuracy: 0.9650

Epoch 00030: val_accuracy did not improve from 0.97203
Epoch 31/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1264 - accuracy: 0.9640 - val_loss: 0.0692 - val_accuracy: 0.9720

Epoch 00031: val_accuracy did not improve from 0.97203
Epoch 32/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1282 - accuracy: 0.9603 - val_loss: 0.0679 - val_accuracy: 0.9650

Epoch 00032: val_accuracy did not improve from 0.97203
Epoch 33/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1112 - accuracy: 0.9727 - val_loss: 0.0681 - val_accuracy: 0.9720

Epoch 00033: val_accuracy did not improve from 0.97203
Epoch 34/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1439 - accuracy: 0.9529 - val_loss: 0.0766 - val_accuracy: 0.9720

Epoch 00034: val_accuracy did not improve from 0.97203
Epoch 35/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1160 - accuracy: 0.9653 - val_loss: 0.0626 - val_accuracy: 0.9720

Epoch 00035: val_accuracy did not improve from 0.97203
Epoch 36/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1213 - accuracy: 0.9603 - val_loss: 0.0654 - val_accuracy: 0.9650

Epoch 00036: val_accuracy did not improve from 0.97203
Epoch 37/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1079 - accuracy: 0.9578 - val_loss: 0.0586 - val_accuracy: 0.9790

Epoch 00037: val_accuracy improved from 0.97203 to 0.97902, saving model to weights.best.hdf5
Epoch 38/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1090 - accuracy: 0.9739 - val_loss: 0.0564 - val_accuracy: 0.9790

Epoch 00038: val_accuracy did not improve from 0.97902
Epoch 39/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1055 - accuracy: 0.9640 - val_loss: 0.0523 - val_accuracy: 0.9790

Epoch 00039: val_accuracy did not improve from 0.97902
Epoch 40/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1068 - accuracy: 0.9677 - val_loss: 0.0548 - val_accuracy: 0.9720

Epoch 00040: val_accuracy did not improve from 0.97902
Epoch 41/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0973 - accuracy: 0.9727 - val_loss: 0.0466 - val_accuracy: 0.9720

Epoch 00041: val_accuracy did not improve from 0.97902
Epoch 42/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1024 - accuracy: 0.9665 - val_loss: 0.0444 - val_accuracy: 0.9790

Epoch 00042: val_accuracy did not improve from 0.97902
Epoch 43/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0784 - accuracy: 0.9789 - val_loss: 0.0558 - val_accuracy: 0.9720

Epoch 00043: val_accuracy did not improve from 0.97902
Epoch 44/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0958 - accuracy: 0.9727 - val_loss: 0.0471 - val_accuracy: 0.9720

Epoch 00044: val_accuracy did not improve from 0.97902
Epoch 45/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0982 - accuracy: 0.9702 - val_loss: 0.0380 - val_accuracy: 0.9930

Epoch 00045: val_accuracy improved from 0.97902 to 0.99301, saving model to weights.best.hdf5
Epoch 46/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0990 - accuracy: 0.9764 - val_loss: 0.0431 - val_accuracy: 0.9860

Epoch 00046: val_accuracy did not improve from 0.99301
Epoch 47/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0819 - accuracy: 0.9739 - val_loss: 0.0458 - val_accuracy: 0.9720

Epoch 00047: val_accuracy did not improve from 0.99301
Epoch 48/200
51/51 [==============================] - 0s 3ms/step - loss: 0.1017 - accuracy: 0.9665 - val_loss: 0.0445 - val_accuracy: 0.9720

Epoch 00048: val_accuracy did not improve from 0.99301
Epoch 49/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0799 - accuracy: 0.9764 - val_loss: 0.0391 - val_accuracy: 0.9930

Epoch 00049: val_accuracy did not improve from 0.99301
Epoch 50/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0677 - accuracy: 0.9777 - val_loss: 0.0465 - val_accuracy: 0.9790

Epoch 00050: val_accuracy did not improve from 0.99301
Epoch 51/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0684 - accuracy: 0.9839 - val_loss: 0.0338 - val_accuracy: 0.9930

Epoch 00051: val_accuracy did not improve from 0.99301
Epoch 52/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0719 - accuracy: 0.9777 - val_loss: 0.0282 - val_accuracy: 0.9930

Epoch 00052: val_accuracy did not improve from 0.99301
Epoch 53/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0746 - accuracy: 0.9715 - val_loss: 0.0362 - val_accuracy: 0.9860

Epoch 00053: val_accuracy did not improve from 0.99301
Epoch 54/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0573 - accuracy: 0.9814 - val_loss: 0.0339 - val_accuracy: 0.9860

Epoch 00054: val_accuracy did not improve from 0.99301
Epoch 55/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0693 - accuracy: 0.9764 - val_loss: 0.0445 - val_accuracy: 0.9790

Epoch 00055: val_accuracy did not improve from 0.99301
Epoch 56/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0683 - accuracy: 0.9864 - val_loss: 0.0301 - val_accuracy: 0.9860

Epoch 00056: val_accuracy did not improve from 0.99301
Epoch 57/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0702 - accuracy: 0.9839 - val_loss: 0.0290 - val_accuracy: 0.9930

Epoch 00057: val_accuracy did not improve from 0.99301
Epoch 58/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0525 - accuracy: 0.9851 - val_loss: 0.0298 - val_accuracy: 0.9860

Epoch 00058: val_accuracy did not improve from 0.99301
Epoch 59/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0604 - accuracy: 0.9814 - val_loss: 0.0389 - val_accuracy: 0.9860

Epoch 00059: val_accuracy did not improve from 0.99301
Epoch 60/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0721 - accuracy: 0.9739 - val_loss: 0.0265 - val_accuracy: 0.9930

Epoch 00060: val_accuracy did not improve from 0.99301
Epoch 61/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0564 - accuracy: 0.9814 - val_loss: 0.0331 - val_accuracy: 0.9860

Epoch 00061: val_accuracy did not improve from 0.99301
Epoch 62/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0687 - accuracy: 0.9814 - val_loss: 0.0338 - val_accuracy: 0.9860

Epoch 00062: val_accuracy did not improve from 0.99301
Epoch 63/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0548 - accuracy: 0.9876 - val_loss: 0.0266 - val_accuracy: 0.9930

Epoch 00063: val_accuracy did not improve from 0.99301
Epoch 64/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0648 - accuracy: 0.9826 - val_loss: 0.0245 - val_accuracy: 0.9930

Epoch 00064: val_accuracy did not improve from 0.99301
Epoch 65/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0554 - accuracy: 0.9901 - val_loss: 0.0167 - val_accuracy: 1.0000

Epoch 00065: val_accuracy improved from 0.99301 to 1.00000, saving model to weights.best.hdf5
Epoch 66/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0695 - accuracy: 0.9789 - val_loss: 0.0208 - val_accuracy: 0.9930

Epoch 00066: val_accuracy did not improve from 1.00000
Epoch 67/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0561 - accuracy: 0.9826 - val_loss: 0.0227 - val_accuracy: 0.9930

Epoch 00067: val_accuracy did not improve from 1.00000
Epoch 68/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0486 - accuracy: 0.9888 - val_loss: 0.0245 - val_accuracy: 0.9930

Epoch 00068: val_accuracy did not improve from 1.00000
Epoch 69/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0561 - accuracy: 0.9789 - val_loss: 0.0213 - val_accuracy: 0.9930

Epoch 00069: val_accuracy did not improve from 1.00000
Epoch 70/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0498 - accuracy: 0.9876 - val_loss: 0.0187 - val_accuracy: 0.9930

Epoch 00070: val_accuracy did not improve from 1.00000
Epoch 71/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0538 - accuracy: 0.9814 - val_loss: 0.0289 - val_accuracy: 0.9860

Epoch 00071: val_accuracy did not improve from 1.00000
Epoch 72/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0511 - accuracy: 0.9876 - val_loss: 0.0251 - val_accuracy: 0.9930

Epoch 00072: val_accuracy did not improve from 1.00000
Epoch 73/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0418 - accuracy: 0.9864 - val_loss: 0.0188 - val_accuracy: 0.9930

Epoch 00073: val_accuracy did not improve from 1.00000
Epoch 74/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0406 - accuracy: 0.9864 - val_loss: 0.0182 - val_accuracy: 0.9930

Epoch 00074: val_accuracy did not improve from 1.00000
Epoch 75/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0437 - accuracy: 0.9851 - val_loss: 0.0342 - val_accuracy: 0.9860

Epoch 00075: val_accuracy did not improve from 1.00000
Epoch 76/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0438 - accuracy: 0.9851 - val_loss: 0.0100 - val_accuracy: 1.0000

Epoch 00076: val_accuracy did not improve from 1.00000
Epoch 77/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0483 - accuracy: 0.9851 - val_loss: 0.0226 - val_accuracy: 0.9930

Epoch 00077: val_accuracy did not improve from 1.00000
Epoch 78/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0425 - accuracy: 0.9901 - val_loss: 0.0232 - val_accuracy: 0.9860

Epoch 00078: val_accuracy did not improve from 1.00000
Epoch 79/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0340 - accuracy: 0.9938 - val_loss: 0.0168 - val_accuracy: 0.9930

Epoch 00079: val_accuracy did not improve from 1.00000
Epoch 80/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0317 - accuracy: 0.9901 - val_loss: 0.0221 - val_accuracy: 0.9930

Epoch 00080: val_accuracy did not improve from 1.00000
Epoch 81/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0344 - accuracy: 0.9913 - val_loss: 0.0155 - val_accuracy: 0.9930

Epoch 00081: val_accuracy did not improve from 1.00000
Epoch 82/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0404 - accuracy: 0.9876 - val_loss: 0.0147 - val_accuracy: 0.9930

Epoch 00082: val_accuracy did not improve from 1.00000
Epoch 83/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0584 - accuracy: 0.9801 - val_loss: 0.0246 - val_accuracy: 0.9860

Epoch 00083: val_accuracy did not improve from 1.00000
Epoch 84/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0426 - accuracy: 0.9851 - val_loss: 0.0154 - val_accuracy: 0.9930

Epoch 00084: val_accuracy did not improve from 1.00000
Epoch 85/200
51/51 [==============================] - 0s 3ms/step - loss: 0.0321 - accuracy: 0.9913 - val_loss: 0.0156 - val_accuracy: 0.9930

Epoch 00085: val_accuracy did not improve from 1.00000
# Visualize the training history to see whether you're overfitting.
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['TRAIN', 'VAL'], loc='lower right')
plt.show()

png

# Evaluate the model using the TEST dataset
loss, accuracy = model.evaluate(X_test, y_test)
15/15 [==============================] - 0s 2ms/step - loss: 0.0277 - accuracy: 0.9956

Draw the confusion matrix to better understand the model performance

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
  """Plots the confusion matrix."""
  if normalize:
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print("Normalized confusion matrix")
  else:
    print('Confusion matrix, without normalization')

  plt.imshow(cm, interpolation='nearest', cmap=cmap)
  plt.title(title)
  plt.colorbar()
  tick_marks = np.arange(len(classes))
  plt.xticks(tick_marks, classes, rotation=55)
  plt.yticks(tick_marks, classes)
  fmt = '.2f' if normalize else 'd'
  thresh = cm.max() / 2.
  for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    plt.text(j, i, format(cm[i, j], fmt),
              horizontalalignment="center",
              color="white" if cm[i, j] > thresh else "black")

  plt.ylabel('True label')
  plt.xlabel('Predicted label')
  plt.tight_layout()

# Classify pose in the TEST dataset using the trained model
y_pred = model.predict(X_test)

# Convert the prediction result to class name
y_pred_label = [class_names[i] for i in np.argmax(y_pred, axis=1)]
y_true_label = [class_names[i] for i in np.argmax(y_test, axis=1)]

# Plot the confusion matrix
cm = confusion_matrix(np.argmax(y_test, axis=1), np.argmax(y_pred, axis=1))
plot_confusion_matrix(cm,
                      class_names,
                      title ='Confusion Matrix of Pose Classification Model')

# Print the classification report
print('\nClassification Report:\n', classification_report(y_true_label,
                                                          y_pred_label))
Confusion matrix, without normalization

Classification Report:
               precision    recall  f1-score   support

       chair       0.99      1.00      0.99        84
       cobra       0.99      1.00      1.00       116
         dog       1.00      1.00      1.00        90
        tree       1.00      1.00      1.00        56
     warrior       1.00      0.98      0.99       109

    accuracy                           1.00       455
   macro avg       1.00      1.00      1.00       455
weighted avg       1.00      1.00      1.00       455

png

(Optional) Investigate incorrect predictions

You can look at the poses from the TEST dataset that were incorrectly predicted to see whether the model accuracy can be improved.

if is_skip_step_1:
  print('ERROR: You must have run step 1 to run this cell.')
else:
  # If step 1 was skipped, skip this step.
  IMAGE_PER_ROW = 3
  MAX_NO_OF_IMAGE_TO_PLOT = 30

  # Extract the list of incorrectly predicted poses
  false_predict = [id_in_df for id_in_df in range(len(y_test)) \
                  if y_pred_label[id_in_df] != y_true_label[id_in_df]]
  if len(false_predict) > MAX_NO_OF_IMAGE_TO_PLOT:
    false_predict = false_predict[:MAX_NO_OF_IMAGE_TO_PLOT]

  # Plot the incorrectly predicted images
  row_count = len(false_predict) // IMAGE_PER_ROW + 1
  fig = plt.figure(figsize=(10 * IMAGE_PER_ROW, 10 * row_count))
  for i, id_in_df in enumerate(false_predict):
    ax = fig.add_subplot(row_count, IMAGE_PER_ROW, i + 1)
    image_path = os.path.join(images_out_test_folder,
                              df_test.iloc[id_in_df]['file_name'])

    image = cv2.imread(image_path)
    plt.title("Predict: %s; Actual: %s"
              % (y_pred_label[id_in_df], y_true_label[id_in_df]))
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
  plt.show()

png

Part 3: Convert the pose classification model to TensorFlow Lite

You'll convert the Keras pose classification model to the TensorFlow Lite format so that you can deploy it to mobile apps, web browsers and IoT devices. When converting the model, you'll apply dynamic range quantization to reduce the pose classification TensorFlow Lite model size by about 4 times with insignificant accuracy loss.

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

print('Model size: %dKB' % (len(tflite_model) / 1024))

with open('pose_classifier.tflite', 'wb') as f:
  f.write(tflite_model)
2021-09-01 02:26:08.483559: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
INFO:tensorflow:Assets written to: /tmp/tmpgn1ruxbt/assets
Model size: 26KB
2021-09-01 02:26:09.691546: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:351] Ignored output_format.
2021-09-01 02:26:09.691590: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:354] Ignored drop_control_dependency.

Then you'll write the label file which contains mapping from the class indexes to the human readable class names.

with open('pose_labels.txt', 'w') as f:
  f.write('\n'.join(class_names))

As you've applied quantization to reduce the model size, let's evaluate the quantized TFLite model to check whether the accuracy drop is acceptable.

def evaluate_model(interpreter, X, y_true):
  """Evaluates the given TFLite model and return its accuracy."""
  input_index = interpreter.get_input_details()[0]["index"]
  output_index = interpreter.get_output_details()[0]["index"]

  # Run predictions on all given poses.
  y_pred = []
  for i in range(len(y_true)):
    # Pre-processing: add batch dimension and convert to float32 to match with
    # the model's input data format.
    test_image = X[i: i + 1].astype('float32')
    interpreter.set_tensor(input_index, test_image)

    # Run inference.
    interpreter.invoke()

    # Post-processing: remove batch dimension and find the class with highest
    # probability.
    output = interpreter.tensor(output_index)
    predicted_label = np.argmax(output()[0])
    y_pred.append(predicted_label)

  # Compare prediction results with ground truth labels to calculate accuracy.
  y_pred = keras.utils.to_categorical(y_pred)
  return accuracy_score(y_true, y_pred)

# Evaluate the accuracy of the converted TFLite model
classifier_interpreter = tf.lite.Interpreter(model_content=tflite_model)
classifier_interpreter.allocate_tensors()
print('Accuracy of TFLite model: %s' %
      evaluate_model(classifier_interpreter, X_test, y_test))
Accuracy of TFLite model: 0.9978021978021978

Now you can download the TFLite model (pose_classifier.tflite) and the label file (pose_labels.txt) to classify custom poses. See the Android and Python/Raspberry Pi sample app for an end-to-end example of how to use the TFLite pose classification model.

zip pose_classifier.zip pose_labels.txt pose_classifier.tflite
adding: pose_labels.txt (stored 0%)
  adding: pose_classifier.tflite (deflated 35%)
# Download the zip archive if running on Colab.
try:
  from google.colab import files
  files.download('pose_classifier.zip')
except:
  pass