Transfer Learning for the Audio Domain with TensorFlow Lite Model Maker

Stay organized with collections Save and categorize content based on your preferences.

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

In this colab notebook, you'll learn how to use the TensorFlow Lite Model Maker to train a custom audio classification model.

The Model Maker library uses transfer learning to simplify the process of training a TensorFlow Lite model using a custom dataset. Retraining a TensorFlow Lite model with your own custom dataset reduces the amount of training data and time required.

It is part of the Codelab to Customize an Audio model and deploy on Android.

You'll use a custom birds dataset and export a TFLite model that can be used on a phone, a TensorFlow.JS model that can be used for inference in the browser and also a SavedModel version that you can use for serving.

Intalling dependencies

sudo apt -y install libportaudio2
pip install tflite-model-maker

Import TensorFlow, Model Maker and other libraries

Among the dependencies that are needed, you'll use TensorFlow and Model Maker. Aside those, the others are for audio manipulation, playing and visualizations.

import tensorflow as tf
import tflite_model_maker as mm
from tflite_model_maker import audio_classifier
import os

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import itertools
import glob
import random

from IPython.display import Audio, Image
from scipy.io import wavfile

print(f"TensorFlow Version: {tf.__version__}")
print(f"Model Maker Version: {mm.__version__}")
TensorFlow Version: 2.8.2
Model Maker Version: 0.4.2

The Birds dataset

The Birds dataset is an education collection of 5 types of birds songs:

  • White-breasted Wood-Wren
  • House Sparrow
  • Red Crossbill
  • Chestnut-crowned Antpitta
  • Azara's Spinetail

The original audio came from Xeno-canto which is a website dedicated to sharing bird sounds from all over the world.

Let's start by downloading the data.

birds_dataset_folder = tf.keras.utils.get_file('birds_dataset.zip',
                                                'https://storage.googleapis.com/laurencemoroney-blog.appspot.com/birds_dataset.zip',
                                                cache_dir='./',
                                                cache_subdir='dataset',
                                                extract=True)
Downloading data from https://storage.googleapis.com/laurencemoroney-blog.appspot.com/birds_dataset.zip
343687168/343680986 [==============================] - 2s 0us/step
343695360/343680986 [==============================] - 2s 0us/step

Explore the data

The audios are already split in train and test folders. Inside each split folder, there's one folder for each bird, using their bird_code as name.

The audios are all mono and with 16kHz sample rate.

For more information about each file, you can read the metadata.csv file. It contains all the files authors, lincenses and some more information. You won't need to read it yourself on this tutorial.

# @title [Run this] Util functions and data structures.

data_dir = './dataset/small_birds_dataset'

bird_code_to_name = {
  'wbwwre1': 'White-breasted Wood-Wren',
  'houspa': 'House Sparrow',
  'redcro': 'Red Crossbill',  
  'chcant2': 'Chestnut-crowned Antpitta',
  'azaspi1': "Azara's Spinetail",   
}

birds_images = {
  'wbwwre1': 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Henicorhina_leucosticta_%28Cucarachero_pechiblanco%29_-_Juvenil_%2814037225664%29.jpg/640px-Henicorhina_leucosticta_%28Cucarachero_pechiblanco%29_-_Juvenil_%2814037225664%29.jpg', #   Alejandro Bayer Tamayo from Armenia, Colombia 
  'houspa': 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/House_Sparrow%2C_England_-_May_09.jpg/571px-House_Sparrow%2C_England_-_May_09.jpg', #    Diliff
  'redcro': 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Red_Crossbills_%28Male%29.jpg/640px-Red_Crossbills_%28Male%29.jpg', #  Elaine R. Wilson, www.naturespicsonline.com
  'chcant2': 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/67/Chestnut-crowned_antpitta_%2846933264335%29.jpg/640px-Chestnut-crowned_antpitta_%2846933264335%29.jpg', #   Mike's Birds from Riverside, CA, US
  'azaspi1': 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Synallaxis_azarae_76608368.jpg/640px-Synallaxis_azarae_76608368.jpg', # https://www.inaturalist.org/photos/76608368
}

test_files = os.path.abspath(os.path.join(data_dir, 'test/*/*.wav'))

