Google I/O is a wrap! Catch up on TensorFlow sessions View sessions

Transfer Learning for the Audio Domain with TensorFlow Lite Model Maker

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.0

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 [==============================] - 3s 0us/step
343695360/343680986 [==============================] - 3s 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: Red Crossbill
Bird code: redcro

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/tmp1na9v6eb

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
23/23 [==============================] - 18s 643ms/step - loss: 1.4572 - acc: 0.3656 - val_loss: 1.4570 - val_acc: 0.3482
Epoch 2/100
23/23 [==============================] - 0s 19ms/step - loss: 1.2310 - acc: 0.5104 - val_loss: 1.3035 - val_acc: 0.5462
Epoch 3/100
23/23 [==============================] - 0s 18ms/step - loss: 1.0927 - acc: 0.5992 - val_loss: 1.2032 - val_acc: 0.6122
Epoch 4/100
23/23 [==============================] - 0s 19ms/step - loss: 0.9935 - acc: 0.6671 - val_loss: 1.1287 - val_acc: 0.6419
Epoch 5/100
23/23 [==============================] - 0s 19ms/step - loss: 0.9191 - acc: 0.6901 - val_loss: 1.0676 - val_acc: 0.6733
Epoch 6/100
23/23 [==============================] - 0s 20ms/step - loss: 0.8577 - acc: 0.7214 - val_loss: 1.0209 - val_acc: 0.6898
Epoch 7/100
23/23 [==============================] - 0s 18ms/step - loss: 0.8092 - acc: 0.7368 - val_loss: 0.9823 - val_acc: 0.7030
Epoch 8/100
23/23 [==============================] - 0s 17ms/step - loss: 0.7736 - acc: 0.7448 - val_loss: 0.9477 - val_acc: 0.7145
Epoch 9/100
23/23 [==============================] - 0s 18ms/step - loss: 0.7448 - acc: 0.7591 - val_loss: 0.9194 - val_acc: 0.7277
Epoch 10/100
23/23 [==============================] - 0s 19ms/step - loss: 0.7137 - acc: 0.7625 - val_loss: 0.8943 - val_acc: 0.7343
Epoch 11/100
23/23 [==============================] - 0s 18ms/step - loss: 0.6978 - acc: 0.7681 - val_loss: 0.8721 - val_acc: 0.7459
Epoch 12/100
23/23 [==============================] - 0s 19ms/step - loss: 0.6648 - acc: 0.7806 - val_loss: 0.8505 - val_acc: 0.7525
Epoch 13/100
23/23 [==============================] - 0s 18ms/step - loss: 0.6495 - acc: 0.7817 - val_loss: 0.8342 - val_acc: 0.7624
Epoch 14/100
23/23 [==============================] - 0s 17ms/step - loss: 0.6283 - acc: 0.7960 - val_loss: 0.8190 - val_acc: 0.7624
Epoch 15/100
23/23 [==============================] - 0s 19ms/step - loss: 0.6043 - acc: 0.8036 - val_loss: 0.8038 - val_acc: 0.7723
Epoch 16/100
23/23 [==============================] - 1s 22ms/step - loss: 0.6020 - acc: 0.7984 - val_loss: 0.7925 - val_acc: 0.7706
Epoch 17/100
23/23 [==============================] - 0s 19ms/step - loss: 0.5831 - acc: 0.8036 - val_loss: 0.7806 - val_acc: 0.7723
Epoch 18/100
23/23 [==============================] - 0s 17ms/step - loss: 0.5760 - acc: 0.8120 - val_loss: 0.7671 - val_acc: 0.7739
Epoch 19/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5646 - acc: 0.8175 - val_loss: 0.7584 - val_acc: 0.7772
Epoch 20/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5512 - acc: 0.8179 - val_loss: 0.7470 - val_acc: 0.7772
Epoch 21/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5470 - acc: 0.8172 - val_loss: 0.7374 - val_acc: 0.7805
Epoch 22/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5295 - acc: 0.8228 - val_loss: 0.7294 - val_acc: 0.7822
Epoch 23/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5213 - acc: 0.8287 - val_loss: 0.7236 - val_acc: 0.7822
Epoch 24/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5137 - acc: 0.8266 - val_loss: 0.7166 - val_acc: 0.7838
Epoch 25/100
23/23 [==============================] - 0s 18ms/step - loss: 0.5087 - acc: 0.8336 - val_loss: 0.7079 - val_acc: 0.7871
Epoch 26/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4993 - acc: 0.8322 - val_loss: 0.7018 - val_acc: 0.7904
Epoch 27/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4926 - acc: 0.8384 - val_loss: 0.6970 - val_acc: 0.7888
Epoch 28/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4850 - acc: 0.8409 - val_loss: 0.6895 - val_acc: 0.7937
Epoch 29/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4831 - acc: 0.8388 - val_loss: 0.6860 - val_acc: 0.7987
Epoch 30/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4834 - acc: 0.8377 - val_loss: 0.6798 - val_acc: 0.8036
Epoch 31/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4735 - acc: 0.8364 - val_loss: 0.6755 - val_acc: 0.8003
Epoch 32/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4679 - acc: 0.8416 - val_loss: 0.6728 - val_acc: 0.8036
Epoch 33/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4664 - acc: 0.8464 - val_loss: 0.6676 - val_acc: 0.8053
Epoch 34/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4609 - acc: 0.8468 - val_loss: 0.6626 - val_acc: 0.8102
Epoch 35/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4577 - acc: 0.8471 - val_loss: 0.6577 - val_acc: 0.8069
Epoch 36/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4472 - acc: 0.8531 - val_loss: 0.6556 - val_acc: 0.8053
Epoch 37/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4416 - acc: 0.8531 - val_loss: 0.6518 - val_acc: 0.8036
Epoch 38/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4431 - acc: 0.8527 - val_loss: 0.6488 - val_acc: 0.8086
Epoch 39/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4322 - acc: 0.8586 - val_loss: 0.6463 - val_acc: 0.8069
Epoch 40/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4325 - acc: 0.8600 - val_loss: 0.6418 - val_acc: 0.8069
Epoch 41/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4279 - acc: 0.8590 - val_loss: 0.6382 - val_acc: 0.8053
Epoch 42/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4295 - acc: 0.8524 - val_loss: 0.6350 - val_acc: 0.8036
Epoch 43/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4274 - acc: 0.8562 - val_loss: 0.6321 - val_acc: 0.8053
Epoch 44/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4140 - acc: 0.8642 - val_loss: 0.6322 - val_acc: 0.8053
Epoch 45/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4124 - acc: 0.8611 - val_loss: 0.6294 - val_acc: 0.8069
Epoch 46/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4185 - acc: 0.8590 - val_loss: 0.6266 - val_acc: 0.8053
Epoch 47/100
23/23 [==============================] - 0s 17ms/step - loss: 0.4108 - acc: 0.8618 - val_loss: 0.6244 - val_acc: 0.8020
Epoch 48/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4036 - acc: 0.8677 - val_loss: 0.6215 - val_acc: 0.8069
Epoch 49/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3997 - acc: 0.8653 - val_loss: 0.6182 - val_acc: 0.8102
Epoch 50/100
23/23 [==============================] - 0s 18ms/step - loss: 0.4031 - acc: 0.8632 - val_loss: 0.6181 - val_acc: 0.8003
Epoch 51/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3978 - acc: 0.8670 - val_loss: 0.6136 - val_acc: 0.8069
Epoch 52/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3911 - acc: 0.8722 - val_loss: 0.6106 - val_acc: 0.8069
Epoch 53/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3887 - acc: 0.8691 - val_loss: 0.6107 - val_acc: 0.8069
Epoch 54/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3856 - acc: 0.8757 - val_loss: 0.6075 - val_acc: 0.8020
Epoch 55/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3919 - acc: 0.8663 - val_loss: 0.6058 - val_acc: 0.8053
Epoch 56/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3828 - acc: 0.8698 - val_loss: 0.6040 - val_acc: 0.8086
Epoch 57/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3784 - acc: 0.8747 - val_loss: 0.6025 - val_acc: 0.8053
Epoch 58/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3803 - acc: 0.8691 - val_loss: 0.6012 - val_acc: 0.8102
Epoch 59/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3838 - acc: 0.8670 - val_loss: 0.5993 - val_acc: 0.8119
Epoch 60/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3765 - acc: 0.8767 - val_loss: 0.5970 - val_acc: 0.8152
Epoch 61/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3695 - acc: 0.8750 - val_loss: 0.5967 - val_acc: 0.8119
Epoch 62/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3720 - acc: 0.8750 - val_loss: 0.5946 - val_acc: 0.8168
Epoch 63/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3688 - acc: 0.8726 - val_loss: 0.5939 - val_acc: 0.8152
Epoch 64/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3676 - acc: 0.8750 - val_loss: 0.5924 - val_acc: 0.8135
Epoch 65/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3663 - acc: 0.8788 - val_loss: 0.5908 - val_acc: 0.8135
Epoch 66/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3659 - acc: 0.8799 - val_loss: 0.5887 - val_acc: 0.8152
Epoch 67/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3559 - acc: 0.8844 - val_loss: 0.5873 - val_acc: 0.8185
Epoch 68/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3658 - acc: 0.8781 - val_loss: 0.5852 - val_acc: 0.8201
Epoch 69/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3644 - acc: 0.8799 - val_loss: 0.5853 - val_acc: 0.8168
Epoch 70/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3611 - acc: 0.8785 - val_loss: 0.5855 - val_acc: 0.8168
Epoch 71/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3576 - acc: 0.8781 - val_loss: 0.5842 - val_acc: 0.8135
Epoch 72/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3516 - acc: 0.8816 - val_loss: 0.5802 - val_acc: 0.8218
Epoch 73/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3550 - acc: 0.8813 - val_loss: 0.5799 - val_acc: 0.8234
Epoch 74/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3500 - acc: 0.8830 - val_loss: 0.5792 - val_acc: 0.8284
Epoch 75/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3467 - acc: 0.8813 - val_loss: 0.5789 - val_acc: 0.8218
Epoch 76/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3497 - acc: 0.8841 - val_loss: 0.5761 - val_acc: 0.8251
Epoch 77/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3453 - acc: 0.8847 - val_loss: 0.5762 - val_acc: 0.8234
Epoch 78/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3427 - acc: 0.8854 - val_loss: 0.5751 - val_acc: 0.8251
Epoch 79/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3439 - acc: 0.8872 - val_loss: 0.5753 - val_acc: 0.8251
Epoch 80/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3478 - acc: 0.8729 - val_loss: 0.5735 - val_acc: 0.8251
Epoch 81/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3359 - acc: 0.8809 - val_loss: 0.5720 - val_acc: 0.8284
Epoch 82/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3415 - acc: 0.8781 - val_loss: 0.5717 - val_acc: 0.8300
Epoch 83/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3432 - acc: 0.8806 - val_loss: 0.5728 - val_acc: 0.8234
Epoch 84/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3379 - acc: 0.8854 - val_loss: 0.5720 - val_acc: 0.8251
Epoch 85/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3342 - acc: 0.8914 - val_loss: 0.5716 - val_acc: 0.8284
Epoch 86/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3419 - acc: 0.8820 - val_loss: 0.5707 - val_acc: 0.8300
Epoch 87/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3296 - acc: 0.8907 - val_loss: 0.5709 - val_acc: 0.8300
Epoch 88/100
23/23 [==============================] - 0s 17ms/step - loss: 0.3292 - acc: 0.8907 - val_loss: 0.5694 - val_acc: 0.8284
Epoch 89/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3312 - acc: 0.8851 - val_loss: 0.5687 - val_acc: 0.8317
Epoch 90/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3309 - acc: 0.8841 - val_loss: 0.5687 - val_acc: 0.8284
Epoch 91/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3291 - acc: 0.8879 - val_loss: 0.5686 - val_acc: 0.8300
Epoch 92/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3295 - acc: 0.8823 - val_loss: 0.5683 - val_acc: 0.8284
Epoch 93/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3247 - acc: 0.8879 - val_loss: 0.5651 - val_acc: 0.8333
Epoch 94/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3210 - acc: 0.8889 - val_loss: 0.5641 - val_acc: 0.8284
Epoch 95/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3235 - acc: 0.8823 - val_loss: 0.5644 - val_acc: 0.8317
Epoch 96/100
23/23 [==============================] - 0s 20ms/step - loss: 0.3179 - acc: 0.8945 - val_loss: 0.5632 - val_acc: 0.8333
Epoch 97/100
23/23 [==============================] - 0s 19ms/step - loss: 0.3164 - acc: 0.8952 - val_loss: 0.5628 - val_acc: 0.8300
Epoch 98/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3275 - acc: 0.8886 - val_loss: 0.5616 - val_acc: 0.8317
Epoch 99/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3147 - acc: 0.8931 - val_loss: 0.5607 - val_acc: 0.8300
Epoch 100/100
23/23 [==============================] - 0s 18ms/step - loss: 0.3186 - acc: 0.8889 - val_loss: 0.5601 - val_acc: 0.8317

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 [==============================] - 4s 125ms/step - loss: 0.8033 - acc: 0.7784
[0.803291916847229, 0.7784156203269958]

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/XC519209.wav
Original size of the audio data: 630432
Number of windows for inference: 41

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/XC519209.wav
Result of the window ith:  your model class -> score,  (spec class -> score)
Result of the window 0:   wbwwre1 -> 0.589,    (Outside, rural or natural -> 0.375)
Result of the window 1:   wbwwre1 -> 0.860,    (Environmental noise -> 0.596)
Result of the window 2:   wbwwre1 -> 0.975,    (Insect -> 0.437)
Result of the window 3:   wbwwre1 -> 1.000,    (Insect -> 0.985)
Result of the window 4:   wbwwre1 -> 0.958,    (Cricket -> 0.950)
Result of the window 5:   wbwwre1 -> 0.984,    (Animal -> 0.667)
Result of the window 6:   wbwwre1 -> 0.973,    (Cricket -> 0.619)
Result of the window 7:   wbwwre1 -> 0.984,    (Insect -> 0.952)
Result of the window 8:   wbwwre1 -> 0.900,    (Outside, rural or natural -> 0.365)
Result of the window 9:   wbwwre1 -> 0.903,    (Environmental noise -> 0.735)
Result of the window 10:  wbwwre1 -> 0.988,    (Cricket -> 0.764)
Result of the window 11:  wbwwre1 -> 0.682,    (Cricket -> 0.500)
Result of the window 12:  wbwwre1 -> 1.000,    (Cricket -> 0.928)
Result of the window 13:  wbwwre1 -> 0.946,    (Bird vocalization, bird call, bird song -> 0.393)
Result of the window 14:  wbwwre1 -> 0.954,    (Cricket -> 0.690)
Result of the window 15:  wbwwre1 -> 0.865,    (Insect -> 0.808)
Result of the window 16:  wbwwre1 -> 0.924,    (Cricket -> 0.383)
Result of the window 17:  wbwwre1 -> 0.726,    (Animal -> 0.730)
Result of the window 18:  wbwwre1 -> 0.963,    (Cricket -> 0.508)
Result of the window 19:  wbwwre1 -> 0.815,    (Cricket -> 0.573)
Result of the window 20:  wbwwre1 -> 0.885,    (Insect -> 0.475)
Result of the window 21:  wbwwre1 -> 0.984,    (Insect -> 0.860)
Result of the window 22:  wbwwre1 -> 0.995,    (Cricket -> 0.588)
Result of the window 23:  wbwwre1 -> 0.900,    (Cricket -> 0.758)
Result of the window 24:  wbwwre1 -> 0.845,    (Cricket -> 0.755)
Result of the window 25:  wbwwre1 -> 0.998,    (Bird vocalization, bird call, bird song -> 0.551)
Result of the window 26:  wbwwre1 -> 0.974,    (Wild animals -> 0.511)
Result of the window 27:  wbwwre1 -> 0.752,    (Animal -> 0.391)
Result of the window 28:  wbwwre1 -> 0.556,    (Outside, rural or natural -> 0.333)
Result of the window 29:  wbwwre1 -> 0.550,    (Cricket -> 0.567)
Result of the window 30:  wbwwre1 -> 0.978,    (Environmental noise -> 0.529)
Result of the window 31:  wbwwre1 -> 0.944,    (Insect -> 0.747)
Result of the window 32:  wbwwre1 -> 0.711,    (Outside, rural or natural -> 0.333)
Result of the window 33:  chcant2 -> 0.999,    (Silence -> 1.000)
Result of the window 34:  redcro -> 0.507,     (Silence -> 1.000)
Result of the window 35:  redcro -> 0.587,     (Silence -> 1.000)
Result of the window 36:  chcant2 -> 0.822,    (Speech -> 0.648)
Result of the window 37:  azaspi1 -> 0.479,    (Speech -> 0.908)
Result of the window 38:  chcant2 -> 0.922,    (Speech -> 0.994)
Result of the window 39:  chcant2 -> 0.990,    (Speech -> 0.494)
Result of the window 40:  redcro -> 0.548,     (Silence -> 1.000)
Mean result: wbwwre1 -> 0.7089077234268188

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-05-26 11:11:59.760858: 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/tmp3e3oxy8n/assets
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp3e3oxy8n/assets
2022-05-26 11:12:06.570868: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:357] Ignored output_format.
2022-05-26 11:12:06.570923: 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.