Have a question? Connect with the community at the TensorFlow Forum Visit Forum

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

Model Maker for the Audio domain needs TensorFlow 2.5 to work.

 pip install -q tflite-model-maker tensorflow==2.5

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__}")
/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/numba/core/errors.py:154: UserWarning: Insufficiently recent colorama version found. Numba requires colorama >= 0.3.9
  warnings.warn(msg)
TensorFlow Version: 2.5.0
Model Maker Version: 0.3.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

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 /tmp/tmpm3o30qio

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 [==============================] - 53s 2s/step - loss: 1.5595 - acc: 0.3309 - val_loss: 1.3238 - val_acc: 0.6259
Epoch 2/100
21/21 [==============================] - 0s 22ms/step - loss: 1.2949 - acc: 0.4796 - val_loss: 1.1878 - val_acc: 0.6497
Epoch 3/100
21/21 [==============================] - 1s 23ms/step - loss: 1.1536 - acc: 0.5770 - val_loss: 1.0982 - val_acc: 0.6837
Epoch 4/100
21/21 [==============================] - 0s 23ms/step - loss: 1.0386 - acc: 0.6460 - val_loss: 1.0301 - val_acc: 0.7188
Epoch 5/100
21/21 [==============================] - 0s 23ms/step - loss: 0.9557 - acc: 0.6992 - val_loss: 0.9811 - val_acc: 0.7358
Epoch 6/100
21/21 [==============================] - 0s 23ms/step - loss: 0.8935 - acc: 0.7211 - val_loss: 0.9427 - val_acc: 0.7438
Epoch 7/100
21/21 [==============================] - 0s 23ms/step - loss: 0.8410 - acc: 0.7481 - val_loss: 0.9169 - val_acc: 0.7449
Epoch 8/100
21/21 [==============================] - 0s 23ms/step - loss: 0.7951 - acc: 0.7589 - val_loss: 0.8943 - val_acc: 0.7517
Epoch 9/100
21/21 [==============================] - 1s 24ms/step - loss: 0.7527 - acc: 0.7673 - val_loss: 0.8724 - val_acc: 0.7574
Epoch 10/100
21/21 [==============================] - 0s 23ms/step - loss: 0.7195 - acc: 0.7862 - val_loss: 0.8651 - val_acc: 0.7494
Epoch 11/100
21/21 [==============================] - 0s 23ms/step - loss: 0.6955 - acc: 0.7866 - val_loss: 0.8453 - val_acc: 0.7608
Epoch 12/100
21/21 [==============================] - 1s 23ms/step - loss: 0.6680 - acc: 0.7966 - val_loss: 0.8362 - val_acc: 0.7596
Epoch 13/100
21/21 [==============================] - 0s 22ms/step - loss: 0.6432 - acc: 0.8155 - val_loss: 0.8211 - val_acc: 0.7676
Epoch 14/100
21/21 [==============================] - 0s 22ms/step - loss: 0.6329 - acc: 0.7962 - val_loss: 0.8135 - val_acc: 0.7710
Epoch 15/100
21/21 [==============================] - 0s 23ms/step - loss: 0.6101 - acc: 0.8151 - val_loss: 0.8050 - val_acc: 0.7687
Epoch 16/100
21/21 [==============================] - 1s 23ms/step - loss: 0.5986 - acc: 0.8178 - val_loss: 0.8007 - val_acc: 0.7619
Epoch 17/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5751 - acc: 0.8282 - val_loss: 0.7930 - val_acc: 0.7630
Epoch 18/100
21/21 [==============================] - 0s 23ms/step - loss: 0.5625 - acc: 0.8278 - val_loss: 0.7874 - val_acc: 0.7630
Epoch 19/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5466 - acc: 0.8359 - val_loss: 0.7835 - val_acc: 0.7608
Epoch 20/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5424 - acc: 0.8324 - val_loss: 0.7765 - val_acc: 0.7574
Epoch 21/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5264 - acc: 0.8463 - val_loss: 0.7744 - val_acc: 0.7540
Epoch 22/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5104 - acc: 0.8555 - val_loss: 0.7721 - val_acc: 0.7540
Epoch 23/100
21/21 [==============================] - 0s 22ms/step - loss: 0.5064 - acc: 0.8544 - val_loss: 0.7718 - val_acc: 0.7494
Epoch 24/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4990 - acc: 0.8471 - val_loss: 0.7649 - val_acc: 0.7517
Epoch 25/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4929 - acc: 0.8463 - val_loss: 0.7619 - val_acc: 0.7472
Epoch 26/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4763 - acc: 0.8552 - val_loss: 0.7554 - val_acc: 0.7472
Epoch 27/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4738 - acc: 0.8656 - val_loss: 0.7629 - val_acc: 0.7370
Epoch 28/100
21/21 [==============================] - 0s 22ms/step - loss: 0.4591 - acc: 0.8675 - val_loss: 0.7580 - val_acc: 0.7370
Epoch 29/100
21/21 [==============================] - 0s 23ms/step - loss: 0.4605 - acc: 0.8586 - val_loss: 0.7553 - val_acc: 0.7358
Epoch 30/100
21/21 [==============================] - 0s 23ms/step - loss: 0.4541 - acc: 0.8575 - val_loss: 0.7565 - val_acc: 0.7336
Epoch 31/100
21/21 [==============================] - 1s 23ms/step - loss: 0.4439 - acc: 0.8771 - val_loss: 0.7583 - val_acc: 0.7313
Epoch 32/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4357 - acc: 0.8729 - val_loss: 0.7553 - val_acc: 0.7313
Epoch 33/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4375 - acc: 0.8690 - val_loss: 0.7514 - val_acc: 0.7324
Epoch 34/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4308 - acc: 0.8648 - val_loss: 0.7542 - val_acc: 0.7256
Epoch 35/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4184 - acc: 0.8725 - val_loss: 0.7509 - val_acc: 0.7313
Epoch 36/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4202 - acc: 0.8710 - val_loss: 0.7557 - val_acc: 0.7211
Epoch 37/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4162 - acc: 0.8702 - val_loss: 0.7502 - val_acc: 0.7290
Epoch 38/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4101 - acc: 0.8744 - val_loss: 0.7522 - val_acc: 0.7132
Epoch 39/100
21/21 [==============================] - 0s 21ms/step - loss: 0.4014 - acc: 0.8763 - val_loss: 0.7538 - val_acc: 0.7109
Epoch 40/100
21/21 [==============================] - 0s 23ms/step - loss: 0.4093 - acc: 0.8744 - val_loss: 0.7483 - val_acc: 0.7188
Epoch 41/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3981 - acc: 0.8748 - val_loss: 0.7466 - val_acc: 0.7211
Epoch 42/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3937 - acc: 0.8814 - val_loss: 0.7493 - val_acc: 0.7109
Epoch 43/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3874 - acc: 0.8817 - val_loss: 0.7492 - val_acc: 0.7120
Epoch 44/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3878 - acc: 0.8771 - val_loss: 0.7486 - val_acc: 0.7154
Epoch 45/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3892 - acc: 0.8814 - val_loss: 0.7500 - val_acc: 0.7098
Epoch 46/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3788 - acc: 0.8848 - val_loss: 0.7517 - val_acc: 0.7029
Epoch 47/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3708 - acc: 0.8921 - val_loss: 0.7530 - val_acc: 0.6984
Epoch 48/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3757 - acc: 0.8802 - val_loss: 0.7496 - val_acc: 0.7007
Epoch 49/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3716 - acc: 0.8806 - val_loss: 0.7548 - val_acc: 0.6961
Epoch 50/100
21/21 [==============================] - 0s 23ms/step - loss: 0.3663 - acc: 0.8921 - val_loss: 0.7498 - val_acc: 0.6995
Epoch 51/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3640 - acc: 0.8810 - val_loss: 0.7494 - val_acc: 0.7007
Epoch 52/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3578 - acc: 0.8918 - val_loss: 0.7507 - val_acc: 0.6961
Epoch 53/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3611 - acc: 0.8871 - val_loss: 0.7533 - val_acc: 0.6916
Epoch 54/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3542 - acc: 0.8867 - val_loss: 0.7523 - val_acc: 0.6905
Epoch 55/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3519 - acc: 0.8898 - val_loss: 0.7523 - val_acc: 0.6916
Epoch 56/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3442 - acc: 0.8948 - val_loss: 0.7566 - val_acc: 0.6859
Epoch 57/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3526 - acc: 0.8875 - val_loss: 0.7504 - val_acc: 0.6939
Epoch 58/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3493 - acc: 0.8871 - val_loss: 0.7583 - val_acc: 0.6825
Epoch 59/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3523 - acc: 0.8810 - val_loss: 0.7565 - val_acc: 0.6882
Epoch 60/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3448 - acc: 0.8894 - val_loss: 0.7533 - val_acc: 0.6882
Epoch 61/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3325 - acc: 0.8925 - val_loss: 0.7577 - val_acc: 0.6859
Epoch 62/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3350 - acc: 0.8956 - val_loss: 0.7570 - val_acc: 0.6848
Epoch 63/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3284 - acc: 0.8956 - val_loss: 0.7580 - val_acc: 0.6859
Epoch 64/100
21/21 [==============================] - 0s 23ms/step - loss: 0.3273 - acc: 0.8964 - val_loss: 0.7533 - val_acc: 0.6871
Epoch 65/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3301 - acc: 0.8964 - val_loss: 0.7528 - val_acc: 0.6916
Epoch 66/100
21/21 [==============================] - 0s 21ms/step - loss: 0.3328 - acc: 0.8945 - val_loss: 0.7557 - val_acc: 0.6859
Epoch 67/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3235 - acc: 0.8979 - val_loss: 0.7570 - val_acc: 0.6848
Epoch 68/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3385 - acc: 0.8956 - val_loss: 0.7621 - val_acc: 0.6769
Epoch 69/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3226 - acc: 0.8968 - val_loss: 0.7587 - val_acc: 0.6780
Epoch 70/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3248 - acc: 0.8906 - val_loss: 0.7571 - val_acc: 0.6848
Epoch 71/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3184 - acc: 0.8925 - val_loss: 0.7537 - val_acc: 0.6882
Epoch 72/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3129 - acc: 0.9025 - val_loss: 0.7577 - val_acc: 0.6803
Epoch 73/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3144 - acc: 0.9018 - val_loss: 0.7600 - val_acc: 0.6780
Epoch 74/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3216 - acc: 0.8937 - val_loss: 0.7598 - val_acc: 0.6814
Epoch 75/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3180 - acc: 0.8956 - val_loss: 0.7667 - val_acc: 0.6735
Epoch 76/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3167 - acc: 0.8956 - val_loss: 0.7641 - val_acc: 0.6780
Epoch 77/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3149 - acc: 0.8979 - val_loss: 0.7630 - val_acc: 0.6791
Epoch 78/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3092 - acc: 0.9014 - val_loss: 0.7662 - val_acc: 0.6769
Epoch 79/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3130 - acc: 0.8956 - val_loss: 0.7636 - val_acc: 0.6769
Epoch 80/100
21/21 [==============================] - 0s 23ms/step - loss: 0.3099 - acc: 0.9014 - val_loss: 0.7665 - val_acc: 0.6746
Epoch 81/100
21/21 [==============================] - 1s 23ms/step - loss: 0.3039 - acc: 0.9025 - val_loss: 0.7649 - val_acc: 0.6769
Epoch 82/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2946 - acc: 0.9076 - val_loss: 0.7675 - val_acc: 0.6757
Epoch 83/100
21/21 [==============================] - 1s 23ms/step - loss: 0.2921 - acc: 0.9002 - val_loss: 0.7645 - val_acc: 0.6769
Epoch 84/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2999 - acc: 0.9052 - val_loss: 0.7692 - val_acc: 0.6701
Epoch 85/100
21/21 [==============================] - 1s 23ms/step - loss: 0.2909 - acc: 0.9006 - val_loss: 0.7645 - val_acc: 0.6780
Epoch 86/100
21/21 [==============================] - 0s 22ms/step - loss: 0.3003 - acc: 0.9049 - val_loss: 0.7701 - val_acc: 0.6667
Epoch 87/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2949 - acc: 0.9033 - val_loss: 0.7739 - val_acc: 0.6633
Epoch 88/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2893 - acc: 0.9102 - val_loss: 0.7776 - val_acc: 0.6599
Epoch 89/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2862 - acc: 0.9095 - val_loss: 0.7717 - val_acc: 0.6689
Epoch 90/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2916 - acc: 0.9076 - val_loss: 0.7784 - val_acc: 0.6610
Epoch 91/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2998 - acc: 0.9052 - val_loss: 0.7798 - val_acc: 0.6610
Epoch 92/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2919 - acc: 0.8975 - val_loss: 0.7684 - val_acc: 0.6689
Epoch 93/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2940 - acc: 0.9010 - val_loss: 0.7741 - val_acc: 0.6644
Epoch 94/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2830 - acc: 0.9102 - val_loss: 0.7729 - val_acc: 0.6667
Epoch 95/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2970 - acc: 0.8975 - val_loss: 0.7748 - val_acc: 0.6655
Epoch 96/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2887 - acc: 0.9049 - val_loss: 0.7800 - val_acc: 0.6610
Epoch 97/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2838 - acc: 0.9049 - val_loss: 0.7638 - val_acc: 0.6746
Epoch 98/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2907 - acc: 0.9022 - val_loss: 0.7788 - val_acc: 0.6610
Epoch 99/100
21/21 [==============================] - 0s 22ms/step - loss: 0.2861 - acc: 0.9037 - val_loss: 0.7817 - val_acc: 0.6610
Epoch 100/100
21/21 [==============================] - 1s 23ms/step - loss: 0.2843 - acc: 0.9102 - val_loss: 0.7764 - val_acc: 0.6644

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 [==============================] - 13s 432ms/step - loss: 0.9247 - acc: 0.7566
[0.9246906042098999, 0.7566016316413879]

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=(1, 521) dtype=float32 (created by layer 'keras_layer')>, <KerasTensor: shape=(1, 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: Azara's Spinetail
Bird code: azaspi1

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/tutorials/dataset/small_birds_dataset/test/azaspi1/XC746.wav
Original size of the audio data: 229728
Number of windows for inference: 15

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/tutorials/dataset/small_birds_dataset/test/azaspi1/XC746.wav
Result of the window ith:  your model class -> score,  (spec class -> score)
Result of the window 0:   azaspi1 -> 0.938,    (Animal -> 0.608)
Result of the window 1:   azaspi1 -> 0.978,    (Animal -> 0.730)
Result of the window 2:   azaspi1 -> 0.425,    (Animal -> 0.412)
Result of the window 3:   wbwwre1 -> 0.796,    (Outside, rural or natural -> 0.414)
Result of the window 4:   houspa -> 0.411,     (Animal -> 0.668)
Result of the window 5:   azaspi1 -> 0.778,    (Animal -> 0.840)
Result of the window 6:   wbwwre1 -> 0.610,    (Animal -> 0.552)
Result of the window 7:   wbwwre1 -> 0.548,    (Animal -> 0.642)
Result of the window 8:   houspa -> 0.637,     (Animal -> 0.862)
Result of the window 9:   wbwwre1 -> 0.596,    (Outside, rural or natural -> 0.474)
Result of the window 10:  azaspi1 -> 0.605,    (Animal -> 0.765)
Result of the window 11:  azaspi1 -> 0.613,    (Animal -> 0.746)
Result of the window 12:  azaspi1 -> 0.521,    (Animal -> 0.514)
Result of the window 13:  houspa -> 0.691,     (Animal -> 0.737)
Result of the window 14:  azaspi1 -> 0.969,    (Animal -> 0.729)
Mean result: azaspi1 -> 0.476293683052063

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
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: /tmp/tmpab_pbmkp/assets
INFO:tensorflow:Assets written to: /tmp/tmpab_pbmkp/assets
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.