def get_random_audio_file():
  test_list = glob.glob(test_files)
  random_audio_path = random.choice(test_list)
  return random_audio_path


def show_bird_data(audio_path):
  sample_rate, audio_data = wavfile.read(audio_path, 'rb')

  bird_code = audio_path.split('/')[-2]
  print(f'Bird name: {bird_code_to_name[bird_code]}')
  print(f'Bird code: {bird_code}')
  display(Image(birds_images[bird_code]))

  plttitle = f'{bird_code_to_name[bird_code]} ({bird_code})'
  plt.title(plttitle)
  plt.plot(audio_data)
  display(Audio(audio_data, rate=sample_rate))

print('functions and data structures created')
functions and data structures created

Playing some audio

To have a better understanding about the data, lets listen to a random audio files from the test split.

random_audio = get_random_audio_file()
show_bird_data(random_audio)
Bird name: Azara's Spinetail
Bird code: azaspi1

jpeg

png

Training the Model

When using Model Maker for audio, you have to start with a model spec. This is the base model that your new model will extract information to learn about the new classes. It also affects how the dataset will be transformed to respect the models spec parameters like: sample rate, number of channels.

YAMNet is an audio event classifier trained on the AudioSet dataset to predict audio events from the AudioSet ontology.

It's input is expected to be at 16kHz and with 1 channel.

You don't need to do any resampling yourself. Model Maker takes care of that for you.

  • frame_length is to decide how long each traininng sample is. in this caase EXPECTED_WAVEFORM_LENGTH * 3s

  • frame_steps is to decide how far appart are the training samples. In this case, the ith sample will start at EXPECTED_WAVEFORM_LENGTH * 6s after the (i-1)th sample.

The reason to set these values is to work around some limitation in real world dataset.

For example, in the bird dataset, birds don't sing all the time. They sing, rest and sing again, with noises in between. Having a long frame would help capture the singing, but setting it too long will reduce the number of samples for training.

spec = audio_classifier.YamNetSpec(
    keep_yamnet_and_custom_heads=True,
    frame_step=3 * audio_classifier.YamNetSpec.EXPECTED_WAVEFORM_LENGTH,
    frame_length=6 * audio_classifier.YamNetSpec.EXPECTED_WAVEFORM_LENGTH)
INFO:tensorflow:Checkpoints are stored in /tmpfs/tmp/tmpqe_4uc58

Loading the data

Model Maker has the API to load the data from a folder and have it in the expected format for the model spec.

The train and test split are based on the folders. The validation dataset will be created as 20% of the train split.

train_data = audio_classifier.DataLoader.from_folder(
    spec, os.path.join(data_dir, 'train'), cache=True)
train_data, validation_data = train_data.split(0.8)
test_data = audio_classifier.DataLoader.from_folder(
    spec, os.path.join(data_dir, 'test'), cache=True)

Training the model

the audio_classifier has the create method that creates a model and already start training it.

You can customize many parameterss, for more information you can read more details in the documentation.

On this first try you'll use all the default configurations and train for 100 epochs.

batch_size = 128
epochs = 100

print('Training the model')
model = audio_classifier.create(
    train_data,
    spec,
    validation_data,
    batch_size=batch_size,
    epochs=epochs)
Training the model
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 classification_head (Dense)  (None, 5)                5125      
                                                                 
