Trigger word detection
Trigger Word Detection
Welcome to the final programming assignment of this specialization!
In this week's videos, you learned about applying deep learning to speech recognition. In this assignment, you will construct a speech dataset and implement an algorithm for trigger word detection (sometimes also called keyword detection, or wakeword detection). Trigger word detection is the technology that allows devices like Amazon Alexa, Google Home, Apple Siri, and Baidu DuerOS to wake up upon hearing a certain word.
For this exercise, our trigger word will be "Activate." Every time it hears you say "activate," it will make a "chiming" sound. By the end of this assignment, you will be able to record a clip of yourself talking, and have the algorithm trigger a chime when it detects you saying "activate."
In this assignment you will learn to:
Structure a speech recognition project
Synthesize and process audio recordings to create train/dev datasets
Train a trigger word detection model and make predictions
Lets get started! Run the following cell to load the package you are going to use.
1 - Data synthesis: Creating a speech dataset
Let's start by building a dataset for your trigger word detection algorithm. A speech dataset should ideally be as close as possible to the application you will want to run it on. In this case, you'd like to detect the word "activate" in working environments (library, home, offices, open-spaces ...). You thus need to create recordings with a mix of positive words ("activate") and negative words (random words other than activate) on different background sounds. Let's see how you can create such a dataset.
1.1 - Listening to the data
One of your friends is helping you out on this project, and they've gone to libraries, cafes, restaurants, homes and offices all around the region to record background noises, as well as snippets of audio of people saying positive/negative words. This dataset includes people speaking in a variety of accents.
In the raw_data directory, you can find a subset of the raw audio files of the positive words, negative words, and background noise. You will use these audio files to synthesize a dataset to train the model. The "activate" directory contains positive examples of people saying the word "activate". The "negatives" directory contains negative examples of people saying random words other than "activate". There is one word per audio recording. The "backgrounds" directory contains 10 second clips of background noise in different environments.
Run the cells below to listen to some examples.
You will use these three type of recordings (positives/negatives/backgrounds) to create a labelled dataset.
1.2 - From audio recordings to spectrograms
What really is an audio recording? A microphone records little variations in air pressure over time, and it is these little variations in air pressure that your ear also perceives as sound. You can think of an audio recording is a long list of numbers measuring the little air pressure changes detected by the microphone. We will use audio sampled at 44100 Hz (or 44100 Hertz). This means the microphone gives us 44100 numbers per second. Thus, a 10 second audio clip is represented by 441000 numbers (= ).
It is quite difficult to figure out from this "raw" representation of audio whether the word "activate" was said. In order to help your sequence model more easily learn to detect triggerwords, we will compute a spectrogram of the audio. The spectrogram tells us how much different frequencies are present in an audio clip at a moment in time.
(If you've ever taken an advanced class on signal processing or on Fourier transforms, a spectrogram is computed by sliding a window over the raw audio signal, and calculates the most active frequencies in each window using a Fourier transform. If you don't understand the previous sentence, don't worry about it.)
Lets see an example.
Figure 1: Spectrogram of an audio recording, where the color shows the degree to which different frequencies are present (loud) in the audio at different points in time. Green squares means a certain frequency is more active or more present in the audio clip (louder); blue squares denote less active frequencies.
The dimension of the output spectrogram depends upon the hyperparameters of the spectrogram software and the length of the input. In this notebook, we will be working with 10 second audio clips as the "standard length" for our training examples. The number of timesteps of the spectrogram will be 5511. You'll see later that the spectrogram will be the input into the network, and so .
Now, you can define:
Note that even with 10 seconds being our default training example length, 10 seconds of time can be discretized to different numbers of value. You've seen 441000 (raw audio) and 5511 (spectrogram). In the former case, each step represents seconds. In the second case, each step represents seconds.
For the 10sec of audio, the key values you will see in this assignment are:
(raw audio)
(spectrogram output, and dimension of input to the neural network).
(used by the
pydub
module to synthesize audio)(the number of steps in the output of the GRU you'll build).
Note that each of these representations correspond to exactly 10 seconds of time. It's just that they are discretizing them to different degrees. All of these are hyperparameters and can be changed (except the 441000, which is a function of the microphone). We have chosen values that are within the standard ranges uses for speech systems.
Consider the number above. This means that for the output of the model, we discretize the 10s into 1375 time-intervals (each one of length s) and try to predict for each of these intervals whether someone recently finished saying "activate."
Consider also the 10000 number above. This corresponds to discretizing the 10sec clip into 10/10000 = 0.001 second itervals. 0.001 seconds is also called 1 millisecond, or 1ms. So when we say we are discretizing according to 1ms intervals, it means we are using 10,000 steps.
1.3 - Generating a single training example
Because speech data is hard to acquire and label, you will synthesize your training data using the audio clips of activates, negatives, and backgrounds. It is quite slow to record lots of 10 second audio clips with random "activates" in it. Instead, it is easier to record lots of positives and negative words, and record background noise separately (or download background noise from free online sources).
To synthesize a single training example, you will:
Pick a random 10 second background audio clip
Randomly insert 0-4 audio clips of "activate" into this 10sec clip
Randomly insert 0-2 audio clips of negative words into this 10sec clip
Because you had synthesized the word "activate" into the background clip, you know exactly when in the 10sec clip the "activate" makes its appearance. You'll see later that this makes it easier to generate the labels as well.
You will use the pydub package to manipulate audio. Pydub converts raw audio files into lists of Pydub data structures (it is not important to know the details here). Pydub uses 1ms as the discretization interval (1ms is 1 millisecond = 1/1000 seconds) which is why a 10sec clip is always represented using 10,000 steps.
Overlaying positive/negative words on the background:
Given a 10sec background clip and a short audio clip (positive or negative word), you need to be able to "add" or "insert" the word's short audio clip onto the background. To ensure audio segments inserted onto the background do not overlap, you will keep track of the times of previously inserted audio clips. You will be inserting multiple clips of positive/negative words onto the background, and you don't want to insert an "activate" or a random word somewhere that overlaps with another clip you had previously added.
For clarity, when you insert a 1sec "activate" onto a 10sec clip of cafe noise, you end up with a 10sec clip that sounds like someone sayng "activate" in a cafe, with "activate" superimposed on the background cafe noise. You do not end up with an 11 sec clip. You'll see later how pydub allows you to do this.
Creating the labels at the same time you overlay:
Recall also that the labels represent whether or not someone has just finished saying "activate." Given a background clip, we can initialize for all , since the clip doesn't contain any "activates."
When you insert or overlay an "activate" clip, you will also update labels for , so that 50 steps of the output now have target label 1. You will train a GRU to detect when someone has finished saying "activate". For example, suppose the synthesized "activate" clip ends at the 5sec mark in the 10sec audio---exactly halfway into the clip. Recall that , so timestep int(1375*0.5)
corresponds to the moment at 5sec into the audio. So, you will set . Further, you would quite satisfied if the GRU detects "activate" anywhere within a short time-internal after this moment, so we actually set 50 consecutive values of the label to 1. Specifically, we have .
This is another reason for synthesizing the training data: It's relatively straightforward to generate these labels as described above. In contrast, if you have 10sec of audio recorded on a microphone, it's quite time consuming for a person to listen to it and mark manually exactly when "activate" finished.
Figure 2
To implement the training set synthesis process, you will use the following helper functions. All of these function will use a 1ms discretization interval, so the 10sec of audio is alwsys discretized into 10,000 steps.
get_random_time_segment(segment_ms)
gets a random time segment in our background audiois_overlapping(segment_time, existing_segments)
checks if a time segment overlaps with existing segmentsinsert_audio_clip(background, audio_clip, existing_times)
inserts an audio segment at a random time in our background audio usingget_random_time_segment
andis_overlapping
insert_ones(y, segment_end_ms)
inserts 1's into our label vector y after the word "activate"
The function get_random_time_segment(segment_ms)
returns a random time segment onto which we can insert an audio clip of duration segment_ms
. Read through the code to make sure you understand what it is doing.
Next, suppose you have inserted audio clips at segments (1000,1800) and (3400,4500). I.e., the first segment starts at step 1000, and ends at step 1800. Now, if we are considering inserting a new audio clip at (3000,3600) does this overlap with one of the previously inserted segments? In this case, (3000,3600) and (3400,4500) overlap, so we should decide against inserting a clip here.
For the purpose of this function, define (100,200) and (200,250) to be overlapping, since they overlap at timestep 200. However, (100,199) and (200,250) are non-overlapping.
Exercise: Implement is_overlapping(segment_time, existing_segments)
to check if a new time segment overlaps with any of the previous segments. You will need to carry out 2 steps:
Create a "False" flag, that you will later set to "True" if you find that there is an overlap.
Loop over the previous_segments' start and end times. Compare these times to the segment's start and end times. If there is an overlap, set the flag defined in (1) as True. You can use:
Hint: There is overlap if the segment starts before the previous segment ends, and the segment ends after the previous segment starts.
Now, lets use the previous helper functions to insert a new audio clip onto the 10sec background at a random time, but making sure that any newly inserted segment doesn't overlap with the previous segments.
Exercise: Implement insert_audio_clip()
to overlay an audio clip onto the background 10sec clip. You will need to carry out 4 steps:
Get a random time segment of the right duration in ms.
Make sure that the time segment does not overlap with any of the previous time segments. If it is overlapping, then go back to step 1 and pick a new time segment.
Add the new time segment to the list of existing time segments, so as to keep track of all the segments you've inserted.
Overlay the audio clip over the background using pydub. We have implemented this for you.
Finally, implement code to update the labels , assuming you just inserted an "activate." In the code below, y
is a (1,1375)
dimensional vector, since .
If the "activate" ended at time step , then set as well as for up to 49 additional consecutive values. However, make sure you don't run off the end of the array and try to update y[0][1375]
, since the valid indices are y[0][0]
through y[0][1374]
because . So if "activate" ends at step 1370, you would get only y[0][1371] = y[0][1372] = y[0][1373] = y[0][1374] = 1
Exercise: Implement insert_ones()
. You can use a for loop. (If you are an expert in py's slice operations, feel free also to use slicing to vectorize this.) If a segment ends at segment_end_ms
(using a 10000 step discretization), to convert it to the indexing for the outputs (using a step discretization), we will use this formula:
Finally, you can use insert_audio_clip
and insert_ones
to create a new training example.
Exercise: Implement create_training_example()
. You will need to carry out the following steps:
Initialize the label vector as a numpy array of zeros and shape .
Initialize the set of existing segments to an empty list.
Randomly select 0 to 4 "activate" audio clips, and insert them onto the 10sec clip. Also insert labels at the correct position in the label vector .
Randomly select 0 to 2 negative audio clips, and insert them into the 10sec clip.
Now you can listen to the training example you created and compare it to the spectrogram generated above.
Expected Output
Finally, you can plot the associated labels for the generated training example.
Expected Output
1.4 - Full training set
You've now implemented the code needed to generate a single training example. We used this process to generate a large training set. To save time, we've already generated a set of training examples.
1.5 - Development set
To test our model, we recorded a development set of 25 examples. While our training data is synthesized, we want to create a development set using the same distribution as the real inputs. Thus, we recorded 25 10-second audio clips of people saying "activate" and other random words, and labeled them by hand. This follows the principle described in Course 3 that we should create the dev set to be as similar as possible to the test set distribution; that's why our dev set uses real rather than synthesized audio.
2 - Model
Now that you've built a dataset, lets write and train a trigger word detection model!
The model will use 1-D convolutional layers, GRU layers, and dense layers. Let's load the packages that will allow you to use these layers in Keras. This might take a minute to load.
2.1 - Build the model
Figure 3
One key step of this model is the 1D convolutional step (near the bottom of Figure 3). It inputs the 5511 step spectrogram, and outputs a 1375 step output, which is then further processed by multiple layers to get the final step output. This layer plays a role similar to the 2D convolutions you saw in Course 4, of extracting low-level features and then possibly generating an output of a smaller dimension.
Computationally, the 1-D conv layer also helps speed up the model because now the GRU has to process only 1375 timesteps rather than 5511 timesteps. The two GRU layers read the sequence of inputs from left to right, then ultimately uses a dense+sigmoid layer to make a prediction for . Because is binary valued (0 or 1), we use a sigmoid output at the last layer to estimate the chance of the output being 1, corresponding to the user having just said "activate."
Note that we use a uni-directional RNN rather than a bi-directional RNN. This is really important for trigger word detection, since we want to be able to detect the trigger word almost immediately after it is said. If we used a bi-directional RNN, we would have to wait for the whole 10sec of audio to be recorded before we could tell if "activate" was said in the first second of the audio clip.
Implementing the model can be done in four steps:
Step 1: CONV layer. Use Conv1D()
to implement this, with 196 filters,
a filter size of 15 (kernel_size=15
), and stride of 4. [See documentation.]
Step 2: First GRU layer. To generate the GRU layer, use:
Setting return_sequences=True
ensures that all the GRU's hidden states are fed to the next layer. Remember to follow this with Dropout and BatchNorm layers.
Step 3: Second GRU layer. This is similar to the previous GRU layer (remember to use return_sequences=True
), but has an extra dropout layer.
Step 4: Create a time-distributed dense layer as follows:
This creates a dense layer followed by a sigmoid, so that the parameters used for the dense layer are the same for every time step. [See documentation.]
Exercise: Implement model()
, the architecture is presented in Figure 3.
Let's print the model summary to keep track of the shapes.
The output of the network is of shape (None, 1375, 1) while the input is (None, 5511, 101). The Conv1D has reduced the number of steps from 5511 at spectrogram to 1375.
2.2 - Fit the model
Trigger word detection takes a long time to train. To save time, we've already trained a model for about 3 hours on a GPU using the architecture you built above, and a large training set of about 4000 examples. Let's load the model.
You can train the model further, using the Adam optimizer and binary cross entropy loss, as follows. This will run quickly because we are training just for one epoch and with a small training set of 26 examples.
2.3 - Test the model
Finally, let's see how your model performs on the dev set.
This looks pretty good! However, accuracy isn't a great metric for this task, since the labels are heavily skewed to 0's, so a neural network that just outputs 0's would get slightly over 90% accuracy. We could define more useful metrics such as F1 score or Precision/Recall. But let's not bother with that here, and instead just empirically see how the model does.
3 - Making Predictions
Now that you have built a working model for trigger word detection, let's use it to make predictions. This code snippet runs audio (saved in a wav file) through the network.
can use your model to make predictions on new audio clips.
You will first need to compute the predictions for an input audio clip.
Exercise: Implement predict_activates(). You will need to do the following:
Compute the spectrogram for the audio file
Use
np.swap
andnp.expand_dims
to reshape your input to size (1, Tx, n_freqs)Use forward propagation on your model to compute the prediction at each output step
Once you've estimated the probability of having detected the word "activate" at each output step, you can trigger a "chiming" sound to play when the probability is above a certain threshold. Further, might be near 1 for many values in a row after "activate" is said, yet we want to chime only once. So we will insert a chime sound at most once every 75 output steps. This will help prevent us from inserting two chimes for a single instance of "activate". (This plays a role similar to non-max suppression from computer vision.)
Exercise: Implement chime_on_activate(). You will need to do the following:
Loop over the predicted probabilities at each output step
When the prediction is larger than the threshold and more than 75 consecutive time steps have passed, insert a "chime" sound onto the original audio clip
Use this code to convert from the 1,375 step discretization to the 10,000 step discretization and insert a "chime" using pydub:
audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio.duration_seconds)*1000)
3.3 - Test on dev examples
Let's explore how our model performs on two unseen audio clips from the development set. Lets first listen to the two dev set clips.
Now lets run the model on these audio clips and see if it adds a chime after "activate"!
Congratulations
You've come to the end of this assignment!
Here's what you should remember:
Data synthesis is an effective way to create a large training set for speech problems, specifically trigger word detection.
Using a spectrogram and optionally a 1D conv layer is a common pre-processing step prior to passing audio data to an RNN, GRU or LSTM.
An end-to-end deep learning approach can be used to built a very effective trigger word detection system.
Congratulations on finishing the fimal assignment!
Thank you for sticking with us through the end and for all the hard work you've put into learning deep learning. We hope you have enjoyed the course!
4 - Try your own example! (OPTIONAL/UNGRADED)
In this optional and ungraded portion of this notebook, you can try your model on your own audio clips!
Record a 10 second audio clip of you saying the word "activate" and other random words, and upload it to the Coursera hub as myaudio.wav
. Be sure to upload the audio as a wav file. If your audio is recorded in a different format (such as mp3) there is free software that you can find online for converting it to wav. If your audio recording is not 10 seconds, the code below will either trim or pad it as needed to make it 10 seconds.
Once you've uploaded your audio file to Coursera, put the path to your file in the variable below.
Finally, use the model to predict when you say activate in the 10 second audio clip, and trigger a chime. If beeps are not being added appropriately, try to adjust the chime_threshold.
Last updated