wesfggfd commited on
Commit
6fd15d9
·
verified ·
1 Parent(s): 0b8419e

Upload 60 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +27 -0
  2. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/.ipynb_checkpoints/Trigger_word_detection_v2a-checkpoint.ipynb +1836 -0
  3. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/Trigger_word_detection_v2a.ipynb +3 -0
  4. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_dev/X_dev.npy +3 -0
  5. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_dev/Y_dev.npy +3 -0
  6. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/.DS_Store +0 -0
  7. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/X.npy +3 -0
  8. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/Y.npy +3 -0
  9. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/__pycache__/td_utils.cpython-37.pyc +0 -0
  10. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/__pycache__/test_utils.cpython-37.pyc +0 -0
  11. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/chime.wav +3 -0
  12. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/example_train.wav +3 -0
  13. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/insert_reference.wav +3 -0
  14. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/my_audio.wav +3 -0
  15. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/train_reference.wav +3 -0
  16. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/chime_output.wav +3 -0
  17. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/generateTestCases.py +159 -0
  18. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/label_diagram.png +0 -0
  19. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/model.png +3 -0
  20. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/ones_reference.png +0 -0
  21. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/sound.png +3 -0
  22. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/spectrogram.png +0 -0
  23. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/train_label.png +0 -0
  24. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/train_reference.png +3 -0
  25. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/insert_test.wav +3 -0
  26. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/.DS_Store +0 -0
  27. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model.h5 +3 -0
  28. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model.json +1 -0
  29. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model_new8.h5 +3 -0
  30. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model_new8.json +1 -0
  31. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/tr_model.h5 +3 -0
  32. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/.DS_Store +0 -0
  33. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1.wav +3 -0
  34. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1_act2.wav +0 -0
  35. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1_act3.wav +3 -0
  36. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2.wav +3 -0
  37. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2_act2.wav +0 -0
  38. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2_act3.wav +3 -0
  39. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3.wav +3 -0
  40. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3_act2.wav +0 -0
  41. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3_act3.wav +3 -0
  42. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/4_act2.wav +0 -0
  43. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/1.wav +3 -0
  44. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/2.wav +3 -0
  45. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/1.wav +3 -0
  46. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/2.wav +3 -0
  47. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/1.wav +0 -0
  48. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/1_0.wav +3 -0
  49. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/2.wav +0 -0
  50. Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/2_1.wav +0 -0
.gitattributes CHANGED
@@ -76,3 +76,30 @@ Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_mech
76
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_model.png filter=lfs diff=lfs merge=lfs -text
77
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention.png filter=lfs diff=lfs merge=lfs -text
78
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention2.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_model.png filter=lfs diff=lfs merge=lfs -text
77
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention.png filter=lfs diff=lfs merge=lfs -text
78
  Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention2.png filter=lfs diff=lfs merge=lfs -text