=================================================================
Total params: 5,125
Trainable params: 5,125
Non-trainable params: 0
_________________________________________________________________
Epoch 1/100
21/21 [==============================] - 18s 740ms/step - loss: 1.5720 - acc: 0.2786 - val_loss: 1.3058 - val_acc: 0.5674
Epoch 2/100
21/21 [==============================] - 0s 21ms/step - loss: 1.3389 - acc: 0.4543 - val_loss: 1.1514 - val_acc: 0.6610
Epoch 3/100
21/21 [==============================] - 1s 26ms/step - loss: 1.1820 - acc: 0.5669 - val_loss: 1.0484 - val_acc: 0.7534
Epoch 4/100
21/21 [==============================] - 1s 23ms/step - loss: 1.0725 - acc: 0.6395 - val_loss: 0.9776 - val_acc: 0.7888
Epoch 5/100
21/21 [==============================] - 0s 22ms/step - loss: 0.9824 - acc: 0.6833 - val_loss: 0.9321 - val_acc: 0.7842
Epoch 6/100
21/21 [==============================] - 0s 21ms/step - loss: 0.9192 - acc: 0.7041 - val_loss: 0.8862 - val_acc: 0.7865
Epoch 7/100
21/21 [==============================] - 0s 21ms/step - loss: 0.8676 - acc: 0.7275 - val_loss: 0.8603 - val_acc: 0.7580
Epoch 8/100
21/21 [==============================] - 0s 21ms/step - loss: 0.8274 - acc: 0.7325 - val_loss: 0.8364 - val_acc: 0.7386
Epoch 9/100
21/21 [==============================] - 0s 22ms/step - loss: 0.7798 - acc: 0.7617 - val_loss: 0.8230 - val_acc: 0.7100
Epoch 10/100
21/21 [==============================] - 0s 20ms/step - loss: 0.7655 - acc: 0.7563 - val_loss: 0.8063 - val_acc: 0.7078
Epoch 11/100
21/21 [==============================] - 0s 21ms/step - loss: 0.7260 - acc: 0.7829 - val_loss: 0.7973 - val_acc: 0.7055
Epoch 12/100
21/21 [==============================] - 0s 20ms/step - loss: 0.6998 - acc: 0.7844 - val_loss: 0.7887 - val_acc: 0.7021
Epoch 13/100
21/21 [==============================] - 0s 21ms/step - loss: 0.6853 - acc: 0.7859 - val_loss: 0.7845 - val_acc: 0.6952
Epoch 14/100
21/21 [==============================] - 0s 20ms/step - loss: 0.6580 - acc: 0.7975 - val_loss: 0.7813 - val_acc: 0.6941
Epoch 15/100
21/21 [==============================] - 0s 21ms/step - loss: 0.6433 - acc: 0.8025 - val_loss: 0.7779 - val_acc: 0.6941
Epoch 16/100
21/21 [==============================] - 0s 20ms/step - loss: 0.6213 - acc: 0.8082 - val_loss: 0.7684 - val_acc: 0.6975
Epoch 17/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5985 - acc: 0.8224 - val_loss: 0.7753 - val_acc: 0.6941
Epoch 18/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5958 - acc: 0.8274 - val_loss: 0.7786 - val_acc: 0.6906
Epoch 19/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5868 - acc: 0.8244 - val_loss: 0.7699 - val_acc: 0.6929
Epoch 20/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5699 - acc: 0.8286 - val_loss: 0.7799 - val_acc: 0.6929
Epoch 21/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5613 - acc: 0.8209 - val_loss: 0.7746 - val_acc: 0.6918
Epoch 22/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5471 - acc: 0.8370 - val_loss: 0.7945 - val_acc: 0.6838
Epoch 23/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5412 - acc: 0.8382 - val_loss: 0.7868 - val_acc: 0.6861
Epoch 24/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5309 - acc: 0.8447 - val_loss: 0.7892 - val_acc: 0.6872
Epoch 25/100
21/21 [==============================] - 0s 20ms/step - loss: 0.5191 - acc: 0.8455 - val_loss: 0.7911 - val_acc: 0.6872
Epoch 26/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5182 - acc: 0.8436 - val_loss: 0.7985 - val_acc: 0.6884
Epoch 27/100
21/21 [==============================] - 0s 21ms/step - loss: 0.5034 - acc: 0.8447 - val_loss: 0.7931 - val_acc: 0.6884
Epoch 28/100
21/21 [==============================] - 1s 23ms/step - loss: 0.5011 - acc: 0.8501 - val_loss: 0.7985 - val_acc: 0.6872
Epoch 29/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4805 - acc: 0.8643 - val_loss: 0.8054 - val_acc: 0.6861
Epoch 30/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4887 - acc: 0.8470 - val_loss: 0.8008 - val_acc: 0.6884
Epoch 31/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4742 - acc: 0.8616 - val_loss: 0.8067 - val_acc: 0.6884
Epoch 32/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4783 - acc: 0.8559 - val_loss: 0.8024 - val_acc: 0.6918
Epoch 33/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4723 - acc: 0.8532 - val_loss: 0.8077 - val_acc: 0.6918
Epoch 34/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4677 - acc: 0.8590 - val_loss: 0.8108 - val_acc: 0.6929
Epoch 35/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4547 - acc: 0.8636 - val_loss: 0.8055 - val_acc: 0.6952
Epoch 36/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4560 - acc: 0.8574 - val_loss: 0.8188 - val_acc: 0.6941
Epoch 37/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4545 - acc: 0.8647 - val_loss: 0.8136 - val_acc: 0.6975
Epoch 38/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4446 - acc: 0.8678 - val_loss: 0.8355 - val_acc: 0.6906
Epoch 39/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4387 - acc: 0.8701 - val_loss: 0.8285 - val_acc: 0.6941
Epoch 40/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4358 - acc: 0.8682 - val_loss: 0.8372 - val_acc: 0.6918
Epoch 41/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4313 - acc: 0.8709 - val_loss: 0.8231 - val_acc: 0.6998
Epoch 42/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4329 - acc: 0.8666 - val_loss: 0.8328 - val_acc: 0.6986
Epoch 43/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4280 - acc: 0.8647 - val_loss: 0.8358 - val_acc: 0.6975
Epoch 44/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4234 - acc: 0.8640 - val_loss: 0.8471 - val_acc: 0.6963
Epoch 45/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4185 - acc: 0.8736 - val_loss: 0.8416 - val_acc: 0.6963
Epoch 46/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4122 - acc: 0.8736 - val_loss: 0.8435 - val_acc: 0.6975
Epoch 47/100
21/21 [==============================] - 0s 20ms/step - loss: 0.4079 - acc: 0.8782 - val_loss: 0.8527 - val_acc: 0.7009
Epoch 48/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4018 - acc: 0.8793 - val_loss: 0.8419 - val_acc: 0.7032
Epoch 49/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3993 - acc: 0.8774 - val_loss: 0.8643 - val_acc: 0.6975
Epoch 50/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4029 - acc: 0.8762 - val_loss: 0.8599 - val_acc: 0.7021
Epoch 51/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3979 - acc: 0.8755 - val_loss: 0.8506 - val_acc: 0.7055
Epoch 52/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3901 - acc: 0.8797 - val_loss: 0.8604 - val_acc: 0.6986
Epoch 53/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3913 - acc: 0.8786 - val_loss: 0.8622 - val_acc: 0.6998
Epoch 54/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3966 - acc: 0.8689 - val_loss: 0.8598 - val_acc: 0.7043
Epoch 55/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3900 - acc: 0.8762 - val_loss: 0.8668 - val_acc: 0.7009
Epoch 56/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3807 - acc: 0.8839 - val_loss: 0.8759 - val_acc: 0.6998
Epoch 57/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3865 - acc: 0.8828 - val_loss: 0.8695 - val_acc: 0.7043
Epoch 58/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3784 - acc: 0.8820 - val_loss: 0.8788 - val_acc: 0.7009
Epoch 59/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3831 - acc: 0.8762 - val_loss: 0.8763 - val_acc: 0.7043
Epoch 60/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3614 - acc: 0.8866 - val_loss: 0.8770 - val_acc: 0.7009
Epoch 61/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3761 - acc: 0.8836 - val_loss: 0.8897 - val_acc: 0.7009
Epoch 62/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3844 - acc: 0.8774 - val_loss: 0.8794 - val_acc: 0.7066
Epoch 63/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3707 - acc: 0.8866 - val_loss: 0.8858 - val_acc: 0.7043
Epoch 64/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3707 - acc: 0.8828 - val_loss: 0.8803 - val_acc: 0.7066
Epoch 65/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3714 - acc: 0.8832 - val_loss: 0.8915 - val_acc: 0.7009
Epoch 66/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3722 - acc: 0.8812 - val_loss: 0.8982 - val_acc: 0.7043
Epoch 67/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3649 - acc: 0.8862 - val_loss: 0.8925 - val_acc: 0.7066
Epoch 68/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3642 - acc: 0.8789 - val_loss: 0.8926 - val_acc: 0.7078
Epoch 69/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3628 - acc: 0.8809 - val_loss: 0.8917 - val_acc: 0.7089
Epoch 70/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3550 - acc: 0.8943 - val_loss: 0.8996 - val_acc: 0.7078
Epoch 71/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3620 - acc: 0.8805 - val_loss: 0.9147 - val_acc: 0.7078
Epoch 72/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3513 - acc: 0.8909 - val_loss: 0.9097 - val_acc: 0.7043
Epoch 73/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3484 - acc: 0.8947 - val_loss: 0.9118 - val_acc: 0.7089
Epoch 74/100
21/21 [==============================] - 0s 23ms/step - loss: 0.3457 - acc: 0.8893 - val_loss: 0.9196 - val_acc: 0.7078
Epoch 75/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3532 - acc: 0.8889 - val_loss: 0.9324 - val_acc: 0.7055
Epoch 76/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3421 - acc: 0.8893 - val_loss: 0.9195 - val_acc: 0.7078
Epoch 77/100
21/21 [==============================] - 0s 20ms/step - loss: 0.3354 - acc: 0.8901 - val_loss: 0.9203 - val_acc: 0.7089
Epoch 78/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3432 - acc: 0.8889 - val_loss: 0.9155 - val_acc: 0.7089
Epoch 79/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3442 - acc: 0.8916 - val_loss: 0.9115 - val_acc: 0.7100
Epoch 80/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3321 - acc: 0.9012 - val_loss: 0.9279 - val_acc: 0.7089
Epoch 81/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3484 - acc: 0.8832 - val_loss: 0.9317 - val_acc: 0.7078
Epoch 82/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3416 - acc: 0.8878 - val_loss: 0.9329 - val_acc: 0.7078
Epoch 83/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3419 - acc: 0.8878 - val_loss: 0.9201 - val_acc: 0.7100
Epoch 84/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3417 - acc: 0.8916 - val_loss: 0.9300 - val_acc: 0.7100
Epoch 85/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3348 - acc: 0.8866 - val_loss: 0.9301 - val_acc: 0.7100
Epoch 86/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3349 - acc: 0.8920 - val_loss: 0.9259 - val_acc: 0.7112
Epoch 87/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3265 - acc: 0.9024 - val_loss: 0.9317 - val_acc: 0.7089
Epoch 88/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3294 - acc: 0.8974 - val_loss: 0.9434 - val_acc: 0.7078
Epoch 89/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3448 - acc: 0.8839 - val_loss: 0.9258 - val_acc: 0.7100
Epoch 90/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3282 - acc: 0.9008 - val_loss: 0.9352 - val_acc: 0.7100
Epoch 91/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3306 - acc: 0.8909 - val_loss: 0.9373 - val_acc: 0.7135
Epoch 92/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3308 - acc: 0.8943 - val_loss: 0.9461 - val_acc: 0.7089
Epoch 93/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3292 - acc: 0.8893 - val_loss: 0.9514 - val_acc: 0.7089
Epoch 94/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3193 - acc: 0.8993 - val_loss: 0.9556 - val_acc: 0.7100
Epoch 95/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3181 - acc: 0.8966 - val_loss: 0.9469 - val_acc: 0.7123
Epoch 96/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3254 - acc: 0.8924 - val_loss: 0.9531 - val_acc: 0.7078
Epoch 97/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3191 - acc: 0.8905 - val_loss: 0.9605 - val_acc: 0.7078
Epoch 98/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3185 - acc: 0.8939 - val_loss: 0.9658 - val_acc: 0.7089
Epoch 99/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3216 - acc: 0.8901 - val_loss: 0.9538 - val_acc: 0.7100
Epoch 100/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3208 - acc: 0.8962 - val_loss: 0.9690 - val_acc: 0.7066

The accuracy looks good but it's important to run the evaluation step on the test data and vefify your model achieved good results on unseed data.

print('Evaluating the model')
model.evaluate(test_data)
Evaluating the model
28/28 [==============================] - 5s 132ms/step - loss: 0.9819 - acc: 0.7325
[0.9819057583808899, 0.7324913740158081]

Understanding your model

When training a classifier, it's useful to see the confusion matrix. The confusion matrix gives you detailed knowledge of how your classifier is performing on test data.

Model Maker already creates the confusion matrix for you.

def show_confusion_matrix(confusion, test_labels):
  """Compute confusion matrix and normalize."""
  confusion_normalized = confusion.astype("float") / confusion.sum(axis=1)
  axis_labels = test_labels
  ax = sns.heatmap(
      confusion_normalized, xticklabels=axis_labels, yticklabels=axis_labels,
      cmap='Blues', annot=True, fmt='.2f', square=True)
  plt.title("Confusion matrix")
  plt.ylabel("True label")
  plt.xlabel("Predicted label")

confusion_matrix = model.confusion_matrix(test_data)
show_confusion_matrix(confusion_matrix.numpy(), test_data.index_to_label)

png

Testing the model [Optional]

You can try the model on a sample audio from the test dataset just to see the results.

First you get the serving model.