79
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/chime.wav filter=lfs diff=lfs merge=lfs -text
80
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/example_train.wav filter=lfs diff=lfs merge=lfs -text
81
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/insert_reference.wav filter=lfs diff=lfs merge=lfs -text
82
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/my_audio.wav filter=lfs diff=lfs merge=lfs -text
83
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/train_reference.wav filter=lfs diff=lfs merge=lfs -text
84
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/chime_output.wav filter=lfs diff=lfs merge=lfs -text
85
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/model.png filter=lfs diff=lfs merge=lfs -text
86
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/sound.png filter=lfs diff=lfs merge=lfs -text
87
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/train_reference.png filter=lfs diff=lfs merge=lfs -text
88
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/insert_test.wav filter=lfs diff=lfs merge=lfs -text
89
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1_act3.wav filter=lfs diff=lfs merge=lfs -text
90
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1.wav filter=lfs diff=lfs merge=lfs -text
91
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2_act3.wav filter=lfs diff=lfs merge=lfs -text
92
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2.wav filter=lfs diff=lfs merge=lfs -text
93
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3_act3.wav filter=lfs diff=lfs merge=lfs -text
94
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3.wav filter=lfs diff=lfs merge=lfs -text
95
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/1.wav filter=lfs diff=lfs merge=lfs -text
96
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/2.wav filter=lfs diff=lfs merge=lfs -text
97
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/1.wav filter=lfs diff=lfs merge=lfs -text
98
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/2.wav filter=lfs diff=lfs merge=lfs -text
99
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/1_0.wav filter=lfs diff=lfs merge=lfs -text
100
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/3.wav filter=lfs diff=lfs merge=lfs -text
101
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/4_0.wav filter=lfs diff=lfs merge=lfs -text
102
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/5_1.wav filter=lfs diff=lfs merge=lfs -text
103
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/tmp.wav filter=lfs diff=lfs merge=lfs -text
104
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/train.wav filter=lfs diff=lfs merge=lfs -text
105
+ Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/Trigger_word_detection_v2a.ipynb filter=lfs diff=lfs merge=lfs -text
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/.ipynb_checkpoints/Trigger_word_detection_v2a-checkpoint.ipynb ADDED
@@ -0,0 +1,1836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## Trigger Word Detection\n",
8
+ "\n",
9
+ "Welcome to the second and last programming assignment of Week 3! \n",
10
+ "\n",
11
+ "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 wake word detection). \n",
12
+ "\n",
13
+ "* 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. \n",
14
+ "* For this exercise, our trigger word will be \"activate\". Every time it hears you say \"activate\", it will make a \"chiming\" sound. \n",
15
+ "* 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\". \n",
16
+ "* After completing this assignment, perhaps you can also extend it to run on your laptop so that every time you say \"activate\" it starts up your favorite app, or turns on a network connected lamp in your house, or triggers some other event? \n",
17
+ "\n",
18
+ "<img src=\"images/sound.png\" style=\"width:1000px;height:150px;\">\n",
19
+ "\n",
20
+ "In this assignment you will learn to: \n",
21
+ "- Structure a speech recognition project\n",
22
+ "- Synthesize and process audio recordings to create train/dev datasets\n",
23
+ "- Train a trigger word detection model and make predictions\n",
24
+ "\n",
25
+ "Let's get started!\n",
26
+ "\n",
27
+ "## Important Note on Submission to the AutoGrader\n",
28
+ "\n",
29
+ "Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:\n",
30
+ "\n",
31
+ "1. You have not added any _extra_ `print` statement(s) in the assignment.\n",
32
+ "2. You have not added any _extra_ code cell(s) in the assignment.\n",
33
+ "3. You have not changed any of the function parameters.\n",
34
+ "4. You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.\n",
35
+ "5. You are not changing the assignment code where it is not required, like creating _extra_ variables.\n",
36
+ "\n",
37
+ "If you do any of the following, you will get something like, `Grader Error: Grader feedback not found` (or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these [instructions](https://www.coursera.org/learn/nlp-sequence-models/supplement/qHIve/h-ow-to-refresh-your-workspace)."
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "markdown",
42
+ "metadata": {},
43
+ "source": [
44
+ "## Table of Contents\n",
45
+ "\n",
46
+ "- [Packages](#0)\n",
47
+ "- [1 - Data synthesis: Creating a Speech Dataset](#1)\n",
48
+ " - [1.1 - Listening to the Data](#1-1)\n",
49
+ " - [1.2 - From Audio Recordings to Spectrograms](#1-2)\n",
50
+ " - [1.3 - Generating a Single Training Example](#1-3)\n",
51
+ " - [Exercise 1 - is_overlapping](#ex-1)\n",
52
+ " - [Exercise 2 - insert_audio_clip](#ex-2)\n",
53
+ " - [Exercise 3 - insert_ones](#ex-3)\n",
54
+ " - [Exercise 4 - create_training_example](#ex-4)\n",
55
+ " - [1.4 - Full Training Set](#1-4)\n",
56
+ " - [1.5 - Development Set](#1-5)\n",
57
+ "- [2 - The Model](#2)\n",
58
+ " - [2.1 - Build the Model](#2-1)\n",
59
+ " - [Exercise 5 - modelf](#ex-5)\n",
60
+ " - [2.2 - Fit the Model](#2-2)\n",
61
+ " - [2.3 - Test the Model](#2-3)\n",
62
+ "- [3 - Making Predictions](#3)\n",
63
+ " - [3.1 - Test on Dev Examples](#3-1)\n",
64
+ "- [4 - Try Your Own Example! (OPTIONAL/UNGRADED)](#4)"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "metadata": {},
70
+ "source": [
71
+ "<a name='0'></a>\n",
72
+ "## Packages"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "execution_count": null,
78
+ "metadata": {
79
+ "deletable": false,
80
+ "editable": false
81
+ },
82
+ "outputs": [],
83
+ "source": [
84
+ "### v2.2"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": null,
90
+ "metadata": {},
91
+ "outputs": [],
92
+ "source": [
93
+ "import numpy as np\n",
94
+ "from pydub import AudioSegment\n",
95
+ "import random\n",
96
+ "import sys\n",
97
+ "import io\n",
98
+ "import os\n",
99
+ "import glob\n",
100
+ "import IPython\n",
101
+ "from td_utils import *\n",
102
+ "%matplotlib inline"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {},
108
+ "source": [
109
+ "<a name='1'></a>\n",
110
+ "## 1 - Data synthesis: Creating a Speech Dataset \n",
111
+ "\n",
112
+ "Let's start by building a dataset for your trigger word detection algorithm. \n",
113
+ "* A speech dataset should ideally be as close as possible to the application you will want to run it on. \n",
114
+ "* In this case, you'd like to detect the word \"activate\" in working environments (library, home, offices, open-spaces ...). \n",
115
+ "* Therefore, you 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. \n",
116
+ "\n",
117
+ "<a name='1-1'></a>\n",
118
+ "### 1.1 - Listening to the Data \n",
119
+ "\n",
120
+ "* 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. \n",
121
+ "* 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. \n",
122
+ " * The \"activate\" directory contains positive examples of people saying the word \"activate\". \n",
123
+ " * The \"negatives\" directory contains negative examples of people saying random words other than \"activate\". \n",
124
+ " * There is one word per audio recording. \n",
125
+ " * The \"backgrounds\" directory contains 10 second clips of background noise in different environments.\n",
126
+ "\n",
127
+ "Run the cells below to listen to some examples."
128
+ ]
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "execution_count": null,
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "IPython.display.Audio(\"./raw_data/activates/1.wav\")"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "metadata": {},
143
+ "outputs": [],
144
+ "source": [
145
+ "IPython.display.Audio(\"./raw_data/negatives/4.wav\")"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "execution_count": null,
151
+ "metadata": {
152
+ "scrolled": false
153
+ },
154
+ "outputs": [],
155
+ "source": [
156
+ "IPython.display.Audio(\"./raw_data/backgrounds/1.wav\")"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "You will use these three types of recordings (positives/negatives/backgrounds) to create a labeled dataset."
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "markdown",
168
+ "metadata": {},
169
+ "source": [
170
+ "<a name='1-2'></a>\n",
171
+ "### 1.2 - From Audio Recordings to Spectrograms\n",
172
+ "\n",
173
+ "What really is an audio recording? \n",
174
+ "* 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. \n",
175
+ "* You can think of an audio recording as a long list of numbers measuring the little air pressure changes detected by the microphone. \n",
176
+ "* We will use audio sampled at 44100 Hz (or 44100 Hertz). \n",
177
+ " * This means the microphone gives us 44,100 numbers per second. \n",
178
+ " * Thus, a 10 second audio clip is represented by 441,000 numbers (= $10 \\times 44,100$). \n",
179
+ "\n",
180
+ "#### Spectrogram\n",
181
+ "* It is quite difficult to figure out from this \"raw\" representation of audio whether the word \"activate\" was said. \n",
182
+ "* In order to help your sequence model more easily learn to detect trigger words, we will compute a *spectrogram* of the audio. \n",
183
+ "* The spectrogram tells us how much different frequencies are present in an audio clip at any moment in time. \n",
184
+ "* If you've ever taken an advanced class on signal processing or on Fourier transforms:\n",
185
+ " * A spectrogram is computed by sliding a window over the raw audio signal, and calculating the most active frequencies in each window using a Fourier transform. \n",
186
+ " * If you don't understand the previous sentence, don't worry about it.\n",
187
+ "\n",
188
+ "Let's look at an example. "
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "execution_count": null,
194
+ "metadata": {},
195
+ "outputs": [],
196
+ "source": [
197
+ "IPython.display.Audio(\"audio_examples/example_train.wav\")"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": null,
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "x = graph_spectrogram(\"audio_examples/example_train.wav\")"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "markdown",
211
+ "metadata": {},
212
+ "source": [
213
+ "The graph above represents how active each frequency is (y axis) over a number of time-steps (x axis). \n",
214
+ "\n",
215
+ "<img src=\"images/spectrogram.png\" style=\"width:500px;height:200px;\">\n",
216
+ "<center> **Figure 1**: Spectrogram of an audio recording </center>\n",
217
+ "\n",
218
+ "\n",
219
+ "* The color in the spectrogram shows the degree to which different frequencies are present (loud) in the audio at different points in time. \n",
220
+ "* Green means a certain frequency is more active or more present in the audio clip (louder).\n",
221
+ "* Blue squares denote less active frequencies.\n",
222
+ "* The dimension of the output spectrogram depends upon the hyperparameters of the spectrogram software and the length of the input. \n",
223
+ "* In this notebook, we will be working with 10 second audio clips as the \"standard length\" for our training examples. \n",
224
+ " * The number of timesteps of the spectrogram will be 5511. \n",
225
+ " * You'll see later that the spectrogram will be the input $x$ into the network, and so $T_x = 5511$."
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": null,
231
+ "metadata": {},
232
+ "outputs": [],
233
+ "source": [
234
+ "_, data = wavfile.read(\"audio_examples/example_train.wav\")\n",
235
+ "print(\"Time steps in audio recording before spectrogram\", data[:,0].shape)\n",
236
+ "print(\"Time steps in input after spectrogram\", x.shape)"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "markdown",
241
+ "metadata": {},
242
+ "source": [
243
+ "Now, you can define:"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "execution_count": null,
249
+ "metadata": {},
250
+ "outputs": [],
251
+ "source": [
252
+ "Tx = 5511 # The number of time steps input to the model from the spectrogram\n",
253
+ "n_freq = 101 # Number of frequencies input to the model at each time step of the spectrogram"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "#### Dividing into time-intervals\n",
261
+ "Note that we may divide a 10 second interval of time with different units (steps).\n",
262
+ "* Raw audio divides 10 seconds into 441,000 units.\n",
263
+ "* A spectrogram divides 10 seconds into 5,511 units.\n",
264
+ " * $T_x = 5511$\n",
265
+ "* You will use a Python module `pydub` to synthesize audio, and it divides 10 seconds into 10,000 units.\n",
266
+ "* The output of our model will divide 10 seconds into 1,375 units.\n",
267
+ " * $T_y = 1375$\n",
268
+ " * For each of the 1375 time steps, the model predicts whether someone recently finished saying the trigger word \"activate\". \n",
269
+ "* All of these are hyperparameters and can be changed (except the 441000, which is a function of the microphone). \n",
270
+ "* We have chosen values that are within the standard range used for speech systems."
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "metadata": {},
277
+ "outputs": [],
278
+ "source": [
279
+ "Ty = 1375 # The number of time steps in the output of our model"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "markdown",
284
+ "metadata": {},
285
+ "source": [
286
+ "<a name='1-3'></a>\n",
287
+ "### 1.3 - Generating a Single Training Example\n",
288
+ "\n",
289
+ "#### Benefits of synthesizing data\n",
290
+ "Because speech data is hard to acquire and label, you will synthesize your training data using the audio clips of activates, negatives, and backgrounds. \n",
291
+ "* It is quite slow to record lots of 10 second audio clips with random \"activates\" in it. \n",
292
+ "* 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). \n",
293
+ "\n",
294
+ "#### Process for Synthesizing an audio clip\n",
295
+ "* To synthesize a single training example, you will:\n",
296
+ " - Pick a random 10 second background audio clip\n",
297
+ " - Randomly insert 0-4 audio clips of \"activate\" into this 10 sec. clip\n",
298
+ " - Randomly insert 0-2 audio clips of negative words into this 10 sec. clip\n",
299
+ "* Because you had synthesized the word \"activate\" into the background clip, you know exactly when in the 10 second clip the \"activate\" makes its appearance. \n",
300
+ " * You'll see later that this makes it easier to generate the labels $y^{\\langle t \\rangle}$ as well. \n",
301
+ "\n",
302
+ "#### Pydub\n",
303
+ "* You will use the pydub package to manipulate audio. \n",
304
+ "* Pydub converts raw audio files into lists of Pydub data structures.\n",
305
+ " * Don't worry about the details of the data structures.\n",
306
+ "* Pydub uses 1ms as the discretization interval (1 ms is 1 millisecond = 1/1000 seconds).\n",
307
+ " * This is why a 10 second clip is always represented using 10,000 steps. "
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": null,
313
+ "metadata": {},
314
+ "outputs": [],
315
+ "source": [
316
+ "# Load audio segments using pydub \n",
317
+ "activates, negatives, backgrounds = load_raw_audio('./raw_data/')\n",
318
+ "\n",
319
+ "print(\"background len should be 10,000, since it is a 10 sec clip\\n\" + str(len(backgrounds[0])),\"\\n\")\n",
320
+ "print(\"activate[0] len may be around 1000, since an `activate` audio clip is usually around 1 second (but varies a lot) \\n\" + str(len(activates[0])),\"\\n\")\n",
321
+ "print(\"activate[1] len: different `activate` clips can have different lengths\\n\" + str(len(activates[1])),\"\\n\")"
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "markdown",
326
+ "metadata": {},
327
+ "source": [
328
+ "#### Overlaying positive/negative 'word' audio clips on top of the background audio\n",
329
+ "\n",
330
+ "* Given a 10 second background clip and a short audio clip containing a positive or negative word, you need to be able to \"add\" the word audio clip on top of the background audio.\n",
331
+ "* You will be inserting multiple clips of positive/negative words into 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. \n",
332
+ " * To ensure that the 'word' audio segments do not overlap when inserted, you will keep track of the times of previously inserted audio clips. \n",
333
+ "* To be clear, when you insert a 1 second \"activate\" onto a 10 second clip of cafe noise, **you do not end up with an 11 sec clip.** \n",
334
+ " * The resulting audio clip is still 10 seconds long.\n",
335
+ " * You'll see later how pydub allows you to do this. "
336
+ ]
337
+ },
338
+ {
339
+ "cell_type": "markdown",
340
+ "metadata": {},
341
+ "source": [
342
+ "#### Label the positive/negative words\n",
343
+ "* Recall that the labels $y^{\\langle t \\rangle}$ represent whether or not someone has just finished saying \"activate\". \n",
344
+ " * $y^{\\langle t \\rangle} = 1$ when that clip has finished saying \"activate\".\n",
345
+ " * Given a background clip, we can initialize $y^{\\langle t \\rangle}=0$ for all $t$, since the clip doesn't contain any \"activate\". \n",
346
+ "* When you insert or overlay an \"activate\" clip, you will also update labels for $y^{\\langle t \\rangle}$.\n",
347
+ " * Rather than updating the label of a single time step, we will update 50 steps of the output to have target label 1. \n",
348
+ " * Recall from the lecture on trigger word detection that updating several consecutive time steps can make the training data more balanced.\n",
349
+ "* You will train a GRU (Gated Recurrent Unit) to detect when someone has **finished** saying \"activate\". \n",
350
+ "\n",
351
+ "##### Example\n",
352
+ "* Suppose the synthesized \"activate\" clip ends at the 5 second mark in the 10 second audio - exactly halfway into the clip. \n",
353
+ "* Recall that $T_y = 1375$, so timestep $687 = $ `int(1375*0.5)` corresponds to the moment 5 seconds into the audio clip. \n",
354
+ "* Set $y^{\\langle 688 \\rangle} = 1$. \n",
355
+ "* We will allow the GRU to detect \"activate\" anywhere within a short time-internal **after** this moment, so we actually **set 50 consecutive values** of the label $y^{\\langle t \\rangle}$ to 1. \n",
356
+ " * Specifically, we have $y^{\\langle 688 \\rangle} = y^{\\langle 689 \\rangle} = \\cdots = y^{\\langle 737 \\rangle} = 1$. \n",
357
+ "\n",
358
+ "##### Synthesized data is easier to label\n",
359
+ "* This is another reason for synthesizing the training data: It's relatively straightforward to generate these labels $y^{\\langle t \\rangle}$ as described above. \n",
360
+ "* 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. "
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "metadata": {},
366
+ "source": [
367
+ "#### Visualizing the labels\n",
368
+ "* Here's a figure illustrating the labels $y^{\\langle t \\rangle}$ in a clip.\n",
369
+ " * We have inserted \"activate\", \"innocent\", \"activate\", \"baby.\" \n",
370
+ " * Note that the positive labels \"1\" are associated only with the positive words. \n",
371
+ "\n",
372
+ "<img src=\"images/label_diagram.png\" style=\"width:500px;height:200px;\">\n",
373
+ "<center> **Figure 2** </center>\n",
374
+ "\n"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "markdown",
379
+ "metadata": {},
380
+ "source": [
381
+ "#### Helper functions\n",
382
+ "\n",
383
+ "To implement the training set synthesis process, you will use the following helper functions. \n",
384
+ "* All of these functions will use a 1ms discretization interval\n",
385
+ "* The 10 seconds of audio is always discretized into 10,000 steps. \n",
386
+ "\n",
387
+ "\n",
388
+ "1. `get_random_time_segment(segment_ms)`\n",
389
+ " * Retrieves a random time segment from the background audio.\n",
390
+ "2. `is_overlapping(segment_time, existing_segments)`\n",
391
+ " * Checks if a time segment overlaps with existing segments\n",
392
+ "3. `insert_audio_clip(background, audio_clip, existing_times)`\n",
393
+ " * Inserts an audio segment at a random time in the background audio\n",
394
+ " * Uses the functions `get_random_time_segment` and `is_overlapping`\n",
395
+ "4. `insert_ones(y, segment_end_ms)`\n",
396
+ " * Inserts additional 1's into the label vector y after the word \"activate\""
397
+ ]
398
+ },
399
+ {
400
+ "cell_type": "markdown",
401
+ "metadata": {},
402
+ "source": [
403
+ "#### Get a random time segment\n",
404
+ "\n",
405
+ "* 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`. \n",
406
+ "* Please read through the code to make sure you understand what it is doing. "
407
+ ]
408
+ },
409
+ {
410
+ "cell_type": "code",
411
+ "execution_count": null,
412
+ "metadata": {},
413
+ "outputs": [],
414
+ "source": [
415
+ "def get_random_time_segment(segment_ms):\n",
416
+ " \"\"\"\n",
417
+ " Gets a random time segment of duration segment_ms in a 10,000 ms audio clip.\n",
418
+ " \n",
419
+ " Arguments:\n",
420
+ " segment_ms -- the duration of the audio clip in ms (\"ms\" stands for \"milliseconds\")\n",
421
+ " \n",
422
+ " Returns:\n",
423
+ " segment_time -- a tuple of (segment_start, segment_end) in ms\n",
424
+ " \"\"\"\n",
425
+ " \n",
426
+ " segment_start = np.random.randint(low=0, high=10000-segment_ms) # Make sure segment doesn't run past the 10sec background \n",
427
+ " segment_end = segment_start + segment_ms - 1\n",
428
+ " \n",
429
+ " return (segment_start, segment_end)"
430
+ ]
431
+ },
432
+ {
433
+ "cell_type": "markdown",
434
+ "metadata": {},
435
+ "source": [
436
+ "#### Check if audio clips are overlapping\n",
437
+ "\n",
438
+ "* Suppose you have inserted audio clips at segments (1000,1800) and (3400,4500).\n",
439
+ " * The first segment starts at step 1000 and ends at step 1800. \n",
440
+ " * The second segment starts at 3400 and ends at 4500.\n",
441
+ "* If we are considering whether to insert a new audio clip at (3000,3600) does this overlap with one of the previously inserted segments? \n",
442
+ " * In this case, (3000,3600) and (3400,4500) overlap, so we should decide against inserting a clip here.\n",
443
+ "* For the purpose of this function, define (100,200) and (200,250) to be overlapping, since they overlap at timestep 200. \n",
444
+ "* (100,199) and (200,250) are non-overlapping. \n",
445
+ "\n",
446
+ "<a name='ex-1'></a>\n",
447
+ "### Exercise 1 - is_overlapping\n",
448
+ "\n",
449
+ "* Implement `is_overlapping(segment_time, existing_segments)` to check if a new time segment overlaps with any of the previous segments. \n",
450
+ "* You will need to carry out 2 steps:\n",
451
+ "\n",
452
+ "1. Create a \"False\" flag, that you will later set to \"True\" if you find that there is an overlap.\n",
453
+ "2. 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. \n",
454
+ "\n",
455
+ "You can use:\n",
456
+ "```python\n",
457
+ "for ....:\n",
458
+ " if ... <= ... and ... >= ...:\n",
459
+ " ...\n",
460
+ "```\n",
461
+ "Hint: There is overlap if:\n",
462
+ "* The new segment starts before the previous segment ends **and**\n",
463
+ "* The new segment ends after the previous segment starts."
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "code",
468
+ "execution_count": null,
469
+ "metadata": {},
470
+ "outputs": [],
471
+ "source": [
472
+ "# UNQ_C1\n",
473
+ "# GRADED FUNCTION: is_overlapping\n",
474
+ "\n",
475
+ "def is_overlapping(segment_time, previous_segments):\n",
476
+ " \"\"\"\n",
477
+ " Checks if the time of a segment overlaps with the times of existing segments.\n",
478
+ " \n",
479
+ " Arguments:\n",
480
+ " segment_time -- a tuple of (segment_start, segment_end) for the new segment\n",
481
+ " previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments\n",
482
+ " \n",
483
+ " Returns:\n",
484
+ " True if the time segment overlaps with any of the existing segments, False otherwise\n",
485
+ " \"\"\"\n",
486
+ " \n",
487
+ " segment_start, segment_end = segment_time\n",
488
+ " \n",
489
+ " ### START CODE HERE ### (≈ 4 lines)\n",
490
+ " # Step 1: Initialize overlap as a \"False\" flag. (≈ 1 line)\n",
491
+ " overlap = None\n",
492
+ " \n",
493
+ " # Step 2: loop over the previous_segments start and end times.\n",
494
+ " # Compare start/end times and set the flag to True if there is an overlap (≈ 3 lines)\n",
495
+ " for previous_start, previous_end in previous_segments:\n",
496
+ " if None:\n",
497
+ " overlap = None\n",
498
+ " break\n",
499
+ " ### END CODE HERE ###\n",
500
+ "\n",
501
+ " return overlap"
502
+ ]
503
+ },
504
+ {
505
+ "cell_type": "code",
506
+ "execution_count": null,
507
+ "metadata": {
508
+ "deletable": false,
509
+ "editable": false
510
+ },
511
+ "outputs": [],
512
+ "source": [
513
+ "### THIS CELL IS NOT EDITABLE\n",
514
+ "\n",
515
+ "# UNIT TEST\n",
516
+ "def is_overlapping_test(target):\n",
517
+ " assert target((670, 1430), []) == False, \"Overlap with an empty list must be False\"\n",
518
+ " assert target((500, 1000), [(100, 499), (1001, 1100)]) == False, \"Almost overlap, but still False\"\n",
519
+ " assert target((750, 900), [(100, 750), (1001, 1100)]) == True, \"Must overlap with the end of first segment\"\n",
520
+ " assert target((750, 1250), [(300, 600), (1250, 1500)]) == True, \"Must overlap with the beginning of second segment\"\n",
521
+ " assert target((750, 1250), [(300, 600), (600, 1500), (1600, 1800)]) == True, \"Is contained in second segment\"\n",
522
+ " assert target((800, 1100), [(300, 600), (900, 1000), (1600, 1800)]) == True, \"New segment contains the second segment\"\n",
523
+ "\n",
524
+ " print(\"\\033[92m All tests passed!\")\n",
525
+ " \n",
526
+ "is_overlapping_test(is_overlapping)"
527
+ ]
528
+ },
529
+ {
530
+ "cell_type": "code",
531
+ "execution_count": null,
532
+ "metadata": {
533
+ "scrolled": true
534
+ },
535
+ "outputs": [],
536
+ "source": [
537
+ "overlap1 = is_overlapping((950, 1430), [(2000, 2550), (260, 949)])\n",
538
+ "overlap2 = is_overlapping((2305, 2950), [(824, 1532), (1900, 2305), (3424, 3656)])\n",
539
+ "print(\"Overlap 1 = \", overlap1)\n",
540
+ "print(\"Overlap 2 = \", overlap2)"
541
+ ]
542
+ },
543
+ {
544
+ "cell_type": "markdown",
545
+ "metadata": {},
546
+ "source": [
547
+ "**Expected Output**:\n",
548
+ "\n",
549
+ "<table>\n",
550
+ " <tr>\n",
551
+ " <td>\n",
552
+ " **Overlap 1**\n",
553
+ " </td>\n",
554
+ " <td>\n",
555
+ " False\n",
556
+ " </td>\n",
557
+ " </tr>\n",
558
+ " <tr>\n",
559
+ " <td>\n",
560
+ " **Overlap 2**\n",
561
+ " </td>\n",
562
+ " <td>\n",
563
+ " True\n",
564
+ " </td>\n",
565
+ " </tr>\n",
566
+ "</table>"
567
+ ]
568
+ },
569
+ {
570
+ "cell_type": "markdown",
571
+ "metadata": {},
572
+ "source": [
573
+ "#### Insert audio clip\n",
574
+ "\n",
575
+ "* Let's use the previous helper functions to insert a new audio clip onto the 10 second background at a random time.\n",
576
+ "* We will ensure that any newly inserted segment doesn't overlap with previously inserted segments. \n",
577
+ "\n",
578
+ "<a name='ex-2'></a>\n",
579
+ "### Exercise 2 - insert_audio_clip\n",
580
+ "* Implement `insert_audio_clip()` to overlay an audio clip onto the background 10sec clip. \n",
581
+ "* You implement 4 steps:\n",
582
+ "\n",
583
+ "1. Get the length of the audio clip that is to be inserted.\n",
584
+ " * Get a random time segment whose duration equals the duration of the audio clip that is to be inserted.\n",
585
+ "2. Make sure that the time segment does not overlap with any of the previous time segments. \n",
586
+ " * If it is overlapping, then go back to step 1 and pick a new time segment.\n",
587
+ "3. Append the new time segment to the list of existing time segments\n",
588
+ " * This keeps track of all the segments you've inserted. \n",
589
+ "4. Overlay the audio clip over the background using pydub. We have implemented this for you."
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "code",
594
+ "execution_count": null,
595
+ "metadata": {},
596
+ "outputs": [],
597
+ "source": [
598
+ "# UNQ_C2\n",
599
+ "# GRADED FUNCTION: insert_audio_clip\n",
600
+ "\n",
601
+ "def insert_audio_clip(background, audio_clip, previous_segments):\n",
602
+ " \"\"\"\n",
603
+ " Insert a new audio segment over the background noise at a random time step, ensuring that the \n",
604
+ " audio segment does not overlap with existing segments.\n",
605
+ " \n",
606
+ " Arguments:\n",
607
+ " background -- a 10 second background audio recording. \n",
608
+ " audio_clip -- the audio clip to be inserted/overlaid. \n",
609
+ " previous_segments -- times where audio segments have already been placed\n",
610
+ " \n",
611
+ " Returns:\n",
612
+ " new_background -- the updated background audio\n",
613
+ " \"\"\"\n",
614
+ " \n",
615
+ " # Get the duration of the audio clip in ms\n",
616
+ " segment_ms = len(audio_clip)\n",
617
+ " \n",
618
+ " ### START CODE HERE ### \n",
619
+ " # Step 1: Use one of the helper functions to pick a random time segment onto which to insert \n",
620
+ " # the new audio clip. (≈ 1 line)\n",
621
+ " segment_time = None\n",
622
+ " \n",
623
+ " # Step 2: Check if the new segment_time overlaps with one of the previous_segments. If so, keep \n",
624
+ " # picking new segment_time at random until it doesn't overlap. To avoid an endless loop\n",
625
+ " # we retry 5 times(≈ 2 lines)\n",
626
+ " retry = 5 \n",
627
+ " while None and retry >= 0:\n",
628
+ " segment_time = None\n",
629
+ " retry = retry - 1\n",
630
+ " ### END CODE HERE ###\n",
631
+ " #print(segment_time)\n",
632
+ " # if last try is not overlaping, insert it to the background\n",
633
+ " if not is_overlapping(segment_time, previous_segments):\n",
634
+ " ### START CODE HERE ### \n",
635
+ " # Step 3: Append the new segment_time to the list of previous_segments (≈ 1 line)\n",
636
+ " None\n",
637
+ " ### END CODE HERE ###\n",
638
+ " # Step 4: Superpose audio segment and background\n",
639
+ " new_background = background.overlay(audio_clip, position = segment_time[0])\n",
640
+ " else:\n",
641
+ " #print(\"Timeouted\")\n",
642
+ " new_background = background\n",
643
+ " segment_time = (10000, 10000)\n",
644
+ " \n",
645
+ " return new_background, segment_time"
646
+ ]
647
+ },
648
+ {
649
+ "cell_type": "code",
650
+ "execution_count": null,
651
+ "metadata": {
652
+ "deletable": false,
653
+ "editable": false
654
+ },
655
+ "outputs": [],
656
+ "source": [
657
+ "### THIS CELL IS NOT EDITABLE\n",
658
+ "\n",
659
+ "# UNIT TEST\n",
660
+ "def insert_audio_clip_test(target):\n",
661
+ " np.random.seed(5)\n",
662
+ " audio_clip, segment_time = target(backgrounds[0], activates[0], [(0, 4400)])\n",
663
+ " duration = segment_time[1] - segment_time[0]\n",
664
+ " #print(f\"xx: {segment_time}\")\n",
665
+ " assert segment_time[0] > 4400, \"Error: The audio clip is overlapping with the first segment\"\n",
666
+ " assert duration + 1 == len(activates[0]) , \"The segment length must match the audio clip length\"\n",
667
+ " assert audio_clip != backgrounds[0] , \"The audio clip must be different than the pure background\"\n",
668
+ " assert segment_time == (7286, 8201), f\"Wrong segment. Expected: (7286, 8201) got:{segment_time}\"\n",
669
+ " \n",
670
+ " # Not possible to insert clip into background\n",
671
+ " audio_clip, segment_time = target(backgrounds[0], activates[0], [(0, 9999)])\n",
672
+ " assert segment_time == (10000, 10000), \"Segment must match the out by max-retry mark\"\n",
673
+ " assert audio_clip == backgrounds[0], \"output audio clip must be exactly the same input background\"\n",
674
+ " \n",
675
+ " print(\"\\033[92m All tests passed!\")\n",
676
+ "\n",
677
+ "insert_audio_clip_test(insert_audio_clip)"
678
+ ]
679
+ },
680
+ {
681
+ "cell_type": "code",
682
+ "execution_count": null,
683
+ "metadata": {},
684
+ "outputs": [],
685
+ "source": [
686
+ "np.random.seed(5)\n",
687
+ "audio_clip, segment_time = insert_audio_clip(backgrounds[0], activates[0], [(3790, 4400)])\n",
688
+ "audio_clip.export(\"insert_test.wav\", format=\"wav\")\n",
689
+ "print(\"Segment Time: \", segment_time)\n",
690
+ "IPython.display.Audio(\"insert_test.wav\")"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "markdown",
695
+ "metadata": {},
696
+ "source": [
697
+ "**Expected Output**\n",
698
+ "\n",
699
+ "<table>\n",
700
+ " <tr>\n",
701
+ " <td>\n",
702
+ " **Segment Time**\n",
703
+ " </td>\n",
704
+ " <td>\n",
705
+ " (2254, 3169)\n",
706
+ " </td>\n",
707
+ " </tr>\n",
708
+ "</table>"
709
+ ]
710
+ },
711
+ {
712
+ "cell_type": "code",
713
+ "execution_count": null,
714
+ "metadata": {},
715
+ "outputs": [],
716
+ "source": [
717
+ "# Expected audio\n",
718
+ "IPython.display.Audio(\"audio_examples/insert_reference.wav\")"
719
+ ]
720
+ },
721
+ {
722
+ "cell_type": "markdown",
723
+ "metadata": {},
724
+ "source": [
725
+ "#### Insert ones for the labels of the positive target\n",
726
+ "\n",
727
+ "* Implement code to update the labels $y^{\\langle t \\rangle}$, assuming you just inserted an \"activate\" audio clip.\n",
728
+ "* In the code below, `y` is a `(1,1375)` dimensional vector, since $T_y = 1375$. \n",
729
+ "* If the \"activate\" audio clip ends at time step $t$, then set $y^{\\langle t+1 \\rangle} = 1$ and also set the next 49 additional consecutive values to 1.\n",
730
+ " * Notice that if the target word appears near the end of the entire audio clip, there may not be 50 additional time steps to set to 1.\n",
731
+ " * 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 $T_y = 1375$. \n",
732
+ " * So if \"activate\" ends at step 1370, you would get only set `y[0][1371] = y[0][1372] = y[0][1373] = y[0][1374] = 1`\n",
733
+ "\n",
734
+ "<a name='ex-3'></a>\n",
735
+ "### Exercise 3 - insert_ones \n",
736
+ "Implement `insert_ones()`. \n",
737
+ "* You can use a for loop. \n",
738
+ "* If you want to use Python's array slicing operations, you can do so as well.\n",
739
+ "* If a segment ends at `segment_end_ms` (using a 10000 step discretization),\n",
740
+ " * To convert it to the indexing for the outputs $y$ (using a $1375$ step discretization), we will use this formula: \n",
741
+ "```\n",
742
+ " segment_end_y = int(segment_end_ms * Ty / 10000.0)\n",
743
+ "```"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": null,
749
+ "metadata": {},
750
+ "outputs": [],
751
+ "source": [
752
+ "# UNQ_C3\n",
753
+ "# GRADED FUNCTION: insert_ones\n",
754
+ "\n",
755
+ "def insert_ones(y, segment_end_ms):\n",
756
+ " \"\"\"\n",
757
+ " Update the label vector y. The labels of the 50 output steps strictly after the end of the segment \n",
758
+ " should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the\n",
759
+ " 50 following labels should be ones.\n",
760
+ " \n",
761
+ " \n",
762
+ " Arguments:\n",
763
+ " y -- numpy array of shape (1, Ty), the labels of the training example\n",
764
+ " segment_end_ms -- the end time of the segment in ms\n",
765
+ " \n",
766
+ " Returns:\n",
767
+ " y -- updated labels\n",
768
+ " \"\"\"\n",
769
+ " _, Ty = y.shape\n",
770
+ " \n",
771
+ " # duration of the background (in terms of spectrogram time-steps)\n",
772
+ " segment_end_y = int(segment_end_ms * Ty / 10000.0)\n",
773
+ " \n",
774
+ " if segment_end_y < Ty:\n",
775
+ " # Add 1 to the correct index in the background label (y)\n",
776
+ " ### START CODE HERE ### (≈ 3 lines)\n",
777
+ " for i in range(None, None):\n",
778
+ " if None < None:\n",
779
+ " y[0, i] = None\n",
780
+ " ### END CODE HERE ###\n",
781
+ " \n",
782
+ " return y"
783
+ ]
784
+ },
785
+ {
786
+ "cell_type": "code",
787
+ "execution_count": null,
788
+ "metadata": {
789
+ "deletable": false,
790
+ "editable": false
791
+ },
792
+ "outputs": [],
793
+ "source": [
794
+ "### THIS CELL IS NOT EDITABLE\n",
795
+ "\n",
796
+ "# UNIT TEST\n",
797
+ "import random\n",
798
+ "def insert_ones_test(target):\n",
799
+ " segment_end_y = random.randrange(0, Ty - 50) \n",
800
+ " segment_end_ms = int(segment_end_y * 10000.4) / Ty; \n",
801
+ " arr1 = target(np.zeros((1, Ty)), segment_end_ms)\n",
802
+ "\n",
803
+ " assert type(arr1) == np.ndarray, \"Wrong type. Output must be a numpy array\"\n",
804
+ " assert arr1.shape == (1, Ty), \"Wrong shape. It must match the input shape\"\n",
805
+ " assert np.sum(arr1) == 50, \"It must insert exactly 50 ones\"\n",
806
+ " assert arr1[0][segment_end_y - 1] == 0, f\"Array at {segment_end_y - 1} must be 0\"\n",
807
+ " assert arr1[0][segment_end_y] == 0, f\"Array at {segment_end_y} must be 0\"\n",
808
+ " assert arr1[0][segment_end_y + 1] == 1, f\"Array at {segment_end_y + 1} must be 1\"\n",
809
+ " assert arr1[0][segment_end_y + 50] == 1, f\"Array at {segment_end_y + 50} must be 1\"\n",
810
+ " assert arr1[0][segment_end_y + 51] == 0, f\"Array at {segment_end_y + 51} must be 0\"\n",
811
+ " \n",
812
+ " arr1 = target(np.zeros((1, Ty)), 9632)\n",
813
+ " assert np.sum(arr1) == 50, f\"Expected sum of 50, but got {np.sum(arr1)}\"\n",
814
+ " arr1 = target(np.zeros((1, Ty)), 9637)\n",
815
+ " assert np.sum(arr1) == 49, f\"Expected sum of 49, but got {np.sum(arr1)}\"\n",
816
+ " arr1 = target(np.zeros((1, Ty)), 10008)\n",
817
+ " assert np.sum(arr1) == 0, f\"Expected sum of 0, but got {np.sum(arr1)}\"\n",
818
+ " arr1 = target(np.zeros((1, Ty)), 10000)\n",
819
+ " assert np.sum(arr1) == 0, f\"Expected sum of 0, but got {np.sum(arr1)}\"\n",
820
+ " arr1 = target(np.zeros((1, Ty)), 9996)\n",
821
+ " assert np.sum(arr1) == 0, f\"Expected sum of 0, but got {np.sum(arr1)}\"\n",
822
+ " arr1 = target(np.zeros((1, Ty)), 9990)\n",
823
+ " assert np.sum(arr1) == 1, f\"Expected sum of 1, but got {np.sum(arr1)}\"\n",
824
+ " arr1 = target(np.zeros((1, Ty)), 9980)\n",
825
+ " assert np.sum(arr1) == 2, f\"Expected sum of 2, but got {np.sum(arr1)}\"\n",
826
+ "\n",
827
+ " print(\"\\033[92m All tests passed!\")\n",
828
+ " \n",
829
+ "insert_ones_test(insert_ones)"
830
+ ]
831
+ },
832
+ {
833
+ "cell_type": "code",
834
+ "execution_count": null,
835
+ "metadata": {},
836
+ "outputs": [],
837
+ "source": [
838
+ "arr1 = insert_ones(np.zeros((1, Ty)), 9700)\n",
839
+ "plt.plot(insert_ones(arr1, 4251)[0,:])\n",
840
+ "print(\"sanity checks:\", arr1[0][1333], arr1[0][634], arr1[0][635])"
841
+ ]
842
+ },
843
+ {
844
+ "cell_type": "markdown",
845
+ "metadata": {},
846
+ "source": [
847
+ "**Expected Output**\n",
848
+ "<table>\n",
849
+ " <tr>\n",
850
+ " <td>\n",
851
+ " **sanity checks**:\n",
852
+ " </td>\n",
853
+ " <td>\n",
854
+ " 0.0 1.0 0.0\n",
855
+ " </td>\n",
856
+ " </tr>\n",
857
+ "</table>\n",
858
+ "<img src=\"images/ones_reference.png\" style=\"width:320;height:240px;\">"
859
+ ]
860
+ },
861
+ {
862
+ "cell_type": "markdown",
863
+ "metadata": {},
864
+ "source": [
865
+ "#### Creating a training example\n",
866
+ "Finally, you can use `insert_audio_clip` and `insert_ones` to create a new training example.\n",
867
+ "\n",
868
+ "<a name='ex-4'></a>\n",
869
+ "### Exercise 4 - create_training_example\n",
870
+ "\n",
871
+ "Implement `create_training_example()`. You will need to carry out the following steps:\n",
872
+ "\n",
873
+ "1. Initialize the label vector $y$ as a numpy array of zeros and shape $(1, T_y)$.\n",
874
+ "2. Initialize the set of existing segments to an empty list.\n",
875
+ "3. Randomly select 0 to 4 \"activate\" audio clips, and insert them onto the 10 second clip. Also insert labels at the correct position in the label vector $y$.\n",
876
+ "4. Randomly select 0 to 2 negative audio clips, and insert them into the 10 second clip. \n"
877
+ ]
878
+ },
879
+ {
880
+ "cell_type": "code",
881
+ "execution_count": null,
882
+ "metadata": {},
883
+ "outputs": [],
884
+ "source": [
885
+ "# UNQ_C4\n",
886
+ "# GRADED FUNCTION: create_training_example\n",
887
+ "\n",
888
+ "def create_training_example(background, activates, negatives, Ty):\n",
889
+ " \"\"\"\n",
890
+ " Creates a training example with a given background, activates, and negatives.\n",
891
+ " \n",
892
+ " Arguments:\n",
893
+ " background -- a 10 second background audio recording\n",
894
+ " activates -- a list of audio segments of the word \"activate\"\n",
895
+ " negatives -- a list of audio segments of random words that are not \"activate\"\n",
896
+ " Ty -- The number of time steps in the output\n",
897
+ "\n",
898
+ " Returns:\n",
899
+ " x -- the spectrogram of the training example\n",
900
+ " y -- the label at each time step of the spectrogram\n",
901
+ " \"\"\"\n",
902
+ " \n",
903
+ " # Make background quieter\n",
904
+ " background = background - 20\n",
905
+ "\n",
906
+ " ### START CODE HERE ###\n",
907
+ " # Step 1: Initialize y (label vector) of zeros (≈ 1 line)\n",
908
+ " y = None\n",
909
+ "\n",
910
+ " # Step 2: Initialize segment times as empty list (≈ 1 line)\n",
911
+ " previous_segments = None\n",
912
+ " ### END CODE HERE ###\n",
913
+ " \n",
914
+ " # Select 0-4 random \"activate\" audio clips from the entire list of \"activates\" recordings\n",
915
+ " number_of_activates = np.random.randint(0, 5)\n",
916
+ " random_indices = np.random.randint(len(activates), size=number_of_activates)\n",
917
+ " random_activates = [activates[i] for i in random_indices]\n",
918
+ " \n",
919
+ " ### START CODE HERE ### (≈ 3 lines)\n",
920
+ " # Step 3: Loop over randomly selected \"activate\" clips and insert in background\n",
921
+ " for one_random_activate in random_activates:\n",
922
+ " # Insert the audio clip on the background\n",
923
+ " background, segment_time = None\n",
924
+ " # Retrieve segment_start and segment_end from segment_time\n",
925
+ " segment_start, segment_end = None\n",
926
+ " # Insert labels in \"y\" at segment_end\n",
927
+ " y = None\n",
928
+ " ### END CODE HERE ###\n",
929
+ "\n",
930
+ " # Select 0-2 random negatives audio recordings from the entire list of \"negatives\" recordings\n",
931
+ " number_of_negatives = np.random.randint(0, 3)\n",
932
+ " random_indices = np.random.randint(len(negatives), size=number_of_negatives)\n",
933
+ " random_negatives = [negatives[i] for i in random_indices]\n",
934
+ "\n",
935
+ " ### START CODE HERE ### (≈ 2 lines)\n",
936
+ " # Step 4: Loop over randomly selected negative clips and insert in background\n",
937
+ " for random_negative in random_negatives:\n",
938
+ " # Insert the audio clip on the background \n",
939
+ " background, _ = None\n",
940
+ " ### END CODE HERE ###\n",
941
+ " \n",
942
+ " # Standardize the volume of the audio clip \n",
943
+ " background = match_target_amplitude(background, -20.0)\n",
944
+ "\n",
945
+ " # Export new training example \n",
946
+ " file_handle = background.export(\"train\" + \".wav\", format=\"wav\")\n",
947
+ " \n",
948
+ " # Get and plot spectrogram of the new recording (background with superposition of positive and negatives)\n",
949
+ " x = graph_spectrogram(\"train.wav\")\n",
950
+ " \n",
951
+ " return x, y"
952
+ ]
953
+ },
954
+ {
955
+ "cell_type": "code",
956
+ "execution_count": null,
957
+ "metadata": {
958
+ "deletable": false,
959
+ "editable": false
960
+ },
961
+ "outputs": [],
962
+ "source": [
963
+ "### THIS CELL IS NOT EDITABLE\n",
964
+ "\n",
965
+ "# UNIT TEST\n",
966
+ "def create_training_example_test(target):\n",
967
+ " np.random.seed(18)\n",
968
+ " x, y = target(backgrounds[0], activates, negatives, 1375)\n",
969
+ " \n",
970
+ " assert type(x) == np.ndarray, \"Wrong type for x\"\n",
971
+ " assert type(y) == np.ndarray, \"Wrong type for y\"\n",
972
+ " assert tuple(x.shape) == (101, 5511), \"Wrong shape for x\"\n",
973
+ " assert tuple(y.shape) == (1, 1375), \"Wrong shape for y\"\n",
974
+ " assert np.all(x > 0), \"All x values must be higher than 0\"\n",
975
+ " assert np.all(y >= 0), \"All y values must be higher or equal than 0\"\n",
976
+ " assert np.all(y <= 1), \"All y values must be smaller or equal than 1\"\n",
977
+ " assert np.sum(y) >= 50, \"It must contain at least one activate\"\n",
978
+ " assert np.sum(y) % 50 == 0, \"Sum of activate marks must be a multiple of 50\"\n",
979
+ " assert np.isclose(np.linalg.norm(x), 39745552.52075), \"Spectrogram is wrong. Check the parameters passed to the insert_audio_clip function\"\n",
980
+ "\n",
981
+ " print(\"\\033[92m All tests passed!\")\n",
982
+ "\n",
983
+ "create_training_example_test(create_training_example)"
984
+ ]
985
+ },
986
+ {
987
+ "cell_type": "code",
988
+ "execution_count": null,
989
+ "metadata": {},
990
+ "outputs": [],
991
+ "source": [
992
+ "# Set the random seed\n",
993
+ "np.random.seed(18)\n",
994
+ "x, y = create_training_example(backgrounds[0], activates, negatives, Ty)"
995
+ ]
996
+ },
997
+ {
998
+ "cell_type": "markdown",
999
+ "metadata": {},
1000
+ "source": [
1001
+ "**Expected Output**\n",
1002
+ "<img src=\"images/train_reference.png\" style=\"width:320;height:240px;\">"
1003
+ ]
1004
+ },
1005
+ {
1006
+ "cell_type": "markdown",
1007
+ "metadata": {},
1008
+ "source": [
1009
+ "Now you can listen to the training example you created and compare it to the spectrogram generated above."
1010
+ ]
1011
+ },
1012
+ {
1013
+ "cell_type": "code",
1014
+ "execution_count": null,
1015
+ "metadata": {},
1016
+ "outputs": [],
1017
+ "source": [
1018
+ "IPython.display.Audio(\"train.wav\")"
1019
+ ]
1020
+ },
1021
+ {
1022
+ "cell_type": "markdown",
1023
+ "metadata": {},
1024
+ "source": [
1025
+ "**Expected Output**"
1026
+ ]
1027
+ },
1028
+ {
1029
+ "cell_type": "code",
1030
+ "execution_count": null,
1031
+ "metadata": {},
1032
+ "outputs": [],
1033
+ "source": [
1034
+ "IPython.display.Audio(\"audio_examples/train_reference.wav\")"
1035
+ ]
1036
+ },
1037
+ {
1038
+ "cell_type": "markdown",
1039
+ "metadata": {},
1040
+ "source": [
1041
+ "Finally, you can plot the associated labels for the generated training example."
1042
+ ]
1043
+ },
1044
+ {
1045
+ "cell_type": "code",
1046
+ "execution_count": null,
1047
+ "metadata": {
1048
+ "scrolled": true
1049
+ },
1050
+ "outputs": [],
1051
+ "source": [
1052
+ "plt.plot(y[0])"
1053
+ ]
1054
+ },
1055
+ {
1056
+ "cell_type": "markdown",
1057
+ "metadata": {},
1058
+ "source": [
1059
+ "**Expected Output**\n",
1060
+ "<img src=\"images/train_label.png\" style=\"width:320;height:240px;\">"
1061
+ ]
1062
+ },
1063
+ {
1064
+ "cell_type": "markdown",
1065
+ "metadata": {},
1066
+ "source": [
1067
+ "<a name='1-4'></a>\n",
1068
+ "### 1.4 - Full Training Set\n",
1069
+ "\n",
1070
+ "* You've now implemented the code needed to generate a single training example. \n",
1071
+ "* We used this process to generate a large training set. \n",
1072
+ "* To save time, we generate a smaller training set of 32 examples. "
1073
+ ]
1074
+ },
1075
+ {
1076
+ "cell_type": "code",
1077
+ "execution_count": null,
1078
+ "metadata": {},
1079
+ "outputs": [],
1080
+ "source": [
1081
+ "# START SKIP FOR GRADING\n",
1082
+ "np.random.seed(4543)\n",
1083
+ "nsamples = 32\n",
1084
+ "X = []\n",
1085
+ "Y = []\n",
1086
+ "for i in range(0, nsamples):\n",
1087
+ " if i%10 == 0:\n",
1088
+ " print(i)\n",
1089
+ " x, y = create_training_example(backgrounds[i % 2], activates, negatives, Ty)\n",
1090
+ " X.append(x.swapaxes(0,1))\n",
1091
+ " Y.append(y.swapaxes(0,1))\n",
1092
+ "X = np.array(X)\n",
1093
+ "Y = np.array(Y)\n",
1094
+ "# END SKIP FOR GRADING"
1095
+ ]
1096
+ },
1097
+ {
1098
+ "cell_type": "markdown",
1099
+ "metadata": {},
1100
+ "source": [
1101
+ "You would like to save your dataset into a file that you can load later if you work in a more realistic environment. We let you the following code for reference. Don't try to run it into Coursera since the file system is read-only, and you cannot save files."
1102
+ ]
1103
+ },
1104
+ {
1105
+ "cell_type": "code",
1106
+ "execution_count": null,
1107
+ "metadata": {},
1108
+ "outputs": [],
1109
+ "source": [
1110
+ "# Save the data for further uses\n",
1111
+ "# np.save(f'./XY_train/X.npy', X)\n",
1112
+ "# np.save(f'./XY_train/Y.npy', Y)\n",
1113
+ "# Load the preprocessed training examples\n",
1114
+ "# X = np.load(\"./XY_train/X.npy\")\n",
1115
+ "# Y = np.load(\"./XY_train/Y.npy\")"
1116
+ ]
1117
+ },
1118
+ {
1119
+ "cell_type": "markdown",
1120
+ "metadata": {},
1121
+ "source": [
1122
+ "<a name='1-5'></a>\n",
1123
+ "### 1.5 - Development Set\n",
1124
+ "\n",
1125
+ "* To test our model, we recorded a development set of 25 examples. \n",
1126
+ "* While our training data is synthesized, we want to create a development set using the same distribution as the real inputs. \n",
1127
+ "* Thus, we recorded 25 10-second audio clips of people saying \"activate\" and other random words, and labeled them by hand. \n",
1128
+ "* This follows the principle described in Course 3 \"Structuring Machine Learning Projects\" that we should create the dev set to be as similar as possible to the test set distribution\n",
1129
+ " * This is why our **dev set uses real audio** rather than synthesized audio. \n"
1130
+ ]
1131
+ },
1132
+ {
1133
+ "cell_type": "code",
1134
+ "execution_count": null,
1135
+ "metadata": {},
1136
+ "outputs": [],
1137
+ "source": [
1138
+ "# Load preprocessed dev set examples\n",
1139
+ "X_dev = np.load(\"./XY_dev/X_dev.npy\")\n",
1140
+ "Y_dev = np.load(\"./XY_dev/Y_dev.npy\")"
1141
+ ]
1142
+ },
1143
+ {
1144
+ "cell_type": "markdown",
1145
+ "metadata": {},
1146
+ "source": [
1147
+ "<a name='2'></a>\n",
1148
+ "## 2 - The Model\n",
1149
+ "\n",
1150
+ "* Now that you've built a dataset, let's write and train a trigger word detection model! \n",
1151
+ "* The model will use 1-D convolutional layers, GRU layers, and dense layers. \n",
1152
+ "* Let's load the packages that will allow you to use these layers in Keras. This might take a minute to load. "
1153
+ ]
1154
+ },
1155
+ {
1156
+ "cell_type": "code",
1157
+ "execution_count": null,
1158
+ "metadata": {},
1159
+ "outputs": [],
1160
+ "source": [
1161
+ "from tensorflow.keras.callbacks import ModelCheckpoint\n",
1162
+ "from tensorflow.keras.models import Model, load_model, Sequential\n",
1163
+ "from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D\n",
1164
+ "from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape\n",
1165
+ "from tensorflow.keras.optimizers import Adam"
1166
+ ]
1167
+ },
1168
+ {
1169
+ "cell_type": "markdown",
1170
+ "metadata": {},
1171
+ "source": [
1172
+ "<a name='2-1'></a>\n",
1173
+ "### 2.1 - Build the Model\n",
1174
+ "\n",
1175
+ "Our goal is to build a network that will ingest a spectrogram and output a signal when it detects the trigger word. This network will use 4 layers:\n",
1176
+ " * A convolutional layer\n",
1177
+ " * Two GRU layers\n",
1178
+ " * A dense layer. \n",
1179
+ "\n",
1180
+ "Here is the architecture we will use.\n",
1181
+ "\n",
1182
+ "<img src=\"images/model.png\" style=\"width:600px;height:600px;\">\n",
1183
+ "<center> **Figure 3** </center>\n",
1184
+ "\n",
1185
+ "##### 1D convolutional layer\n",
1186
+ "One key layer of this model is the 1D convolutional step (near the bottom of Figure 3). \n",
1187
+ "* It inputs the 5511 step spectrogram. Each step is a vector of 101 units.\n",
1188
+ "* It outputs a 1375 step output\n",
1189
+ "* This output is further processed by multiple layers to get the final $T_y = 1375$ step output. \n",
1190
+ "* This 1D convolutional 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. \n",
1191
+ "* Computationally, the 1-D conv layer also helps speed up the model because now the GRU can process only 1375 timesteps rather than 5511 timesteps. \n",
1192
+ "\n",
1193
+ "##### GRU, dense and sigmoid\n",
1194
+ "* The two GRU layers read the sequence of inputs from left to right.\n",
1195
+ "* A dense plus sigmoid layer makes a prediction for $y^{\\langle t \\rangle}$. \n",
1196
+ "* Because $y$ is a binary value (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\".\n",
1197
+ "\n",
1198
+ "#### Unidirectional RNN\n",
1199
+ "* Note that we use a **unidirectional RNN** rather than a bidirectional RNN. \n",
1200
+ "* This is because we consider that focusing on past context is more critical than future context for detecting the activation word. This simplification reduces computational overhead, as the model does not process information in both directions. \n",
1201
+ "* In a real application, trigger word detection could be performed every second using a sliding 10-second window. Therefore, even if the activation word could appear at any point within these 10 seconds, it can be detected immediately upon being spoken. If the algorithm initially fails to detect it, further detections with each subsequent second provide additional opportunities for recognition. This approach efficiently balances performance with timely detection attempts."
1202
+ ]
1203
+ },
1204
+ {
1205
+ "cell_type": "markdown",
1206
+ "metadata": {},
1207
+ "source": [
1208
+ "#### Implement the model\n",
1209
+ "\n",
1210
+ "In the following model, the input of each layer is the output of the previous one. Implementing the model can be done in four steps. \n",
1211
+ "\n",
1212
+ "**Step 1**: CONV layer. Use `Conv1D()` to implement this, with 196 filters, \n",
1213
+ "a filter size of 15 (`kernel_size=15`), and stride of 4. [conv1d](https://keras.io/layers/convolutional/#conv1d)\n",
1214
+ "\n",
1215
+ "```Python\n",
1216
+ "output_x = Conv1D(filters=...,kernel_size=...,strides=...)(input_x)\n",
1217
+ "```\n",
1218
+ "* Follow this with batch normalization. No parameters need to be set.\n",
1219
+ "\n",
1220
+ "```Python\n",
1221
+ "output_x = BatchNormalization()(input_x)\n",
1222
+ "```\n",
1223
+ "* Follow this with a ReLu activation. Note that we can pass in the name of the desired activation as a string, all in lowercase letters.\n",
1224
+ "\n",
1225
+ "```Python\n",
1226
+ "output_x = Activation(\"...\")(input_x)\n",
1227
+ "```\n",
1228
+ "\n",
1229
+ "* Follow this with dropout, using a rate of 0.8 \n",
1230
+ "\n",
1231
+ "```Python\n",
1232
+ "output_x = Dropout(rate=...)(input_x)\n",
1233
+ "```\n",
1234
+ "\n",
1235
+ "\n",
1236
+ "**Step 2**: First GRU layer. To generate the GRU layer, use 128 units.\n",
1237
+ "```Python\n",
1238
+ "output_x = GRU(units=..., return_sequences = ...)(input_x)\n",
1239
+ "```\n",
1240
+ "* Return sequences instead of just the last time step's prediction to ensure that all the GRU's hidden states are fed to the next layer. \n",
1241
+ "* Follow this with dropout, using a rate of 0.8.\n",
1242
+ "* Follow this with batch normalization. No parameters need to be set.\n",
1243
+ "```Python\n",
1244
+ "output_x = BatchNormalization()(input_x)\n",
1245
+ "```\n",
1246
+ "\n",
1247
+ "**Step 3**: Second GRU layer. This has the same specifications as the first GRU layer.\n",
1248
+ "* Follow this with a dropout, batch normalization, and then another dropout.\n",
1249
+ "\n",
1250
+ "**Step 4**: Create a time-distributed dense layer as follows: \n",
1251
+ "```Python\n",
1252
+ "output_x = TimeDistributed(Dense(1, activation = \"sigmoid\"))(input_x)\n",
1253
+ "```\n",
1254
+ "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. \n",
1255
+ "Documentation:\n",
1256
+ "* [Keras documentation on wrappers](https://keras.io/layers/wrappers/). \n",
1257
+ "* To learn more, you can read this blog post [How to Use the TimeDistributed Layer in Keras](https://machinelearningmastery.com/timedistributed-layer-for-long-short-term-memory-networks-in-python/).\n",
1258
+ "\n",
1259
+ "<a name='ex-5'></a>\n",
1260
+ "### Exercise 5 - modelf\n",
1261
+ "\n",
1262
+ "Implement `modelf()`, the architecture is presented in Figure 3."
1263
+ ]
1264
+ },
1265
+ {
1266
+ "cell_type": "code",
1267
+ "execution_count": null,
1268
+ "metadata": {},
1269
+ "outputs": [],
1270
+ "source": [
1271
+ "# UNQ_C5\n",
1272
+ "# GRADED FUNCTION: modelf\n",
1273
+ "\n",
1274
+ "def modelf(input_shape):\n",
1275
+ " \"\"\"\n",
1276
+ " Function creating the model's graph in Keras.\n",
1277
+ " \n",
1278
+ " Argument:\n",
1279
+ " input_shape -- shape of the model's input data (using Keras conventions)\n",
1280
+ "\n",
1281
+ " Returns:\n",
1282
+ " model -- Keras model instance\n",
1283
+ " \"\"\"\n",
1284
+ " \n",
1285
+ " X_input = Input(shape = input_shape)\n",
1286
+ " \n",
1287
+ " ### START CODE HERE ###\n",
1288
+ " \n",
1289
+ " # Step 1: CONV layer (≈4 lines)\n",
1290
+ " # Add a Conv1D with 196 units, kernel size of 15 and stride of 4\n",
1291
+ " X = None\n",
1292
+ " # Batch normalization\n",
1293
+ " X = None\n",
1294
+ " # ReLu activation\n",
1295
+ " X = None\n",
1296
+ " # dropout (use 0.8)\n",
1297
+ " X = None \n",
1298
+ "\n",
1299
+ " # Step 2: First GRU Layer (≈4 lines)\n",
1300
+ " # GRU (use 128 units and return the sequences)\n",
1301
+ " X = None\n",
1302
+ " # dropout (use 0.8)\n",
1303
+ " X = None\n",
1304
+ " # Batch normalization.\n",
1305
+ " X = None \n",
1306
+ " \n",
1307
+ " # Step 3: Second GRU Layer (≈4 lines)\n",
1308
+ " # GRU (use 128 units and return the sequences)\n",
1309
+ " X = None\n",
1310
+ " # dropout (use 0.8)\n",
1311
+ " X = None \n",
1312
+ " # Batch normalization\n",
1313
+ " X = None\n",
1314
+ " # dropout (use 0.8)\n",
1315
+ " X = None \n",
1316
+ " \n",
1317
+ " # Step 4: Time-distributed dense layer (≈1 line)\n",
1318
+ " # TimeDistributed with sigmoid activation \n",
1319
+ " X = None \n",
1320
+ "\n",
1321
+ " ### END CODE HERE ###\n",
1322
+ "\n",
1323
+ " model = Model(inputs = X_input, outputs = X)\n",
1324
+ " \n",
1325
+ " return model "
1326
+ ]
1327
+ },
1328
+ {
1329
+ "cell_type": "code",
1330
+ "execution_count": null,
1331
+ "metadata": {
1332
+ "deletable": false,
1333
+ "editable": false
1334
+ },
1335
+ "outputs": [],
1336
+ "source": [
1337
+ "### THIS CELL IS NOT EDITABLE\n",
1338
+ "\n",
1339
+ "# UNIT TEST\n",
1340
+ "from test_utils import *\n",
1341
+ "\n",
1342
+ "def modelf_test(target):\n",
1343
+ " Tx = 5511\n",
1344
+ " n_freq = 101\n",
1345
+ " model = target(input_shape = (Tx, n_freq))\n",
1346
+ " expected_model = [['InputLayer', [(None, 5511, 101)], 0],\n",
1347
+ " ['Conv1D', (None, 1375, 196), 297136, 'valid', 'linear', (4,), (15,), 'GlorotUniform'],\n",
1348
+ " ['BatchNormalization', (None, 1375, 196), 784],\n",
1349
+ " ['Activation', (None, 1375, 196), 0],\n",
1350
+ " ['Dropout', (None, 1375, 196), 0, 0.8],\n",
1351
+ " ['GRU', (None, 1375, 128), 125184, True],\n",
1352
+ " ['Dropout', (None, 1375, 128), 0, 0.8],\n",
1353
+ " ['BatchNormalization', (None, 1375, 128), 512],\n",
1354
+ " ['GRU', (None, 1375, 128), 99072, True],\n",
1355
+ " ['Dropout', (None, 1375, 128), 0, 0.8],\n",
1356
+ " ['BatchNormalization', (None, 1375, 128), 512],\n",
1357
+ " ['Dropout', (None, 1375, 128), 0, 0.8],\n",
1358
+ " ['TimeDistributed', (None, 1375, 1), 129, 'sigmoid']]\n",
1359
+ " comparator(summary(model), expected_model)\n",
1360
+ " \n",
1361
+ " \n",
1362
+ "modelf_test(modelf)"
1363
+ ]
1364
+ },
1365
+ {
1366
+ "cell_type": "code",
1367
+ "execution_count": null,
1368
+ "metadata": {},
1369
+ "outputs": [],
1370
+ "source": [
1371
+ "model = modelf(input_shape = (Tx, n_freq))"
1372
+ ]
1373
+ },
1374
+ {
1375
+ "cell_type": "markdown",
1376
+ "metadata": {},
1377
+ "source": [
1378
+ "Let's print the model summary to keep track of the shapes."
1379
+ ]
1380
+ },
1381
+ {
1382
+ "cell_type": "code",
1383
+ "execution_count": null,
1384
+ "metadata": {},
1385
+ "outputs": [],
1386
+ "source": [
1387
+ "model.summary()"
1388
+ ]
1389
+ },
1390
+ {
1391
+ "cell_type": "markdown",
1392
+ "metadata": {},
1393
+ "source": [
1394
+ "**Expected Output**:\n",
1395
+ "\n",
1396
+ "<table>\n",
1397
+ " <tr>\n",
1398
+ " <td>\n",
1399
+ " **Total params**\n",
1400
+ " </td>\n",
1401
+ " <td>\n",
1402
+ " 523,329\n",
1403
+ " </td>\n",
1404
+ " </tr>\n",
1405
+ " <tr>\n",
1406
+ " <td>\n",
1407
+ " **Trainable params**\n",
1408
+ " </td>\n",
1409
+ " <td>\n",
1410
+ " 522,425\n",
1411
+ " </td>\n",
1412
+ " </tr>\n",
1413
+ " <tr>\n",
1414
+ " <td>\n",
1415
+ " **Non-trainable params**\n",
1416
+ " </td>\n",
1417
+ " <td>\n",
1418
+ " 904\n",
1419
+ " </td>\n",
1420
+ " </tr>\n",
1421
+ "</table>"
1422
+ ]
1423
+ },
1424
+ {
1425
+ "cell_type": "markdown",
1426
+ "metadata": {},
1427
+ "source": [
1428
+ "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 to 1375. "
1429
+ ]
1430
+ },
1431
+ {
1432
+ "cell_type": "markdown",
1433
+ "metadata": {},
1434
+ "source": [
1435
+ "<a name='2-2'></a>\n",
1436
+ "### 2.2 - Fit the Model"
1437
+ ]
1438
+ },
1439
+ {
1440
+ "cell_type": "markdown",
1441
+ "metadata": {},
1442
+ "source": [
1443
+ "* Trigger word detection takes a long time to train. \n",
1444
+ "* 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. \n",
1445
+ "* Let's load the model. "
1446
+ ]
1447
+ },
1448
+ {
1449
+ "cell_type": "code",
1450
+ "execution_count": null,
1451
+ "metadata": {},
1452
+ "outputs": [],
1453
+ "source": [
1454
+ "from tensorflow.keras.models import model_from_json\n",
1455
+ "\n",
1456
+ "json_file = open('./models/model.json', 'r')\n",
1457
+ "loaded_model_json = json_file.read()\n",
1458
+ "json_file.close()\n",
1459
+ "model = model_from_json(loaded_model_json)\n",
1460
+ "model.load_weights('./models/model.h5')"
1461
+ ]
1462
+ },
1463
+ {
1464
+ "cell_type": "markdown",
1465
+ "metadata": {},
1466
+ "source": [
1467
+ "<a name='2-2-1'></a>\n",
1468
+ "#### 2.2.1 Block Training for BatchNormalization Layers\n",
1469
+ "\n",
1470
+ "If you are going to fine-tune a pretrained model, it is important that you block the weights of all your batchnormalization layers. If you are going to train a new model from scratch, skip the next cell. "
1471
+ ]
1472
+ },
1473
+ {
1474
+ "cell_type": "code",
1475
+ "execution_count": null,
1476
+ "metadata": {},
1477
+ "outputs": [],
1478
+ "source": [
1479
+ "model.layers[2].trainable = False\n",
1480
+ "model.layers[7].trainable = False\n",
1481
+ "model.layers[10].trainable = False"
1482
+ ]
1483
+ },
1484
+ {
1485
+ "cell_type": "markdown",
1486
+ "metadata": {},
1487
+ "source": [
1488
+ "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 two epochs and with a small training set of 32 examples. "
1489
+ ]
1490
+ },
1491
+ {
1492
+ "cell_type": "code",
1493
+ "execution_count": null,
1494
+ "metadata": {},
1495
+ "outputs": [],
1496
+ "source": [
1497
+ "opt = Adam(lr=1e-6, beta_1=0.9, beta_2=0.999)\n",
1498
+ "model.compile(loss='binary_crossentropy', optimizer=opt, metrics=[\"accuracy\"])"
1499
+ ]
1500
+ },
1501
+ {
1502
+ "cell_type": "code",
1503
+ "execution_count": null,
1504
+ "metadata": {},
1505
+ "outputs": [],
1506
+ "source": [
1507
+ "model.fit(X, Y, batch_size = 16, epochs=1)"
1508
+ ]
1509
+ },
1510
+ {
1511
+ "cell_type": "markdown",
1512
+ "metadata": {},
1513
+ "source": [
1514
+ "<a name='2-3'></a>\n",
1515
+ "### 2.3 - Test the Model\n",
1516
+ "\n",
1517
+ "Finally, let's see how your model performs on the dev set."
1518
+ ]
1519
+ },
1520
+ {
1521
+ "cell_type": "code",
1522
+ "execution_count": null,
1523
+ "metadata": {},
1524
+ "outputs": [],
1525
+ "source": [
1526
+ "loss, acc, = model.evaluate(X_dev, Y_dev)\n",
1527
+ "print(\"Dev set accuracy = \", acc)"
1528
+ ]
1529
+ },
1530
+ {
1531
+ "cell_type": "markdown",
1532
+ "metadata": {},
1533
+ "source": [
1534
+ "This looks pretty good! \n",
1535
+ "* However, accuracy isn't a great metric for this task\n",
1536
+ " * Since the labels are heavily skewed to 0's, a neural network that just outputs 0's would get slightly over 90% accuracy. \n",
1537
+ "* We could define more useful metrics such as F1 score or Precision/Recall. \n",
1538
+ " * Let's not bother with that here, and instead just empirically see how the model does with some predictions."
1539
+ ]
1540
+ },
1541
+ {
1542
+ "cell_type": "markdown",
1543
+ "metadata": {},
1544
+ "source": [
1545
+ "<a name='3'></a>\n",
1546
+ "## 3 - Making Predictions\n",
1547
+ "\n",
1548
+ "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. \n",
1549
+ "\n",
1550
+ "<!--\n",
1551
+ "can use your model to make predictions on new audio clips.\n",
1552
+ "\n",
1553
+ "You will first need to compute the predictions for an input audio clip.\n",
1554
+ "\n",
1555
+ "**Exercise**: Implement predict_activates(). You will need to do the following:\n",
1556
+ "\n",
1557
+ "1. Compute the spectrogram for the audio file\n",
1558
+ "2. Use `np.swap` and `np.expand_dims` to reshape your input to size (1, Tx, n_freqs)\n",
1559
+ "5. Use forward propagation on your model to compute the prediction at each output step\n",
1560
+ "!-->"
1561
+ ]
1562
+ },
1563
+ {
1564
+ "cell_type": "code",
1565
+ "execution_count": null,
1566
+ "metadata": {},
1567
+ "outputs": [],
1568
+ "source": [
1569
+ "def detect_triggerword(filename):\n",
1570
+ " plt.subplot(2, 1, 1)\n",
1571
+ " \n",
1572
+ " # Correct the amplitude of the input file before prediction \n",
1573
+ " audio_clip = AudioSegment.from_wav(filename)\n",
1574
+ " audio_clip = match_target_amplitude(audio_clip, -20.0)\n",
1575
+ " file_handle = audio_clip.export(\"tmp.wav\", format=\"wav\")\n",
1576
+ " filename = \"tmp.wav\"\n",
1577
+ "\n",
1578
+ " x = graph_spectrogram(filename)\n",
1579
+ " # the spectrogram outputs (freqs, Tx) and we want (Tx, freqs) to input into the model\n",
1580
+ " x = x.swapaxes(0,1)\n",
1581
+ " x = np.expand_dims(x, axis=0)\n",
1582
+ " predictions = model.predict(x)\n",
1583
+ " \n",
1584
+ " plt.subplot(2, 1, 2)\n",
1585
+ " plt.plot(predictions[0,:,0])\n",
1586
+ " plt.ylabel('probability')\n",
1587
+ " plt.show()\n",
1588
+ " return predictions"
1589
+ ]
1590
+ },
1591
+ {
1592
+ "cell_type": "markdown",
1593
+ "metadata": {},
1594
+ "source": [
1595
+ "#### Insert a chime to acknowledge the \"activate\" trigger\n",
1596
+ "* 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. \n",
1597
+ "* $y^{\\langle t \\rangle}$ might be near 1 for many values in a row after \"activate\" is said, yet we want to chime only once. \n",
1598
+ " * So we will insert a chime sound at most once every 75 output steps. \n",
1599
+ " * This will help prevent us from inserting two chimes for a single instance of \"activate\". \n",
1600
+ " * This plays a role similar to non-max suppression from computer vision.\n",
1601
+ "\n",
1602
+ "<!-- \n",
1603
+ "**Exercise**: Implement chime_on_activate(). You will need to do the following:\n",
1604
+ "\n",
1605
+ "1. Loop over the predicted probabilities at each output step\n",
1606
+ "2. 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\n",
1607
+ "\n",
1608
+ "Use this code to convert from the 1,375 step discretization to the 10,000 step discretization and insert a \"chime\" using pydub:\n",
1609
+ "\n",
1610
+ "` audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio.duration_seconds)*1000)\n",
1611
+ "`\n",
1612
+ "!--> "
1613
+ ]
1614
+ },
1615
+ {
1616
+ "cell_type": "code",
1617
+ "execution_count": null,
1618
+ "metadata": {},
1619
+ "outputs": [],
1620
+ "source": [
1621
+ "chime_file = \"audio_examples/chime.wav\"\n",
1622
+ "def chime_on_activate(filename, predictions, threshold):\n",
1623
+ " audio_clip = AudioSegment.from_wav(filename)\n",
1624
+ " chime = AudioSegment.from_wav(chime_file)\n",
1625
+ " Ty = predictions.shape[1]\n",
1626
+ " # Step 1: Initialize the number of consecutive output steps to 0\n",
1627
+ " consecutive_timesteps = 0\n",
1628
+ " i = 0\n",
1629
+ " # Step 2: Loop over the output steps in the y\n",
1630
+ " while i < Ty:\n",
1631
+ " # Step 3: Increment consecutive output steps\n",
1632
+ " consecutive_timesteps += 1\n",
1633
+ " # Step 4: If prediction is higher than the threshold for 20 consecutive output steps have passed\n",
1634
+ " if consecutive_timesteps > 20:\n",
1635
+ " # Step 5: Superpose audio and background using pydub\n",
1636
+ " audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio_clip.duration_seconds) * 1000)\n",
1637
+ " # Step 6: Reset consecutive output steps to 0\n",
1638
+ " consecutive_timesteps = 0\n",
1639
+ " i = 75 * (i // 75 + 1)\n",
1640
+ " continue\n",
1641
+ " # if amplitude is smaller than the threshold reset the consecutive_timesteps counter\n",
1642
+ " if predictions[0, i, 0] < threshold:\n",
1643
+ " consecutive_timesteps = 0\n",
1644
+ " i += 1\n",
1645
+ " \n",
1646
+ " audio_clip.export(\"chime_output.wav\", format='wav')"
1647
+ ]
1648
+ },
1649
+ {
1650
+ "cell_type": "markdown",
1651
+ "metadata": {},
1652
+ "source": [
1653
+ "<a name='3-1'></a>\n",
1654
+ "### 3.1 - Test on Dev Examples"
1655
+ ]
1656
+ },
1657
+ {
1658
+ "cell_type": "markdown",
1659
+ "metadata": {},
1660
+ "source": [
1661
+ "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. "
1662
+ ]
1663
+ },
1664
+ {
1665
+ "cell_type": "code",
1666
+ "execution_count": null,
1667
+ "metadata": {},
1668
+ "outputs": [],
1669
+ "source": [
1670
+ "IPython.display.Audio(\"./raw_data/dev/1.wav\")"
1671
+ ]
1672
+ },
1673
+ {
1674
+ "cell_type": "code",
1675
+ "execution_count": null,
1676
+ "metadata": {},
1677
+ "outputs": [],
1678
+ "source": [
1679
+ "IPython.display.Audio(\"./raw_data/dev/2.wav\")"
1680
+ ]
1681
+ },
1682
+ {
1683
+ "cell_type": "markdown",
1684
+ "metadata": {},
1685
+ "source": [
1686
+ "Now lets run the model on these audio clips and see if it adds a chime after \"activate\"!"
1687
+ ]
1688
+ },
1689
+ {
1690
+ "cell_type": "code",
1691
+ "execution_count": null,
1692
+ "metadata": {},
1693
+ "outputs": [],
1694
+ "source": [
1695
+ "filename = \"./raw_data/dev/1.wav\"\n",
1696
+ "prediction = detect_triggerword(filename)\n",
1697
+ "chime_on_activate(filename, prediction, 0.5)\n",
1698
+ "IPython.display.Audio(\"./chime_output.wav\")"
1699
+ ]
1700
+ },
1701
+ {
1702
+ "cell_type": "code",
1703
+ "execution_count": null,
1704
+ "metadata": {},
1705
+ "outputs": [],
1706
+ "source": [
1707
+ "filename = \"./raw_data/dev/2.wav\"\n",
1708
+ "prediction = detect_triggerword(filename)\n",
1709
+ "chime_on_activate(filename, prediction, 0.5)\n",
1710
+ "IPython.display.Audio(\"./chime_output.wav\")"
1711
+ ]
1712
+ },
1713
+ {
1714
+ "cell_type": "markdown",
1715
+ "metadata": {},
1716
+ "source": [
1717
+ "### Congratulations \n",
1718
+ "\n",
1719
+ "You've come to the end of this assignment! \n",
1720
+ "\n",
1721
+ "#### Here's what you should remember:\n",
1722
+ "- Data synthesis is an effective way to create a large training set for speech problems, specifically trigger word detection. \n",
1723
+ "- 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.\n",
1724
+ "- An end-to-end deep learning approach can be used to build a very effective trigger word detection system. \n",
1725
+ "\n",
1726
+ "*Congratulations* on finishing this assignment!"
1727
+ ]
1728
+ },
1729
+ {
1730
+ "cell_type": "markdown",
1731
+ "metadata": {},
1732
+ "source": [
1733
+ "<a name='4'></a>\n",
1734
+ "## 4 - Try Your Own Example! (OPTIONAL/UNGRADED)\n",
1735
+ "\n",
1736
+ "In this optional and ungraded portion of this notebook, you can try your model on your own audio clips! \n",
1737
+ "\n",
1738
+ "* 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`. \n",
1739
+ "* Be sure to upload the audio as a wav file. \n",
1740
+ "* 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. \n",
1741
+ "* If your audio recording is not 10 seconds, the code below will either trim or pad it as needed to make it 10 seconds. "
1742
+ ]
1743
+ },
1744
+ {
1745
+ "cell_type": "code",
1746
+ "execution_count": null,
1747
+ "metadata": {},
1748
+ "outputs": [],
1749
+ "source": [
1750
+ "# Preprocess the audio to the correct format\n",
1751
+ "def preprocess_audio(filename):\n",
1752
+ " # Trim or pad audio segment to 10000ms\n",
1753
+ " padding = AudioSegment.silent(duration=10000)\n",
1754
+ " segment = AudioSegment.from_wav(filename)[:10000]\n",
1755
+ " segment = padding.overlay(segment)\n",
1756
+ " # Set frame rate to 44100\n",
1757
+ " segment = segment.set_frame_rate(44100)\n",
1758
+ " # Export as wav\n",
1759
+ " segment.export(filename, format='wav')"
1760
+ ]
1761
+ },
1762
+ {
1763
+ "cell_type": "markdown",
1764
+ "metadata": {},
1765
+ "source": [
1766
+ "Once you've uploaded your audio file to Coursera, put the path to your file in the variable below."
1767
+ ]
1768
+ },
1769
+ {
1770
+ "cell_type": "code",
1771
+ "execution_count": null,
1772
+ "metadata": {},
1773
+ "outputs": [],
1774
+ "source": [
1775
+ "your_filename = \"audio_examples/my_audio.wav\""
1776
+ ]
1777
+ },
1778
+ {
1779
+ "cell_type": "code",
1780
+ "execution_count": null,
1781
+ "metadata": {},
1782
+ "outputs": [],
1783
+ "source": [
1784
+ "preprocess_audio(your_filename)\n",
1785
+ "IPython.display.Audio(your_filename) # listen to the audio you uploaded "
1786
+ ]
1787
+ },
1788
+ {
1789
+ "cell_type": "markdown",
1790
+ "metadata": {},
1791
+ "source": [
1792
+ "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."
1793
+ ]
1794
+ },
1795
+ {
1796
+ "cell_type": "code",
1797
+ "execution_count": null,
1798
+ "metadata": {},
1799
+ "outputs": [],
1800
+ "source": [
1801
+ "chime_threshold = 0.5\n",
1802
+ "prediction = detect_triggerword(your_filename)\n",
1803
+ "chime_on_activate(your_filename, prediction, chime_threshold)\n",
1804
+ "IPython.display.Audio(\"./chime_output.wav\")"
1805
+ ]
1806
+ },
1807
+ {
1808
+ "cell_type": "code",
1809
+ "execution_count": null,
1810
+ "metadata": {},
1811
+ "outputs": [],
1812
+ "source": []
1813
+ }
1814
+ ],
1815
+ "metadata": {
1816
+ "kernelspec": {
1817
+ "display_name": "Python 3",
1818
+ "language": "python",
1819
+ "name": "python3"
1820
+ },
1821
+ "language_info": {
1822
+ "codemirror_mode": {
1823
+ "name": "ipython",
1824
+ "version": 3
1825
+ },
1826
+ "file_extension": ".py",
1827
+ "mimetype": "text/x-python",
1828
+ "name": "python",
1829
+ "nbconvert_exporter": "python",
1830
+ "pygments_lexer": "ipython3",
1831
+ "version": "3.7.6"
1832
+ }
1833
+ },
1834
+ "nbformat": 4,
1835
+ "nbformat_minor": 2
1836
+ }
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/Trigger_word_detection_v2a.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a2ac45381690397424fb0882b83213d6eeb8f5b4811fd29251f1195d0edec58
3
+ size 29212735
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_dev/X_dev.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:976486c83889ec182da33f32d7ccc1f928ed893c8a2ee3384c7b2d8c45fe12e7
3
+ size 111322328
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_dev/Y_dev.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5055b824872ddf114a2317dc82d0f9a237b1cf9811aa8b0ddcde57a0ed96d814
3
+ size 275128
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/X.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05d21b8db3929bc2cdedec44e4036323b0547d8f1276c7b63a2554b3ed0537fb
3
+ size 142492544
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/XY_train/Y.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65e87e1ca59628d5a6516eaf4d5d3355be93c0d81745c095600bebb6fed382c8
3
+ size 352128
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/__pycache__/td_utils.cpython-37.pyc ADDED
Binary file (1.48 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/__pycache__/test_utils.cpython-37.pyc ADDED
Binary file (2.17 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/chime.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92bd78b7795b26365b0cb1464b511d1abc382d535e58c9df332e866c0f97f87d
3
+ size 165476
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/example_train.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f05679dec5d8bf560a5914627c98c7ab6b59abcd71dda9de1daa7e7b1437afe
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/insert_reference.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03719961e6afa8302ca0283291c6881bab975e305ee90a7d33b676719b54a244
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/my_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebeca83419e48d23d92e56c014df63c4dc685ab5dc8c005c416672e99ad0b1e9
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/audio_examples/train_reference.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f5f7404f7ea18d9a89917d8fb6c696546438432cd5054d3cec43f6b2a7cf20f
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/chime_output.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86ec3d6e23d0b39e59b311dc148d5fc96042699b17d27e8b3b4bba9100526af4
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/generateTestCases.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # New Generate Test Cases
2
+ import numpy as np
3
+ import math
4
+ import os,sys
5
+ sys.path.append('../')
6
+ os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
7
+
8
+ from td_utils import *
9
+ import warnings
10
+ warnings.filterwarnings("ignore")
11
+
12
+ from pydub import AudioSegment
13
+
14
+ class suppress_stdout_stderr(object):
15
+ '''
16
+ A context manager for doing a "deep suppression" of stdout and stderr in
17
+ Python, i.e. will suppress all print, even if the print originates in a
18
+ compiled C/Fortran sub-function.
19
+ This will not suppress raised exceptions, since exceptions are printed
20
+ to stderr just before a script exits, and after the context manager has
21
+ exited (at least, I think that is why it lets exceptions through).
22
+
23
+ '''
24
+ def __init__(self):
25
+ # Open a pair of null files
26
+ self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
27
+ # Save the actual stdout (1) and stderr (2) file descriptors.
28
+ self.save_fds = [os.dup(1), os.dup(2)]
29
+
30
+ def __enter__(self):
31
+ # Assign the null pointers to stdout and stderr.
32
+ os.dup2(self.null_fds[0],1)
33
+ os.dup2(self.null_fds[1],2)
34
+
35
+ def __exit__(self, *_):
36
+ # Re-assign the real stdout/stderr back to (1) and (2)
37
+ os.dup2(self.save_fds[0],1)
38
+ os.dup2(self.save_fds[1],2)
39
+ # Close all file descriptors
40
+ for fd in self.null_fds + self.save_fds:
41
+ os.close(fd)
42
+
43
+ with suppress_stdout_stderr():
44
+ from solutions import *
45
+
46
+ # import copy
47
+ # from keras.callbacks import History
48
+ # import tensorflow as tf
49
+ sys.path.append('../../')
50
+
51
+ from grader_support import stdout_redirector
52
+ from grader_support import util
53
+
54
+
55
+
56
+
57
+ # This grader is for the Emojify assignment
58
+
59
+ mFiles = [
60
+ "is_overlapping.py",
61
+ "insert_audio_clip.py",
62
+ "insert_ones.py",
63
+ "create_training_example.py",
64
+ "model.py"
65
+ ]
66
+
67
+ np.random.seed(3)
68
+
69
+ # generating the testCases for is_overlapping
70
+ overlap1 = is_overlapping((900, 2500), [(2000, 2550), (260, 949)])
71
+ overlap2 = is_overlapping((2306, 2307), [(824, 1532), (1900, 2305), (3424, 3656)])
72
+
73
+ # generating the test cases for the insert_audio_clip
74
+ # (2732, 3452), (4859, 5579)
75
+ a = AudioSegment.from_wav("activate.wav")
76
+ b = AudioSegment.from_wav("background.wav")
77
+ audio_clip, segment_time = insert_audio_clip(b, a, [(3790, 4400)])
78
+ audio_clip.export('test.wav', format = 'wav')
79
+
80
+ inserted = graph_spectrogram('test.wav')
81
+
82
+ # generate the testCases for insert_ones
83
+ arr1 = insert_ones(np.zeros((1, Ty)), 9)
84
+
85
+ # generate the test Cases for create_training_example
86
+
87
+ n = AudioSegment.from_wav("negative.wav")
88
+
89
+ A = []
90
+ N = []
91
+ A.append(a)
92
+ N.append(n)
93
+
94
+ with stdout_redirector.stdout_redirected():
95
+ a, s = create_training_example(b, A, N)
96
+
97
+
98
+ # generating the test cases for the model
99
+ with suppress_stdout_stderr():
100
+ model = model(input_shape = (Tx, n_freq))
101
+ ml = len(model.layers)
102
+ cp = model.count_params()
103
+ mi = len(model.inputs)
104
+ mo = len(model.outputs)
105
+
106
+ def generateTestCases():
107
+ testCases = {
108
+ 'is_overlapping': {
109
+ 'partId': 'S8DvY',
110
+ 'testCases': [
111
+ {
112
+ 'testInput': ((900, 2500), [(2000, 2550), (260, 949)]),
113
+ 'testOutput': overlap1
114
+ },
115
+ {
116
+ 'testInput': ((2306, 2307), [(824, 1532), (1900, 2305), (3424, 3656)]),
117
+ 'testOutput': overlap2
118
+ }
119
+ ]
120
+ },
121
+ 'insert_audio_clip': {
122
+ 'partId': 'BSIWi',
123
+ 'testCases': [
124
+ {
125
+ 'testInput': ("activate.wav", "background.wav"),
126
+ 'testOutput': inserted
127
+ }
128
+ ]
129
+ },
130
+ 'insert_ones': {
131
+ 'partId': '2Kdnr',
132
+ 'testCases': [
133
+ {
134
+ 'testInput': (np.zeros((1, Ty)), 9) ,
135
+ 'testOutput': arr1
136
+ }
137
+ ]
138
+ },
139
+ 'create_training_example': {
140
+ 'partId': 'v097u',
141
+ 'testCases': [
142
+ {
143
+ 'testInput': (b, A, N),
144
+ 'testOutput': (a,s)
145
+ }
146
+ ]
147
+ },
148
+ 'model': {
149
+ 'partId': '0Txcd',
150
+ 'testCases': [
151
+ {
152
+ 'testInput': (Tx, n_freq),
153
+ 'testOutput': np.asarray([cp, ml, mi, mo])
154
+ }
155
+ ]
156
+ }
157
+ }
158
+ return testCases
159
+
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/label_diagram.png ADDED
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/model.png ADDED

Git LFS Details

  • SHA256: a3cdeeb86bddb27b101aedec2e79fdeb3e37a5732962ea6e2d3cce12b37a6946
  • Pointer size: 131 Bytes
  • Size of remote file: 232 kB
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/ones_reference.png ADDED
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/sound.png ADDED

Git LFS Details

  • SHA256: 49d883090e8db70d6789c0dd6a40fa04ee7144bb6feb2e6c3592ad589d7227d1
  • Pointer size: 131 Bytes
  • Size of remote file: 201 kB
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/spectrogram.png ADDED
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/train_label.png ADDED
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/images/train_reference.png ADDED

Git LFS Details

  • SHA256: 7f1201d5879840450f28e3310102d059139ce17f5e7103a80d3e7f1d38216e7e
  • Pointer size: 131 Bytes
  • Size of remote file: 350 kB
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/insert_test.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03719961e6afa8302ca0283291c6881bab975e305ee90a7d33b676719b54a244
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22f4a153c9e50f73db60df7fc67bce93698b31594a2383a41011eab4ea9e8ef5
3
+ size 2130896
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"class_name": "Functional", "config": {"name": "model", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": [null, 5511, 101], "dtype": "float32", "sparse": false, "ragged": false, "name": "input_1"}, "name": "input_1", "inbound_nodes": []}, {"class_name": "Conv1D", "config": {"name": "conv1d", "trainable": true, "dtype": "float32", "filters": 196, "kernel_size": [15], "strides": [4], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1], "groups": 1, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "name": "conv1d", "inbound_nodes": [[["input_1", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization", "trainable": false, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization", "inbound_nodes": [[["conv1d", 0, 0, {}]]]}, {"class_name": "Activation", "config": {"name": "activation", "trainable": true, "dtype": "float32", "activation": "relu"}, "name": "activation", "inbound_nodes": [[["batch_normalization", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout", "inbound_nodes": [[["activation", 0, 0, {}]]]}, {"class_name": "GRU", "config": {"name": "gru", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 128, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2, "reset_after": true}, "name": "gru", "inbound_nodes": [[["dropout", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_1", "inbound_nodes": [[["gru", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization_1", "trainable": false, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization_1", "inbound_nodes": [[["dropout_1", 0, 0, {}]]]}, {"class_name": "GRU", "config": {"name": "gru_1", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 128, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2, "reset_after": true}, "name": "gru_1", "inbound_nodes": [[["batch_normalization_1", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_2", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_2", "inbound_nodes": [[["gru_1", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization_2", "trainable": false, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization_2", "inbound_nodes": [[["dropout_2", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_3", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_3", "inbound_nodes": [[["batch_normalization_2", 0, 0, {}]]]}, {"class_name": "TimeDistributed", "config": {"name": "time_distributed", "trainable": true, "dtype": "float32", "layer": {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 1, "activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}}, "name": "time_distributed", "inbound_nodes": [[["dropout_3", 0, 0, {}]]]}], "input_layers": [["input_1", 0, 0]], "output_layers": [["time_distributed", 0, 0]]}, "keras_version": "2.4.0", "backend": "tensorflow"}
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model_new8.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92dc387f9230849d6707c73ab9a6a4dd060c8d79fea07f5b7a853ebfca1d798b
3
+ size 2130888
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/model_new8.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"class_name": "Functional", "config": {"name": "model", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": [null, 5511, 101], "dtype": "float32", "sparse": false, "ragged": false, "name": "input_1"}, "name": "input_1", "inbound_nodes": []}, {"class_name": "Conv1D", "config": {"name": "conv1d", "trainable": true, "dtype": "float32", "filters": 196, "kernel_size": [15], "strides": [4], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1], "groups": 1, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "name": "conv1d", "inbound_nodes": [[["input_1", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization", "trainable": true, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization", "inbound_nodes": [[["conv1d", 0, 0, {}]]]}, {"class_name": "Activation", "config": {"name": "activation", "trainable": true, "dtype": "float32", "activation": "relu"}, "name": "activation", "inbound_nodes": [[["batch_normalization", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout", "inbound_nodes": [[["activation", 0, 0, {}]]]}, {"class_name": "GRU", "config": {"name": "gru", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 128, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2, "reset_after": true}, "name": "gru", "inbound_nodes": [[["dropout", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_1", "inbound_nodes": [[["gru", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization_1", "trainable": true, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization_1", "inbound_nodes": [[["dropout_1", 0, 0, {}]]]}, {"class_name": "GRU", "config": {"name": "gru_1", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 128, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2, "reset_after": true}, "name": "gru_1", "inbound_nodes": [[["batch_normalization_1", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_2", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_2", "inbound_nodes": [[["gru_1", 0, 0, {}]]]}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization_2", "trainable": true, "dtype": "float32", "axis": [2], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}, "name": "batch_normalization_2", "inbound_nodes": [[["dropout_2", 0, 0, {}]]]}, {"class_name": "Dropout", "config": {"name": "dropout_3", "trainable": true, "dtype": "float32", "rate": 0.8, "noise_shape": null, "seed": null}, "name": "dropout_3", "inbound_nodes": [[["batch_normalization_2", 0, 0, {}]]]}, {"class_name": "TimeDistributed", "config": {"name": "time_distributed", "trainable": true, "dtype": "float32", "layer": {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 1, "activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}}, "name": "time_distributed", "inbound_nodes": [[["dropout_3", 0, 0, {}]]]}], "input_layers": [["input_1", 0, 0]], "output_layers": [["time_distributed", 0, 0]]}, "keras_version": "2.4.0", "backend": "tensorflow"}
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/models/tr_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1fc69bf375bbe0a3ed64f8df6766d4aff61aa2fc9a6b48959f88a7b5b6fd792
3
+ size 7687264
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0837e165424b2ee6868aff35019c266fcfb73066a55a132f09f20a0baa130445
3
+ size 127148
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1_act2.wav ADDED
Binary file (64.5 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/1_act3.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4087f9e8d33157ec3d260bbe36b6f5cede6ed4db851f46a97398cad2f6e25bcc
3
+ size 307244
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28e524a403d45080ca88ad3b31eb8729b916d9e56f7b95df751eb34778b30abb
3
+ size 160336
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2_act2.wav ADDED
Binary file (64 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/2_act3.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7539f5966d7a4db2be94752600c2cfc6dc3c97d4a7d8c298714d4cd759ce60f8
3
+ size 278572
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a17469a412d5d8b113cc9c2442fc336da4fc8d2bd1a19e8bc7325d16b9099e56
3
+ size 117856
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3_act2.wav ADDED
Binary file (80.8 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/3_act3.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33a7db1f092ff91824bf0884ce8c868539574ec8187cde5c0f8064f9fefb6b2b
3
+ size 421932
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/activates/4_act2.wav ADDED
Binary file (57.8 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/1.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:300a3d49a912c53828163f8040b137bbbcd12e8d43c47faca27d048d239a3dfe
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/backgrounds/2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69a9f50b4d3f47bc10952049eb2f9730b8bdfd2376e44d6266b2b80ea57ed8ea
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/1.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55eb57c10eb0179e3cc08dc52bc9181c0908b659161aa310be74e5b94c894fda
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/dev/2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3947adc899c86618e9d6f22010c2c7891ca93ed775a29a7b2d237d00a1701cba
3
+ size 1764044
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/1.wav ADDED
Binary file (63.5 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/1_0.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df7e9713ce93df12570bc87b75a6a92c0f63426a6cc4d96ef6e2e7fe0e5aeb69
3
+ size 102176
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/2.wav ADDED
Binary file (71.8 kB). View file
 
Seq2Seq/Trigger_detection/home/jovyan/work/W3A2/raw_data/negatives/2_1.wav ADDED
Binary file (95.5 kB). View file