serving_model = model.create_serving_model()

print(f'Model\'s input shape and type: {serving_model.inputs}')
print(f'Model\'s output shape and type: {serving_model.outputs}')
Model's input shape and type: [<KerasTensor: shape=(None, 15600) dtype=float32 (created by layer 'audio')>]
Model's output shape and type: [<KerasTensor: shape=(None, 521) dtype=float32 (created by layer 'keras_layer')>, <KerasTensor: shape=(None, 5) dtype=float32 (created by layer 'sequential')>]

Coming back to the random audio you loaded earlier

# if you want to try another file just uncoment the line below
random_audio = get_random_audio_file()
show_bird_data(random_audio)
Bird name: White-breasted Wood-Wren
Bird code: wbwwre1

jpeg

png

The model created has a fixed input window.

For a given audio file, you'll have to split it in windows of data of the expected size. The last window might need to be filled with zeros.

sample_rate, audio_data = wavfile.read(random_audio, 'rb')

audio_data = np.array(audio_data) / tf.int16.max
input_size = serving_model.input_shape[1]

splitted_audio_data = tf.signal.frame(audio_data, input_size, input_size, pad_end=True, pad_value=0)

print(f'Test audio path: {random_audio}')
print(f'Original size of the audio data: {len(audio_data)}')
print(f'Number of windows for inference: {len(splitted_audio_data)}')
Test audio path: /tmpfs/src/temp/tensorflow/lite/g3doc/models/modify/model_maker/dataset/small_birds_dataset/test/wbwwre1/XC525556.wav
Original size of the audio data: 1190944
Number of windows for inference: 77

You'll loop over all the splitted audio and apply the model for each one of them.

The model you've just trained has 2 outputs: The original YAMNet's output and the one you've just trained. This is important because the real world environment is more complicated than just bird sounds. You can use the YAMNet's output to filter out non relevant audio, for example, on the birds use case, if YAMNet is not classifying Birds or Animals, this might show that the output from your model might have an irrelevant classification.

Below both outpus are printed to make it easier to understand their relation. Most of the mistakes that your model make are when YAMNet's prediction is not related to your domain (eg: birds).

print(random_audio)

results = []
print('Result of the window ith:  your model class -> score,  (spec class -> score)')
for i, data in enumerate(splitted_audio_data):
  yamnet_output, inference = serving_model(data)
  results.append(inference[0].numpy())
  result_index = tf.argmax(inference[0])
  spec_result_index = tf.argmax(yamnet_output[0])
  t = spec._yamnet_labels()[spec_result_index]
  result_str = f'Result of the window {i}: ' \
  f'\t{test_data.index_to_label[result_index]} -> {inference[0][result_index].numpy():.3f}, ' \
  f'\t({spec._yamnet_labels()[spec_result_index]} -> {yamnet_output[0][spec_result_index]:.3f})'
  print(result_str)


results_np = np.array(results)
mean_results = results_np.mean(axis=0)
result_index = mean_results.argmax()
print(f'Mean result: {test_data.index_to_label[result_index]} -> {mean_results[result_index]}')
/tmpfs/src/temp/tensorflow/lite/g3doc/models/modify/model_maker/dataset/small_birds_dataset/test/wbwwre1/XC525556.wav
Result of the window ith:  your model class -> score,  (spec class -> score)
Result of the window 0:   wbwwre1 -> 0.966,    (Insect -> 0.861)
Result of the window 1:   wbwwre1 -> 0.993,    (Insect -> 0.459)
Result of the window 2:   wbwwre1 -> 0.973,    (Animal -> 0.918)
Result of the window 3:   wbwwre1 -> 1.000,    (Insect -> 0.982)
Result of the window 4:   wbwwre1 -> 0.997,    (Insect -> 0.990)
Result of the window 5:   wbwwre1 -> 0.999,    (Animal -> 0.993)
Result of the window 6:   wbwwre1 -> 0.998,    (Insect -> 0.964)
Result of the window 7:   wbwwre1 -> 0.628,    (Insect -> 0.562)
Result of the window 8:   wbwwre1 -> 0.999,    (Insect -> 0.958)
Result of the window 9:   wbwwre1 -> 0.997,    (Insect -> 0.995)
Result of the window 10:  wbwwre1 -> 0.952,    (Cricket -> 0.915)
Result of the window 11:  wbwwre1 -> 0.986,    (Animal -> 0.994)
Result of the window 12:  wbwwre1 -> 0.909,    (Insect -> 0.388)
Result of the window 13:  wbwwre1 -> 0.942,    (Insect -> 0.810)
Result of the window 14:  wbwwre1 -> 0.921,    (Insect -> 0.918)
Result of the window 15:  wbwwre1 -> 0.951,    (Insect -> 0.959)
Result of the window 16:  wbwwre1 -> 1.000,    (Animal -> 0.994)
Result of the window 17:  wbwwre1 -> 1.000,    (Animal -> 0.950)
Result of the window 18:  wbwwre1 -> 0.689,    (Insect -> 0.980)
Result of the window 19:  wbwwre1 -> 0.933,    (Insect -> 0.608)
Result of the window 20:  azaspi1 -> 0.644,    (Animal -> 0.831)
Result of the window 21:  wbwwre1 -> 0.982,    (Animal -> 0.997)
Result of the window 22:  wbwwre1 -> 0.964,    (Cricket -> 0.298)
Result of the window 23:  wbwwre1 -> 0.965,    (Cricket -> 0.465)
Result of the window 24:  wbwwre1 -> 0.998,    (Cricket -> 0.913)
Result of the window 25:  wbwwre1 -> 0.998,    (Helicopter -> 0.509)
Result of the window 26:  wbwwre1 -> 0.976,    (Cricket -> 0.394)
Result of the window 27:  wbwwre1 -> 0.975,    (Animal -> 0.971)
Result of the window 28:  wbwwre1 -> 1.000,    (Animal -> 0.882)
Result of the window 29:  wbwwre1 -> 0.990,    (Cricket -> 0.785)
Result of the window 30:  wbwwre1 -> 0.882,    (Insect -> 0.476)
Result of the window 31:  wbwwre1 -> 0.996,    (Animal -> 0.951)
Result of the window 32:  wbwwre1 -> 1.000,    (Animal -> 0.989)
Result of the window 33:  wbwwre1 -> 0.990,    (Insect -> 0.949)
Result of the window 34:  wbwwre1 -> 0.506,    (Animal -> 0.395)
Result of the window 35:  wbwwre1 -> 0.960,    (Insect -> 0.472)
Result of the window 36:  wbwwre1 -> 0.807,    (Insect -> 0.790)
Result of the window 37:  wbwwre1 -> 1.000,    (Insect -> 0.986)
Result of the window 38:  wbwwre1 -> 0.997,    (Insect -> 0.829)
Result of the window 39:  wbwwre1 -> 0.987,    (Cricket -> 0.875)
Result of the window 40:  wbwwre1 -> 0.995,    (Insect -> 0.949)
Result of the window 41:  wbwwre1 -> 0.879,    (Cricket -> 0.554)
Result of the window 42:  wbwwre1 -> 0.987,    (Cricket -> 0.807)
Result of the window 43:  wbwwre1 -> 0.983,    (Animal -> 0.940)
Result of the window 44:  wbwwre1 -> 0.991,    (Cricket -> 0.940)
Result of the window 45:  wbwwre1 -> 0.891,    (Insect -> 0.299)
Result of the window 46:  wbwwre1 -> 0.942,    (Speech -> 0.573)
Result of the window 47:  wbwwre1 -> 0.979,    (Cricket -> 0.799)
Result of the window 48:  wbwwre1 -> 0.994,    (Cricket -> 0.929)
Result of the window 49:  wbwwre1 -> 0.906,    (Speech -> 0.711)
Result of the window 50:  wbwwre1 -> 0.951,    (Cricket -> 0.666)
Result of the window 51:  wbwwre1 -> 0.986,    (Speech -> 0.426)
Result of the window 52:  wbwwre1 -> 0.993,    (Cricket -> 0.905)
Result of the window 53:  wbwwre1 -> 0.955,    (Speech -> 0.899)
Result of the window 54:  wbwwre1 -> 0.976,    (Insect -> 0.882)
Result of the window 55:  wbwwre1 -> 0.988,    (Cricket -> 0.431)
Result of the window 56:  wbwwre1 -> 0.924,    (Outside, rural or natural -> 0.521)
Result of the window 57:  wbwwre1 -> 0.999,    (Cricket -> 0.924)
Result of the window 58:  wbwwre1 -> 0.892,    (Cricket -> 0.718)
Result of the window 59:  wbwwre1 -> 0.836,    (Speech -> 0.884)
Result of the window 60:  wbwwre1 -> 0.970,    (Insect -> 0.382)
Result of the window 61:  wbwwre1 -> 0.978,    (Insect -> 0.847)
Result of the window 62:  wbwwre1 -> 0.999,    (Cricket -> 0.959)
Result of the window 63:  wbwwre1 -> 0.987,    (Cricket -> 0.323)
Result of the window 64:  wbwwre1 -> 0.963,    (Insect -> 0.515)
Result of the window 65:  wbwwre1 -> 0.816,    (Cricket -> 0.490)
Result of the window 66:  wbwwre1 -> 0.988,    (Cricket -> 0.853)
Result of the window 67:  wbwwre1 -> 0.819,    (Insect -> 0.156)
Result of the window 68:  wbwwre1 -> 0.904,    (Cricket -> 0.544)
Result of the window 69:  wbwwre1 -> 0.906,    (Insect -> 0.795)
Result of the window 70:  wbwwre1 -> 0.880,    (Frog -> 0.346)
Result of the window 71:  redcro -> 0.467,     (Silence -> 0.894)
Result of the window 72:  chcant2 -> 0.572,    (Silence -> 1.000)
Result of the window 73:  chcant2 -> 0.356,    (Silence -> 0.421)
Result of the window 74:  chcant2 -> 0.983,    (Silence -> 0.405)
Result of the window 75:  chcant2 -> 0.982,    (Silence -> 1.000)
Result of the window 76:  chcant2 -> 0.916,    (Silence -> 1.000)
Mean result: wbwwre1 -> 0.8623756170272827

Exporting the model

The last step is exporting your model to be used on embedded devices or on the browser.

The export method export both formats for you.

models_path = './birds_models'
print(f'Exporing the TFLite model to {models_path}')

model.export(models_path, tflite_filename='my_birds_model.tflite')
Exporing the TFLite model to ./birds_models
2022-08-31 13:23:42.686910: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp0a9_ukpr/assets
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp0a9_ukpr/assets
2022-08-31 13:23:49.197846: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:357] Ignored output_format.
2022-08-31 13:23:49.197904: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored drop_control_dependency.
INFO:tensorflow:TensorFlow Lite model exported successfully: ./birds_models/my_birds_model.tflite
INFO:tensorflow:TensorFlow Lite model exported successfully: ./birds_models/my_birds_model.tflite

You can also export the SavedModel version for serving or using on a Python environment.

model.export(models_path, export_format=[mm.ExportFormat.SAVED_MODEL, mm.ExportFormat.LABEL])
WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.
WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.
INFO:tensorflow:Assets written to: ./birds_models/saved_model/assets
INFO:tensorflow:Assets written to: ./birds_models/saved_model/assets
INFO:tensorflow:Saving labels in ./birds_models/labels.txt
INFO:tensorflow:Saving labels in ./birds_models/labels.txt

Next Steps

You did it.

Now your new model can be deployed on mobile devices using TFLite AudioClassifier Task API.

You can also try the same process with your own data with different classes and here is the documentation for Model Maker for Audio Classification.

Also learn from end-to-end reference apps: Android, iOS.