<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.0">Jekyll</generator><link href="https://jonathanbgn.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://jonathanbgn.com/" rel="alternate" type="text/html" /><updated>2022-04-05T09:27:30+00:00</updated><id>https://jonathanbgn.com/feed.xml</id><title type="html">Jonathan Bgn</title><subtitle>Building stuff with machine learning and natural language processing.</subtitle><author><name>Jonathan Boigne</name></author><entry><title type="html">A Timeline of Large Transformer Models for Speech</title><link href="https://jonathanbgn.com/2021/12/31/timeline-transformers-speech.html" rel="alternate" type="text/html" title="A Timeline of Large Transformer Models for Speech" /><published>2021-12-31T10:00:00+00:00</published><updated>2021-12-31T10:00:00+00:00</updated><id>https://jonathanbgn.com/2021/12/31/timeline-transformers-speech</id><content type="html" xml:base="https://jonathanbgn.com/2021/12/31/timeline-transformers-speech.html">&lt;p&gt;Since the arrival of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)&quot;&gt;Transformer architecture&lt;/a&gt; in 2017, transformer-based models have made their way into all domains of machine learning. As &lt;a href=&quot;https://twitter.com/karpathy/status/1468370605229547522&quot;&gt;Andrej Karpathy of Tesla noted&lt;/a&gt;, they are quickly becoming the go-to architecture as either a strong baseline or state-of-the-art performance for most problems in language, vision, and now speech.&lt;/p&gt;

&lt;p&gt;In speech processing especially, we are seeing many new methods to apply transformers to acoustic data. Popular libraries like &lt;a href=&quot;https://huggingface.co/models&quot;&gt;HuggingFace’s Transformers&lt;/a&gt; are also implementing more and more speech models.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/timeline-transformers-speech.png&quot; alt=&quot;A Timeline of Transformers for Speech&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Similar to the natural language processing field, tech companies are now building larger and larger speech transformer models. I will cover some of the most popular ones, starting in 2019 where things started to take off in the speech processing field.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2019-vq-wav2vec-mockingjay-discretebert&quot;&gt;2019: VQ-Wav2vec, Mockingjay, DiscreteBERT&lt;/h2&gt;

&lt;h3 id=&quot;vq-wav2vec&quot;&gt;VQ-Wav2vec&lt;/h3&gt;

&lt;p&gt;The &lt;a href=&quot;/2021/06/29/illustrated-wav2vec.html&quot;&gt;original wav2vec model&lt;/a&gt; did not use transformers and instead relied on two distinct convolutional networks. Its immediate successor, vq-wav2vec, re-used the same architecture but applied a quantization process to transform continuous acoustic features into discrete units (&lt;em&gt;VQ&lt;/em&gt; stands for &lt;em&gt;Vector Quantization&lt;/em&gt;). These discrete representations were then used to train a BERT model, a large transformer encoder network.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/vq-wav2vec.png&quot; alt=&quot;Architecture of vq-wav2vec&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/1910.05453&quot;&gt;vq-wav2vec paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In contrast to the original BERT model, only the Masked Language Modelling objective was used, as the next sentence prediction objective could hinder performance for speech.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;mockingjay&quot;&gt;Mockingjay&lt;/h3&gt;

&lt;p&gt;This model created by researchers at National Taiwan University experimented with applying transformer encoders directly to the continuous audio features, rather than discretizing first like vq-wav2vec. Inspired by BERT, the pre-training process also masks a random subset of audio frames for prediction. However, since the frames were not discretized, the model tries to reconstruct the original features frame, and an L1 reconstruction loss is used as the objective (hence the model is named after a bird that mimics sound).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/mockingjay.png&quot; alt=&quot;Architecture of Mockingjay&quot; width=&quot;400&quot; style=&quot;display: block; margin: auto;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/1910.12638&quot;&gt;Mockingjay paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The authors report improved performance on a variety of downstream tasks like phoneme classification, speaker recognition, and sentiment classification, after either extracting latent representations from the last layer of the model, a combination of intermediate hidden representations (weighted like ELMo), or directly fine-tuning the model to the downstream tasks.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;discretebert&quot;&gt;DiscreteBERT&lt;/h3&gt;

&lt;p&gt;With the same architecture and training process as vq-wav2vec, DiscreteBERT confirms the benefits of using discrete units as an input for the transformer encoder rather than continuous features. There is some slight difference in the training approach compared to vq-wav2vec, and you can have a look at &lt;a href=&quot;https://arxiv.org/abs/1911.03912&quot;&gt;the paper&lt;/a&gt; for more details.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/discrete-bert.png&quot; alt=&quot;Architecture of DiscreteBERT&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the &lt;a href=&quot;https://arxiv.org/abs/1911.03912&quot;&gt;original paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2020-conformer-wav2vec-20-decoar-20&quot;&gt;2020: Conformer, Wav2vec 2.0, DeCoAR 2.0…&lt;/h2&gt;

&lt;h3 id=&quot;conformer&quot;&gt;Conformer&lt;/h3&gt;

&lt;p&gt;In the first half of 2020, researchers at Google combined convolution neural networks to exploit local features with transformers to model the global context and achieved state-of-the-art performance on LibriSpeech. This out-performed previous Transformer-only transducers by a large margin, demonstrating the advantage of combining CNN with Transformer for end-to-end speech recognition. Their architecture replaces the Transformer blocks with Conformer blocks, which add a convolution operation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/conformer.png&quot; alt=&quot;Conformer Architecture&quot; width=&quot;400&quot; style=&quot;display: block; margin: auto;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;The conformer model combines self-attention with convolution wrapped in two feed-forward modules (&lt;a href=&quot;https://arxiv.org/abs/2005.08100&quot;&gt;Image source&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;wav2vec-20--xlsr-53&quot;&gt;Wav2vec 2.0 / XLSR-53&lt;/h3&gt;

&lt;p&gt;A continuation of the wav2vec series, wav2vec 2.0 replaces the convolutional context network of the original architecture with a transformer encoder. Despite the use of discrete speech units and a quantization module like the vq-wav2vec model, wav2vec 2.0 goes back to the original contrastive objective used in the first version of wav2vec, rather than the BERT’s masked language modeling objective.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_architecture_pretraining.png&quot; alt=&quot;Wav2vec 2.0, based on a transformer encoder&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from &lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;An Illustrated Tour of Wav2vec 2.0&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A few days after releasing the wav2vec 2.0 preprint, Facebook AI also released &lt;strong&gt;XLSR-53&lt;/strong&gt;, a multi-lingual version of the wav2vec 2.0 model trained in 53 languages.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;w2v-conformer&quot;&gt;w2v-Conformer&lt;/h3&gt;

&lt;p&gt;In a preprint released in October 2020, a team at Google merged the Conformer architecture with the wav2vec 2.0 pre-training objective and &lt;a href=&quot;https://paperswithcode.com/method/noisy-student&quot;&gt;noisy student training&lt;/a&gt; to reach new state-of-the-art results on LibriSpeech speech recognition. The team also scaled the model to a much larger dimension than the original wav2vec 2.0 paper, with a &lt;em&gt;Conformer XXL&lt;/em&gt; model using &lt;strong&gt;1 billion parameters&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/w2v-conformer.png&quot; alt=&quot;w2v-Conformer Architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the &lt;a href=&quot;https://arxiv.org/abs/2010.10504&quot;&gt;original paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;decoar-20&quot;&gt;DeCoAR 2.0&lt;/h3&gt;

&lt;p&gt;This model from Amazon Web Services is the successor of a non-transformer LSTM-based model named DeCoAR (Deep Contextualized Acoustic Representations), which takes its inspiration directly from the popular &lt;a href=&quot;https://en.wikipedia.org/wiki/ELMo&quot;&gt;ELMo model&lt;/a&gt; in natural language processing. This second version replaces the bi-directional LSTM layers with a transformer encoder and uses a combination of the wav2vec 2.0 loss and another reconstruction loss as its objective.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/decoar-2.png&quot; alt=&quot;DeCoAR 2.0 Architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/2012.06659&quot;&gt;DeCoAR 2.0 paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2021-unispeech-hubert-xls-r-bigssl&quot;&gt;2021: UniSpeech, HuBERT, XLS-R, BigSSL…&lt;/h2&gt;

&lt;h3 id=&quot;unispeech&quot;&gt;UniSpeech&lt;/h3&gt;

&lt;p&gt;In early 2021, Microsoft released a multi-task model that combines a self-supervised learning objective (same as wav2vec 2.0) with a supervised ASR objective (Connectionist temporal classification). This joint optimization allowed for better alignment of the discrete speech units with the phonetic structure of the audio, improving performance on multi-lingual speech recognition and audio domain transfer.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/unispeech.png&quot; alt=&quot;UniSpeech Architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/2101.07597&quot;&gt;UniSpeech paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;hubert&quot;&gt;HuBERT&lt;/h3&gt;

&lt;p&gt;Coming also from Facebook/Meta AI, HuBERT re-uses the wav2vec 2.0 architecture but replaces the contrastive objective by BERT’s original masked language modeling objective. This is made possible by a pre-training process alternating between two steps: a clustering step where pseudo-labels are assigned to short segments of speech, and a prediction step where the model is trained to predict these pseudo-labels at randomly-masked positions in the original audio sequence.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-hubert/hubert_explained.png&quot; alt=&quot;HuBERT Explained&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from &lt;a href=&quot;/2021/10/30/hubert-visually-explained.html&quot;&gt;HuBERT: How to Apply BERT to Speech, Visually Explained&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;w2v-bert&quot;&gt;w2v-BERT&lt;/h3&gt;

&lt;p&gt;w2v-BERT comes from researchers at Google Brain and MIT and combines concepts from wav2vec 2.0, BERT, and Conformer. Similar to w2v-Conformer, it re-uses the wav2vec 2.0 architecture but with transformer layers replaced by conformer layers. It also combines the contrastive loss of wav2vec 2.0 with the masked language modeling objective of BERT, allowing for an end-to-end training process of MLM without the need to alternate between processes like HuBERT. Its largest version, &lt;em&gt;w2v-BERT XXL&lt;/em&gt;, scales to &lt;strong&gt;1 billion parameters&lt;/strong&gt;, similar to the largest w2v-Conformer model.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/w2v-bert.png&quot; alt=&quot;w2v-BERT Architecture&quot; width=&quot;400&quot; style=&quot;display: block; margin: auto;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/2108.06209&quot;&gt;w2v-BERT paper&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;xls-r&quot;&gt;XLS-R&lt;/h3&gt;

&lt;p&gt;A scaled-up version of XLSR-53, based on wav2vec 2.0. This very large model uses &lt;strong&gt;2 billion parameters&lt;/strong&gt; and is trained on half a million hours of speech in 128 different languages. This is more than twice the original 53 languages used by XLSR-53. XLS-R attains state-of-the-art performance in speech translation to English and language identification.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/xls-r.png&quot; alt=&quot;XLS-R Architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from &lt;a href=&quot;https://ai.facebook.com/blog/xls-r-self-supervised-speech-processing-for-128-languages/&quot;&gt;Meta AI blog&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The model also seems to perform as well as English-only pre-trained versions of wav2vec 2.0 when translating from English speech, hinting at the potential of multi-lingual models compared to monolingual ones.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;bigssl&quot;&gt;BigSSL&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2109.13226&quot;&gt;BigSSL&lt;/a&gt; is a continuation of Google’s effort with its w2v-Conformer, scaling up both the model size and data (unlabeled and labeled data), and trained on approximately one million hours of audio. It is the largest of such speech Transformer models so far, with a staggering &lt;strong&gt;8 billion parameters&lt;/strong&gt;. This work highlights the benefits of scaling up speech models which, just like in natural language processing, benefit downstream tasks when trained on more data and with more parameters.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;unispeech-sat--wavlm&quot;&gt;UniSpeech-SAT / WavLM&lt;/h3&gt;

&lt;p&gt;Both coming from Microsoft, the UniSpeech-SAT and WavLM models follow the HuBERT framework while focusing on data-augmentation during the pre-training stage to improve speaker representation learning and speaker-related downstream tasks.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transformers-speech/unispeech-sat.png&quot; alt=&quot;UniSpeech-SAT Architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em style=&quot;display:block; text-align: center;&quot;&gt;Image from the original &lt;a href=&quot;https://arxiv.org/abs/2110.05752&quot;&gt;UniSpeech-SAT&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The WavLM model is especially efficient for downstream tasks, it is currently leading the &lt;a href=&quot;https://superbbenchmark.org/leaderboard&quot;&gt;SUPERB leaderboard&lt;/a&gt;, a performance benchmark for re-using speech representations in a variety of tasks such as automatic speech recognition, phoneme recognition, speaker identification, emotion recognition…&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-does-2022-hold-for-speech-processing&quot;&gt;What does 2022 hold for speech processing?&lt;/h2&gt;

&lt;p&gt;In light of all the innovations that happened in 2021, we can be quite optimistic for 2022. We will most likely see even larger transformer models and better ways to transfer knowledge from pre-trained models to downstream tasks. In another post I’ve listed what I think could be some of the most interesting &lt;a href=&quot;/2021/11/30/speech-processing-trends-2022.html&quot;&gt;trends in speech processing for 2022&lt;/a&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/2021/11/30/speech-processing-trends-2022.html&quot;&gt;2022 Trends for Speech Processing&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2021/10/30/hubert-visually-explained.html&quot;&gt;HuBERT: How to Apply BERT to Speech, Visually Explained&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;An Illustrated Tour of Wav2vec 2.0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2021/06/29/illustrated-wav2vec.html&quot;&gt;The Illustrated Wav2vec 1.0&lt;/a&gt;&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Since the arrival of the Transformer architecture in 2017, transformer-based models have made their way into all domains of machine learning. As Andrej Karpathy of Tesla noted, they are quickly becoming the go-to architecture as either a strong baseline or state-of-the-art performance for most problems in language, vision, and now speech.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://jonathanbgn.com/assets/images/transformers-speech/timeline-transformers-speech.png" /><media:content medium="image" url="https://jonathanbgn.com/assets/images/transformers-speech/timeline-transformers-speech.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">2022 Trends for Speech Processing</title><link href="https://jonathanbgn.com/2021/11/30/speech-processing-trends-2022.html" rel="alternate" type="text/html" title="2022 Trends for Speech Processing" /><published>2021-11-30T12:00:00+00:00</published><updated>2021-11-30T12:00:00+00:00</updated><id>https://jonathanbgn.com/2021/11/30/speech-processing-trends-2022</id><content type="html" xml:base="https://jonathanbgn.com/2021/11/30/speech-processing-trends-2022.html">&lt;p&gt;It’s an exciting time to be working in speech processing. The field has seen a lot of transformations and changes just over the past few years. In this post, I’d like to share my perspective on how I see the field moving forward in 2022, based on what we saw recently.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;more-transformers&quot;&gt;More Transformers&lt;/h2&gt;

&lt;p&gt;After revolutionizing the field of natural language processing, and then computer vision, the &lt;a href=&quot;https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)&quot;&gt;transformer architecture&lt;/a&gt; is now being adopted more and more in the speech processing community. It still feels like early days though, when you compare the diversity of transformer-based speech models compared to the multitude of such models in NLP.&lt;/p&gt;

&lt;p&gt;Most visible so far has been the &lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;wav2vec 2.0 model&lt;/a&gt; as well as &lt;a href=&quot;/2021/10/30/hubert-visually-explained.html&quot;&gt;HuBERT&lt;/a&gt;, both coming from Facebook AI (now called Meta AI). The use of transformers, where each position attends to every other one, enables much richer contextual representations of audio sequences, compared to previous methods which relied on recurrent neural networks like LSTM to build sequence-level embeddings.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_architecture_pretraining.png&quot; alt=&quot;Wav2vec 2.0, based on a transformer encoder&quot; /&gt;
&lt;em&gt;The wav2vec 2.0 model is based on the transformer encoder. Image from &lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;An Illustrated Tour of Wav2vec 2.0&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;larger-models-and-datasets&quot;&gt;Larger Models and Datasets&lt;/h2&gt;

&lt;p&gt;As the field will likely follow what happened in NLP after the introduction of transformers, we’ll see bigger models emerge in the next year. We are still far from what we see in NLP with GPT-3 and its 175 billion parameters though. The largest transformer-based speech model (&lt;strong&gt;XLS-R&lt;/strong&gt;) has slightly more than 2 billion parameters, around the same order of magnitude as the largest version of GPT-2, back in 2019.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/speech-processing-trends-2022/nlp_model_size.jpg&quot; alt=&quot;NLP Model Size&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;There seems to be no end in sight to NLP models scaling (&lt;a href=&quot;https://huggingface.co/blog/large-language-models&quot;&gt;image source&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Speech datasets too are being scaled up in size. The &lt;a href=&quot;https://commonvoice.mozilla.org/en&quot;&gt;Common Voice initiative&lt;/a&gt; by Mozilla has already collected more than 13,000 hours of voice samples from 75,000+ speakers in 76 languages. The &lt;a href=&quot;https://ai.facebook.com/blog/voxpopuli-the-largest-open-multilingual-speech-corpus-for-ai-translation-and-more/&quot;&gt;VoxPopuli dataset&lt;/a&gt;, open-sourced this year, offers 400,000 hours of unlabelled speech in 23 languages, making it the largest open speech dataset so far.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;less-supervision&quot;&gt;Less Supervision&lt;/h2&gt;

&lt;p&gt;As model sizes scale, so must training data. While we will see bigger labeled datasets, this will be far from being enough to feed the ever-larger capacity of these models. New approaches will likely be developed to train larger models more effectively in a self-supervised way, without the need to label data. We already saw a lot of different self-supervised training methods based on contrastive losses or unsupervised clustering to create pseudo-labels. More will come.&lt;/p&gt;

&lt;p&gt;Fully unsupervised ASR systems are also starting to make their apparition: &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-unsupervised-speech-recognition-without-supervision/&quot;&gt;wav2vec-U&lt;/a&gt;, released this year, shows comparable performance to the best supervised models from only a few years ago, while using no labeled data at all.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/speech-processing-trends-2022/wav2vec-u-performance.jpg&quot; alt=&quot;Wav2vec-U Performance&quot; /&gt;
&lt;em&gt;Wav2vec-U shows impressive performance on speech recognition without using any labeled data (Librispeech benchmark) (&lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-unsupervised-speech-recognition-without-supervision/&quot;&gt;image source&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;multilingual-models&quot;&gt;Multilingual Models&lt;/h2&gt;

&lt;p&gt;The rise of &lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;self-supervised learning&lt;/a&gt; has opened the door to effective speech recognition for low-resource languages for which labeled datasets aren’t available, or too small to be able to generalize from. The just-released &lt;a href=&quot;https://ai.facebook.com/blog/xls-r-self-supervised-speech-processing-for-128-languages/&quot;&gt;XLS-R model&lt;/a&gt;, the largest of such models yet with over 2 billion parameters, has been trained on 128 languages, more than twice its predecessor. Interestingly, such large multilingual models improve performance much more when scaling the model size. This will probably lead to a preference for multilingual models over single language ones in the future.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/speech-processing-trends-2022/xls-r_speech_translation.png&quot; alt=&quot;XLS-R speech translation performance&quot; /&gt;
&lt;em&gt;Speech translation performance of XLS-R from target language to English (&lt;a href=&quot;https://ai.facebook.com/blog/xls-r-self-supervised-speech-processing-for-128-languages/&quot;&gt;image source&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;textless-nlp&quot;&gt;Textless NLP&lt;/h2&gt;

&lt;p&gt;Generative models like GPT-3 are certainly impressive, but they don’t capture all the subtlety of languages. This year researchers at Meta AI released the &lt;a href=&quot;https://ai.facebook.com/blog/textless-nlp-generating-expressive-speech-from-raw-audio/&quot;&gt;Generative Spoken Language Model (GSLM)&lt;/a&gt;, capable of generating speech continuation without any dependency on text. This kind of textless NLP model enables much richer language expression by capturing much more para-linguistic information than just semantics. Tone, emotions, speakers voice characteristics… all these elements can now be encoded both for classification or generation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/speech-processing-trends-2022/generative-spoken-language-model.jpg&quot; alt=&quot;Generative Spoken Language Model&quot; /&gt;
&lt;em&gt;Architecture of the Generative Spoken Language Model, a textless generative model (&lt;a href=&quot;https://ai.facebook.com/blog/textless-nlp-generating-expressive-speech-from-raw-audio/&quot;&gt;image source&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Such progress in speech processing could lead to many breakthrough applications, like expressive searchable speech audio, better voice interfaces and assistants, and immersive entertainment.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;better-libraries-and-tools&quot;&gt;Better Libraries and Tools&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/speech-processing-trends-2022/huggingface-transformers.png&quot; alt=&quot;HuggingFace Library&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Speech processing used to be much harder, but things are now changing fast. This year, the popular HuggingFace Transformers library started implementing speech models like wav2vec 2.0 and HuBERT. The &lt;a href=&quot;https://speechbrain.github.io/index.html&quot;&gt;SpeechBrain tookit&lt;/a&gt; has also seen much progress, and the &lt;a href=&quot;https://github.com/pytorch/audio&quot;&gt;TorchAudio library&lt;/a&gt; got some serious improvements this year, with new models added like Tacotron2 as well as easy access to some of the most popular speech datasets. We should expect more to come soon. Exciting times ahead!&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">It’s an exciting time to be working in speech processing. The field has seen a lot of transformations and changes just over the past few years. In this post, I’d like to share my perspective on how I see the field moving forward in 2022, based on what we saw recently.</summary></entry><entry><title type="html">HuBERT: How to Apply BERT to Speech, Visually Explained</title><link href="https://jonathanbgn.com/2021/10/30/hubert-visually-explained.html" rel="alternate" type="text/html" title="HuBERT: How to Apply BERT to Speech, Visually Explained" /><published>2021-10-30T08:00:00+00:00</published><updated>2021-10-30T08:00:00+00:00</updated><id>https://jonathanbgn.com/2021/10/30/hubert-visually-explained</id><content type="html" xml:base="https://jonathanbgn.com/2021/10/30/hubert-visually-explained.html">&lt;p&gt;Research in &lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;self-supervised learning&lt;/a&gt; for speech has been accelerating since the original &lt;a href=&quot;/2021/06/29/illustrated-wav2vec.html&quot;&gt;wav2vec model&lt;/a&gt; released by Facebook AI in 2019. &lt;strong&gt;HuBERT&lt;/strong&gt; is one of the latest of such models, with an open-source implementation already available in HuggingFace’s Transformers library.&lt;/p&gt;

&lt;p&gt;Its main idea is to discover discrete &lt;strong&gt;hidden units&lt;/strong&gt; (the &lt;em&gt;Hu&lt;/em&gt; in the name) to transform speech data into a more “language-like” structure. These hidden units could be compared to words or tokens in a text sentence. Representing speech as a sequence of discrete units enables us to apply the same powerful models available for natural language processing, such as BERT.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-hubert/hubert_explained.png&quot; alt=&quot;HuBERT Explained&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The method draws inspiration from the &lt;a href=&quot;https://research.fb.com/publications/deep-clustering-for-unsupervised-learning-of-visual-features/&quot;&gt;DeepCluster paper&lt;/a&gt; in computer vision, where images are assigned to a given number of clusters before re-using these clusters as “pseudo-labels” for training the model in a self-supervised way. In HuBERT’s case, clustering is not applied on images but on short audio segments (25 milliseconds), and the resulting clusters become the &lt;em&gt;hidden units&lt;/em&gt; that the model will be trained to predict.&lt;/p&gt;

&lt;h3 id=&quot;differences-with-wav2vec-20&quot;&gt;Differences with wav2vec 2.0&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;&lt;u&gt;Note:&lt;/u&gt; Have a look at &lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;An Illustrated Tour of Wav2vec 2.0&lt;/a&gt; for a detailed explanation of the model.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;At first glance, HuBERT looks very similar to &lt;strong&gt;wav2vec 2.0&lt;/strong&gt;: both models use the same convolutional network followed by a transformer encoder. However, their training processes are very different, and HuBERT’s performance, when fine-tuned for automatic speech recognition, either matches or improves upon wav2vec 2.0. Here are the key differences to keep in mind:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HuBERT uses the cross-entropy loss&lt;/strong&gt;, instead of the more complex combination of contrastive loss + diversity loss used by wav2vec 2.0. This makes training easier and more stable since this is the same loss that was used in the &lt;a href=&quot;https://arxiv.org/abs/1810.04805v2&quot;&gt;original BERT paper&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HuBERT builds targets via a separate clustering process&lt;/strong&gt;, while wav2vec 2.0 learns its targets simultaneously while training the model (via a quantization process using Gumbel-softmax). While wav2vec 2.0 training could seem simpler as it consists of only a single step, in practice, it can become more complex as the temperature of the Gumbel-softmax must be carefully adjusted during training to prevent the model from sticking to a small subset of all available targets.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HuBERT re-uses embeddings from the BERT encoder to improve targets&lt;/strong&gt;, while wav2vec 2.0 only uses the output of the convolutional network for quantization. In the HuBERT paper, the authors show that using such embeddings from intermediate layers of the BERT encoder leads to better targets quality than using the CNN output.&lt;/p&gt;

&lt;p&gt;In terms of model architecture, the &lt;em&gt;BASE&lt;/em&gt; and &lt;em&gt;LARGE&lt;/em&gt; versions of HuBERT have the same configuration as the &lt;em&gt;BASE&lt;/em&gt; and &lt;em&gt;LARGE&lt;/em&gt; versions of wav2vec 2.0 (95 million and 317 million of parameters respectively). However, an &lt;em&gt;X-LARGE&lt;/em&gt; version of HuBERT is also used with twice as many transformer layers as in the &lt;em&gt;LARGE&lt;/em&gt; version, with almost 1 billion parameters.&lt;/p&gt;

&lt;h2 id=&quot;training-process&quot;&gt;Training process&lt;/h2&gt;

&lt;p&gt;The training process alternates between two steps: a clustering step to create pseudo-targets, and a prediction step where the model tries to guess these targets at masked positions.&lt;/p&gt;

&lt;h3 id=&quot;step-1-discover-hidden-units-targets-through-clustering&quot;&gt;Step 1: Discover “hidden units” targets through clustering&lt;/h3&gt;

&lt;p&gt;The first step is to extract the hidden units (pseudo-targets) from the raw waveform of the audio. The &lt;a href=&quot;https://en.wikipedia.org/wiki/K-means_clustering&quot;&gt;K-means algorithm&lt;/a&gt; is used to assign each segment of audio (25 milliseconds) into one of &lt;em&gt;K&lt;/em&gt; clusters. Each identified cluster will then become a hidden unit, and all audio frames assigned to this cluster will be assigned with this unit label. Each hidden unit is then mapped to its corresponding &lt;em&gt;embedding vector&lt;/em&gt; that can be used during the second step to make predictions.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-hubert/hubert_clustering.png&quot; alt=&quot;HuBERT Clustering Step&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The most important decision for clustering is into which features to transform the waveform for clustering. &lt;a href=&quot;https://en.wikipedia.org/wiki/Mel-frequency_cepstrum&quot;&gt;Mel-Frequency Cepstral Coefficients (MFCCs)&lt;/a&gt; are used for the first clustering step, as these features have been shown to be relatively efficient for speech processing. However, for subsequent clustering steps, representations from an intermediate layer of the HuBERT transformer encoder (from the previous iteration) are re-used.&lt;/p&gt;

&lt;p&gt;More precisely, the 6th transformer layer is used for clustering during the second iteration of the HuBERT &lt;em&gt;BASE&lt;/em&gt; model (the &lt;em&gt;BASE&lt;/em&gt; model is only trained for two iterations in total). Furthermore, HuBERT &lt;em&gt;LARGE&lt;/em&gt; and &lt;em&gt;X-LARGE&lt;/em&gt; are trained for a third iteration by re-using the 9th transformer layer from the second iteration of the &lt;em&gt;BASE&lt;/em&gt; model.&lt;/p&gt;

&lt;h4 id=&quot;combining-clustering-of-different-sizes&quot;&gt;Combining clustering of different sizes&lt;/h4&gt;

&lt;p&gt;The authors also experiment with a combination of multiple clustering with a different number of clusters to capture targets of different granularity (
 vowel/consonant vs &lt;a href=&quot;https://en.wikipedia.org/wiki/Phone_(phonetics)&quot;&gt;sub-phone states&lt;/a&gt; for example). They show that using cluster ensembles can improve performance by a small margin. You can find more details on this in the &lt;a href=&quot;https://arxiv.org/abs/2106.07447&quot;&gt;original paper&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;step-2-predict-noisy-targets-from-the-context&quot;&gt;Step 2: Predict noisy targets from the context&lt;/h3&gt;

&lt;p&gt;The second step is the same as for the original BERT: training with the &lt;strong&gt;masked language modeling&lt;/strong&gt; objective. Around 50% of transformer encoder input features are masked, and the model is asked to predict the targets for these positions. For this, the cosine similarity is computed between the transformer outputs (projected to a lower dimension) and each hidden unit embedding from all possible hidden units to give prediction logits. The cross-entropy loss is then used to penalize wrong predictions.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-hubert/hubert_pretraining_prediction.png&quot; alt=&quot;HuBERT Prediction Step&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The loss is only applied to the masked positions&lt;/strong&gt; as it has been shown to perform better when using noisy labels. The authors prove this experimentally by trying to predict only masked targets, only un-masked ones, or both together.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;HuBERT can be used for automatic speech recognition like wav2vec 2.0 before it, but the paper authors also found that the representations learned can be very useful for speech generation. Indeed in another paper written by most of the same authors, they build a &lt;a href=&quot;https://ai.facebook.com/blog/textless-nlp-generating-expressive-speech-from-raw-audio/&quot;&gt;generative spoken language model&lt;/a&gt; able to generate speech without any use of text, opening the door to more applications for textless NLP.&lt;/p&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/2021/09/30/illustrated-wav2vec-2.html&quot;&gt;An Illustrated Tour of Wav2vec 2.0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2021/06/29/illustrated-wav2vec.html&quot;&gt;The Illustrated Wav2vec 1.0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;The Rise of Self-Supervised Learning&lt;/a&gt;&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Research in self-supervised learning for speech has been accelerating since the original wav2vec model released by Facebook AI in 2019. HuBERT is one of the latest of such models, with an open-source implementation already available in HuggingFace’s Transformers library.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://jonathanbgn.com/assets/images/illustrated-hubert/hubert_explained.png" /><media:content medium="image" url="https://jonathanbgn.com/assets/images/illustrated-hubert/hubert_explained.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">An Illustrated Tour of Wav2vec 2.0</title><link href="https://jonathanbgn.com/2021/09/30/illustrated-wav2vec-2.html" rel="alternate" type="text/html" title="An Illustrated Tour of Wav2vec 2.0" /><published>2021-09-30T14:00:00+00:00</published><updated>2021-09-30T14:00:00+00:00</updated><id>https://jonathanbgn.com/2021/09/30/illustrated-wav2vec-2</id><content type="html" xml:base="https://jonathanbgn.com/2021/09/30/illustrated-wav2vec-2.html">&lt;p&gt;Transformer-based neural networks have been revolutionizing the natural language processing field, but are only starting to become popular in the speech processing community. &lt;strong&gt;Wav2vec 2.0&lt;/strong&gt; is set to change that. Its architecture is based on the Transformer’s encoder, with a training objective similar to &lt;strong&gt;BERT’s masked language modeling&lt;/strong&gt; objective, but adapted for speech.&lt;/p&gt;

&lt;p&gt;This new method allows for efficient &lt;a href=&quot;https://en.wikipedia.org/wiki/Semi-supervised_learning&quot;&gt;semi-supervised training&lt;/a&gt;: first, pre-train the model on a large quantity of unlabeled speech, then fine-tune on a smaller labeled dataset. In &lt;a href=&quot;https://proceedings.neurips.cc/paper/2020/hash/92d1e1eb1cd6f9fba3227870bb6d7f07-Abstract.html&quot;&gt;wav2vec 2.0’s original paper&lt;/a&gt;, the authors demonstrated that fine-tuning the model on only one hour of labeled speech data could beat the previous state-of-the-art systems trained on 100 times more labeled data.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_architecture_pretraining.png&quot; alt=&quot;Wav2vec 2.0 Architecture Overview&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Above is an overview of the wav2vec 2.0 architecture and its pre-training process. There are four important elements in this diagram: the &lt;strong&gt;feature encoder&lt;/strong&gt;, &lt;strong&gt;context network&lt;/strong&gt;, &lt;strong&gt;quantization module&lt;/strong&gt;, and the &lt;strong&gt;contrastive loss&lt;/strong&gt; (pre-training objective). We will open the hood and look in detail at each one.&lt;/p&gt;

&lt;h2 id=&quot;feature-encoder&quot;&gt;Feature encoder&lt;/h2&gt;

&lt;p&gt;The feature encoder’s job is to reduce the dimensionality of the audio data, converting the raw waveform into a sequence of feature vectors &lt;em&gt;Z&lt;sub&gt;0&lt;/sub&gt;, Z&lt;sub&gt;1&lt;/sub&gt;, Z&lt;sub&gt;2&lt;/sub&gt;, …, Z&lt;sub&gt;T&lt;/sub&gt;&lt;/em&gt; each 20 milliseconds. Its architecture is simple: a 7-layer convolutional neural network (single-dimensional) with 512 channels at each layer.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_feature_encoder.png&quot; alt=&quot;Wav2vec 2.0 Latent Feature Encoder&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The waveform is normalized before being sent to the network, and the kernel width and strides of the convolutional layers decrease as we get higher in the network. The feature encoder has a total receptive field of 400 samples or 25 ms of audio (audio data is encoded at a sample rate of 16 kHz).&lt;/p&gt;

&lt;h2 id=&quot;quantization-module&quot;&gt;Quantization module&lt;/h2&gt;

&lt;p&gt;One of the main obstacles of using Transformers for speech processing is the &lt;strong&gt;continuous nature of speech&lt;/strong&gt;. Written language can be naturally discretized into words or sub-words, therefore creating a finite vocabulary of discrete units. Speech doesn’t have such natural sub-units. We could use phones as a discrete system, but then we would need humans to first label the entire dataset beforehand, so we wouldn’t be able to pre-train on unlabeled data.&lt;/p&gt;

&lt;p&gt;Wav2vec 2.0 proposes to &lt;strong&gt;automatically learn discrete speech units&lt;/strong&gt;, by sampling from the &lt;a href=&quot;https://paperswithcode.com/method/gumbel-softmax&quot;&gt;Gumbel-Softmax distribution&lt;/a&gt;. Possible units are made of &lt;em&gt;codewords&lt;/em&gt; sampled from &lt;em&gt;codebooks&lt;/em&gt; (groups). &lt;em&gt;Codewords&lt;/em&gt; are then concatenated to form the final speech unit. Wav2vec uses 2 groups with 320 possible words in each group, hence a theoretical maximum of 320 x 320 = 102,400 speech units.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_quantization_module.png&quot; alt=&quot;Wav2vec 2.0 Quantization Module&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The latent features are multiplied by the &lt;em&gt;quantization matrix&lt;/em&gt; to give the logits: one score for each of the possible &lt;em&gt;codewords&lt;/em&gt; in each &lt;em&gt;codebook&lt;/em&gt;. The Gumbel-Softmax trick allows sampling a single codeword from each codebook, after converting these logits into probabilities. It is similar to taking the &lt;a href=&quot;https://en.wikipedia.org/wiki/Arg_max&quot;&gt;argmax&lt;/a&gt; except that the operation is fully differentiable. Moreover, a small randomness effect, whose effect is controlled by a temperature argument, is introduced to the sampling process to facilitate training and codewords utilization.&lt;/p&gt;

&lt;h2 id=&quot;context-network&quot;&gt;Context network&lt;/h2&gt;

&lt;p&gt;The core of wav2vec 2.0 is its Transformer encoder, which takes as input the latent feature vectors and processes it through 12 Transformer blocks for the &lt;em&gt;BASE&lt;/em&gt; version of the model, or 24 blocks for the &lt;em&gt;LARGE&lt;/em&gt; version. To match the inner dimension of the Transformer encoder, the input sequence first needs to go through a feature projection layer to increase the dimension from 512 (output of the CNN) to 768 for &lt;em&gt;BASE&lt;/em&gt; or 1,024 for &lt;em&gt;LARGE&lt;/em&gt;. I will not describe further the Transformer architecture here and invite you to read &lt;a href=&quot;https://jalammar.github.io/illustrated-transformer/&quot;&gt;The Illustrated Transformer&lt;/a&gt; if you forgot the details.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_context_network_transformer.png&quot; alt=&quot;Wav2vec 2.0 Transformer Context Network&quot; /&gt;&lt;/p&gt;

&lt;p&gt;One difference from the original Transformer architecture is how positional information is added to the input. Since the self-attention operation of the Transformer doesn’t preserve the order of the input sequence, fixed pre-generated positional embeddings were added to the input vectors in the original implementation. The wav2vec model instead uses a new &lt;a href=&quot;https://paperswithcode.com/method/grouped-convolution&quot;&gt;grouped convolution layer&lt;/a&gt; to learn relative positional embeddings by itself.&lt;/p&gt;

&lt;h2 id=&quot;pre-training--contrastive-loss&quot;&gt;Pre-training &amp;amp; contrastive loss&lt;/h2&gt;

&lt;p&gt;The pre-training process uses a contrastive task to train on unlabeled speech data. A mask is first randomly applied in the latent space, where ~50% of the projected latent feature vectors. Masked positions are then replaced by the same trained vector &lt;em&gt;Z’&lt;sub&gt;M&lt;/sub&gt;&lt;/em&gt; before being fed to the Transformer network.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec2_contrastive_loss.png&quot; alt=&quot;Wav2vec 2.0 Contrastive Loss&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The final context vectors then go through the last projection layer to match the dimension of the quantized speech units &lt;em&gt;Q&lt;sub&gt;t&lt;/sub&gt;&lt;/em&gt;. For each masked position, &lt;strong&gt;100 negative distractors are uniformly sampled from other positions in the same sentence&lt;/strong&gt;. The model then compares the similarity (&lt;a href=&quot;https://en.wikipedia.org/wiki/Cosine_similarity&quot;&gt;cosine similarity&lt;/a&gt;) between the projected context vector &lt;em&gt;C’&lt;sub&gt;t&lt;/sub&gt;&lt;/em&gt; and the true positive target &lt;em&gt;Q&lt;sub&gt;p&lt;/sub&gt;&lt;/em&gt; along with all negative distractors &lt;em&gt;Q&lt;sub&gt;ñ&lt;/sub&gt;&lt;/em&gt;. The contrastive loss then encourages high similarity with the true positive target and penalizes high similarity scores with negative distractors.&lt;/p&gt;

&lt;h3 id=&quot;diversity-loss&quot;&gt;Diversity loss&lt;/h3&gt;

&lt;p&gt;During pre-training, another loss is added to the contrastive loss to encourage the model to use all codewords equally often. This works by maximizing the &lt;a href=&quot;https://en.wikipedia.org/wiki/Entropy_(information_theory)&quot;&gt;entropy&lt;/a&gt; of the Gumbel-Softmax distribution, preventing the model to always choose from a small sub-group of all available codebook entries. You can find more details in the &lt;a href=&quot;https://proceedings.neurips.cc/paper/2020/hash/92d1e1eb1cd6f9fba3227870bb6d7f07-Abstract.html&quot;&gt;original paper&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;This concludes our tour of wav2vec 2.0 and its pre-training process. The resulting pre-trained model can be used for a variety of speech downstream tasks: automatic speech recognition, &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;emotion detection&lt;/a&gt;, speaker recognition, language detection… In the original paper, the authors directly fine-tuned the model for speech recognition with a &lt;a href=&quot;https://distill.pub/2017/ctc/&quot;&gt;CTC loss&lt;/a&gt;, adding a linear projection on top of the context network to predict a word token at each timestep.&lt;/p&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/2021/10/30/hubert-visually-explained.html&quot;&gt;HuBERT: How to Apply BERT to Speech, Visually Explained&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2021/06/29/illustrated-wav2vec.html&quot;&gt;The Illustrated Wav2vec 1.0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;The Rise of Self-Supervised Learning&lt;/a&gt;&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Transformer-based neural networks have been revolutionizing the natural language processing field, but are only starting to become popular in the speech processing community. Wav2vec 2.0 is set to change that. Its architecture is based on the Transformer’s encoder, with a training objective similar to BERT’s masked language modeling objective, but adapted for speech.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://jonathanbgn.com/assets/images/illustrated-wav2vec/wav2vec2_architecture_pretraining.png" /><media:content medium="image" url="https://jonathanbgn.com/assets/images/illustrated-wav2vec/wav2vec2_architecture_pretraining.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Simple Audio Augmentation with PyTorch</title><link href="https://jonathanbgn.com/2021/08/30/audio-augmentation.html" rel="alternate" type="text/html" title="Simple Audio Augmentation with PyTorch" /><published>2021-08-30T12:00:00+00:00</published><updated>2021-08-30T12:00:00+00:00</updated><id>https://jonathanbgn.com/2021/08/30/audio-augmentation</id><content type="html" xml:base="https://jonathanbgn.com/2021/08/30/audio-augmentation.html">&lt;p&gt;No matter if you are training a model for automatic speech recognition or something more esoteric like &lt;a href=&quot;https://www.kaggle.com/c/birdsong-recognition&quot;&gt;recognizing birds from sound&lt;/a&gt;, you could benefit a lot from audio data augmentation. The idea is simple: &lt;strong&gt;by applying random transformations to your training examples, you can generate new examples for free and make your training dataset bigger.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In computer vision, for example, images can be randomly cropped, rotated… colors can be distorted, and so on. Of course, transformations should not be so destructive as to change the label of the example. If the label for one image is ‘dog’, the resulting image after transformations should still display a recognizable dog (you don’t want a picture of a pink tail).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/audio-augmentation/butterfly_augmentation.png&quot; alt=&quot;Data augmentation examples for an image&quot; style=&quot;max-width: 80%; margin: auto; display: block;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Data augmentation for images (&lt;a href=&quot;https://www.researchgate.net/publication/319413978_Data_augmentation-assisted_deep_learning_of_hand-drawn_partially_colored_sketches_for_visual_search&quot;&gt;Source&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Augmenting your dataset can often provide much more benefits than just tweaking your model architecture or hyperparameters. Andrej Karpathy, Tesla’s AI chief, goes so far as calling &lt;a href=&quot;http://karpathy.github.io/2019/04/25/recipe/#4-regularize&quot;&gt;data augmentation the best thing you can do to prevent overfitting&lt;/a&gt; (excluding getting new real data), before other regularization techniques such as dropout, weight decay, early stopping…&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;three-easy-to-apply-audio-transformations&quot;&gt;Three easy-to-apply audio transformations&lt;/h2&gt;

&lt;p&gt;Data augmentation does not have to be difficult, and from my own experience, the simplest techniques usually work better (on top of being easier to debug). In this tutorial, we will use PyTorch’s &lt;a href=&quot;https://pytorch.org/audio/stable/index.html&quot;&gt;torchaudio&lt;/a&gt; library to implement some of these techniques in only a few lines of code.&lt;/p&gt;

&lt;p&gt;For demo purposes, we will use a ~30s speech sample downloaded from the &lt;a href=&quot;http://www.voiptroubleshooter.com/open_speech/&quot;&gt;Open Speech Repository&lt;/a&gt;. First, let’s load the audio data along with the sample rate of the recording:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torchaudio&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchaudio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;load&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'OSR_us_000_0010_8k.wav'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/audio-augmentation/original.png&quot; alt=&quot;Sample audio waveform&quot; /&gt;&lt;/p&gt;

&lt;audio controls=&quot;&quot; style=&quot;margin: auto; display: block; margin-bottom: 30px;&quot;&gt;
 &lt;source src=&quot;/assets/audio/OSR_us_000_0010_8k.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;h3 id=&quot;1-random-clipping&quot;&gt;1. Random clipping&lt;/h3&gt;

&lt;p&gt;A very simple yet effective technique I use whenever training audio/speech models is taking a random segment of the audio clip. Not only this makes the model much more robust to time-shifting, it is also a neat way to batch audio files with different durations and prevent the use of padding which can create its own problems. If you don’t care about having the same length for each audio file, you could also apply PyTorch’s included Voice Activity Detector to trim silences at the beginning and end of the clipped segment.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torchaudio&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RandomClip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchaudio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Vad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trigger_level&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clip_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# remove silences at the beggining/end
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;clip_transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;RandomClip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# 8 seconds clip
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/audio-augmentation/clipped.png&quot; alt=&quot;Random clipping&quot; /&gt;&lt;/p&gt;

&lt;audio controls=&quot;&quot; style=&quot;margin: auto; display: block; margin-bottom: 30px;&quot;&gt;
 &lt;source src=&quot;/assets/audio/clipped.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;p&gt;Of course, you should make sure that clipping the audio won’t change the label. For tasks like speaker or language identification, this should not be a problem. But if you are training a speech recognition system, for instance, make sure that you also clip the transcription accordingly to preserve the integrity of the data.&lt;/p&gt;

&lt;h3 id=&quot;2-speed-perturbation&quot;&gt;2. Speed perturbation&lt;/h3&gt;

&lt;p&gt;Torchaudio lets you apply all sorts of effects on audio such as changing the pitch, applying low/high pass filter, adding reverberation, and so on (&lt;a href=&quot;http://sox.sourceforge.net/sox.html&quot;&gt;full list here&lt;/a&gt;). One particularly effective technique for speech-based applications, however, is to just change the speed of the audio signal.&lt;/p&gt;

&lt;p&gt;Indeed, it has been shown that producing two augmented versions of the original dataset with speed factors of 0.9 and 1.1 could &lt;a href=&quot;https://danielpovey.com/files/2015_interspeech_augmentation.pdf&quot;&gt;significantly improve speech recognition&lt;/a&gt;, more than other more complicated methods based on vocal tract lengths.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RandomSpeedChange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;speed_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;speed_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# no change
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# change speed and resample to original rate:
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sox_effects&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;speed&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;speed_factor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;rate&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchaudio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sox_effects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;apply_effects_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sox_effects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt;
 
&lt;span class=&quot;n&quot;&gt;speed_transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;RandomSpeedChange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;speed_transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The following is the original audio file with speed increased by a factor of 1.1.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/audio-augmentation/faster.png&quot; alt=&quot;Speed increased by x1.1&quot; /&gt;&lt;/p&gt;

&lt;audio controls=&quot;&quot; style=&quot;margin: auto; display: block; margin-bottom: 30px;&quot;&gt;
 &lt;source src=&quot;/assets/audio/faster.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;h3 id=&quot;3-background-noise&quot;&gt;3. Background noise&lt;/h3&gt;

&lt;p&gt;We could just add auto-generated noises like &lt;a href=&quot;https://en.wikipedia.org/wiki/White_noise&quot;&gt;white noise&lt;/a&gt; in the background, but adding real noises and sounds can increase a lot the robustness of models. Especially important is to have a large enough library of noises so that the model very rarely sees the same noise twice during training. Fortunately, there exists tons of free sound databases online. I strongly recommend &lt;a href=&quot;http://www.openslr.org/17/&quot;&gt;MUSAN&lt;/a&gt;, a large 11GB collection of music, speech, and noise recordings.&lt;/p&gt;

&lt;p&gt;The following transform will pick a random noise file from a given folder and will apply it to the original audio file. For added diversity, it will also choose a random &lt;a href=&quot;https://en.wikipedia.org/wiki/Signal-to-noise_ratio&quot;&gt;signal-to-noise ratio&lt;/a&gt; (from a given range) to apply noises at a different volume compared to the original signal.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;os&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pathlib&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torch&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RandomBackgroundNoise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_dir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_snr_db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_snr_db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_snr_db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_snr_db&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_snr_db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_snr_db&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;os&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exists&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_dir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;raise&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;IOError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Noise directory `&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_dir&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;` does not exist'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# find all WAV files including in sub-folders:
&lt;/span&gt;        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_files_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pathlib&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_dir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;glob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'**/*.wav'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_files_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;raise&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;IOError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'No .wav file found in the noise directory `&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_dir&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;`'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;random_noise_file&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_files_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;effects&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'remix'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'1'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# convert to mono
&lt;/span&gt;            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'rate'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# resample
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchaudio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sox_effects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;apply_effects_file&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_noise_file&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;effects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;normalize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;noise_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[...,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;snr_db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_snr_db&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_snr_db&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;snr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;snr_db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;audio_power&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;noise_power&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;snr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_power&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_power&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
 
&lt;span class=&quot;n&quot;&gt;noise_transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;RandomBackgroundNoise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'./noises_directory'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The following audio example is the original file with a randomly added sound of a crowd in the background.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/audio-augmentation/background_noise.png&quot; alt=&quot;Crowd noise in the background&quot; /&gt;&lt;/p&gt;

&lt;audio controls=&quot;&quot; style=&quot;margin: auto; display: block; margin-bottom: 30px;&quot;&gt;
 &lt;source src=&quot;/assets/audio/background_noise.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;combine-transformations&quot;&gt;Combine transformations&lt;/h2&gt;

&lt;p&gt;The beauty of PyTorch’s transforms design pattern is that you can easily combine them. From this simple set of three transformations, we could generate an infinite number of diverse-enough examples by applying transformations on the fly during training.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ComposeTransform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;compose_transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ComposeTransform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RandomClip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequence_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RandomSpeedChange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RandomBackgroundNoise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'./noises_directory'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;transformed_audio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compose_transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;audio_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The following audio examples were all generated from the same original audio file.&lt;/p&gt;

&lt;audio controls=&quot;&quot;&gt;
 &lt;source src=&quot;/assets/audio/composed1.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;audio controls=&quot;&quot;&gt;
 &lt;source src=&quot;/assets/audio/composed2.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;audio controls=&quot;&quot;&gt;
 &lt;source src=&quot;/assets/audio/composed3.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;audio controls=&quot;&quot;&gt;
 &lt;source src=&quot;/assets/audio/composed4.wav&quot; type=&quot;audio/mpeg&quot; /&gt;
 Your browser does not support the audio element.
&lt;/audio&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;more-advanced-augmentation&quot;&gt;More advanced augmentation&lt;/h2&gt;

&lt;p&gt;In my experience, these simple techniques should already bring you quite far. If you want to go further, there exists &lt;a href=&quot;https://github.com/iver56/audiomentations&quot;&gt;external&lt;/a&gt; &lt;a href=&quot;https://github.com/asteroid-team/torch-audiomentations&quot;&gt;libraries&lt;/a&gt; to apply more sophisticated effects, although they might not translate into better model performance and generalization. The official &lt;a href=&quot;https://pytorch.org/tutorials/beginner/audio_preprocessing_tutorial.html#simulating-room-reverbration&quot;&gt;torchaudio tutorial&lt;/a&gt; also describes an interesting method to apply room reverberation from a dataset of &lt;a href=&quot;https://www.openslr.org/28/&quot;&gt;room impulse responses&lt;/a&gt; (someone clapping hands in an empty room). Keep in mind that you need clean audio recording for this to work properly.&lt;/p&gt;

&lt;p&gt;It is also possible to apply data augmentation techniques directly on the features computed from the audio, rather than on the raw audio itself. &lt;a href=&quot;https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html&quot;&gt;SpecAugment&lt;/a&gt; for example apply transformations directly on the spectrogram of the audio signal, such as time or frequency masking. Torchaudio also comes with a convenient &lt;a href=&quot;https://pytorch.org/tutorials/beginner/audio_preprocessing_tutorial.html#specaugment&quot;&gt;SpecAugment implementation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The future is bright! As the field of machine learning is moving more and more towards a &lt;a href=&quot;https://www.deeplearning.ai/wp-content/uploads/2021/06/MLOps-From-Model-centric-to-Data-centric-AI.pdf&quot;&gt;data-centric approach&lt;/a&gt; rather than model-centric, new techniques and resources will likely appear in the near future to help with setting up better and faster data augmentation pipelines.&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">No matter if you are training a model for automatic speech recognition or something more esoteric like recognizing birds from sound, you could benefit a lot from audio data augmentation. The idea is simple: by applying random transformations to your training examples, you can generate new examples for free and make your training dataset bigger.</summary></entry><entry><title type="html">Detecting Depression with Machine Learning: The Why and the How</title><link href="https://jonathanbgn.com/2021/07/30/depression-detection-machine-learning.html" rel="alternate" type="text/html" title="Detecting Depression with Machine Learning: The Why and the How" /><published>2021-07-30T08:00:00+00:00</published><updated>2021-07-30T08:00:00+00:00</updated><id>https://jonathanbgn.com/2021/07/30/depression-detection-machine-learning</id><content type="html" xml:base="https://jonathanbgn.com/2021/07/30/depression-detection-machine-learning.html">&lt;p&gt;Over the past decade, there has been tremendous progress in using artificial intelligence to better understand people. From natural language understanding to &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;recognizing people’s emotions&lt;/a&gt;, deep learning has enabled a whole new set of applications that will profoundly change the way we interact with machines.&lt;/p&gt;

&lt;p&gt;One of the most promising applications is in mental health, where machine learning could provide great value to both doctors and patients. Especially a lot of attention has been given to automatic depression detection, and how to use machine learning to help with screening, diagnosis, and monitoring. In this post, I’d like to give an overview of what’s being done and the benefits of a more automated approach.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-rising-burden-of-depression-worldwide&quot;&gt;The rising burden of depression worldwide&lt;/h2&gt;

&lt;p&gt;Cases of depression increased by nearly a fifth during 2005-15. It is estimated that around 15% of people worldwide experience depression at some point in their lifetime. The &lt;a href=&quot;https://en.wikipedia.org/wiki/Global_Burden_of_Disease_Study&quot;&gt;Global Burden of Disease Study&lt;/a&gt;, which compares the number of years lost due to ill-health, disability, or early death between 369 diseases worldwide, found that years lost due to depressive disorders increased more than 60% between 1990 and 2019. This sets depression as the &lt;a href=&quot;https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(20)30925-9/fulltext&quot;&gt;6th most burdensome disorder&lt;/a&gt; for adults aged 25-49, before strokes or diabetes.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/covid_depression_nature.png&quot; alt=&quot;Covid and depression&quot; width=&quot;400&quot; style=&quot;max-width: 100%; margin: auto; display: block&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Image credit: &lt;a href=&quot;https://www.nature.com/articles/d41586-021-00175-z&quot;&gt;COVID’s mental-health toll: how scientists are tracking a surge in depression&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The Covid 19 pandemic has only made the problem more urgent. Depression and anxiety issues are surging worldwide since the beginning of the pandemic, and researchers are increasingly worried about the long-term effects of Covid on mental health.&lt;/p&gt;

&lt;h2 id=&quot;how-can-doctors-tell-if-you-are-depressed&quot;&gt;How can doctors tell if you are depressed?&lt;/h2&gt;

&lt;p&gt;The biggest problem for diagnosing depression is the &lt;strong&gt;lack of any objective laboratory test&lt;/strong&gt;, unlike other medical branches. For example, if a doctor suspects a case of diabetes, a simple blood test to measure glucose content can be done. There is no such thing for detecting depression, so psychiatrists have to rely on their own judgment and recognizing patterns of symptoms.&lt;/p&gt;

&lt;p&gt;The confusion and disagreement around the differences between mental health diseases are also not helping the task. There is a large overlap of symptoms between depression and other mental health conditions. Less intense but persistent forms of depression, like &lt;a href=&quot;https://en.wikipedia.org/wiki/Dysthymia&quot;&gt;dysthymia&lt;/a&gt;, are also classified separately. This complexity has led to intense efforts to improve the reliability of depression diagnosis: that is doctors should all make the same judgment for patients with the same set of symptoms.&lt;/p&gt;

&lt;h3 id=&quot;dsm-5-the-bible-of-psychiatrists&quot;&gt;DSM-5, the bible of psychiatrists&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/DSM-5.jpg&quot; alt=&quot;DSM-5 book cover. Source: American Psychiatric Association&quot; width=&quot;300&quot; style=&quot;max-width: 50%; float: left; margin-right: 20px;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;One of the most popular systems to standardize the classification of mental health conditions like &lt;em&gt;major depressive disorder&lt;/em&gt; is the &lt;a href=&quot;https://en.wikipedia.org/wiki/Diagnostic_and_Statistical_Manual_of_Mental_Disorders#DSM-5_(2013)&quot;&gt;Diagnostic and Statistical Manual of Mental Disorders&lt;/a&gt;, which also goes by its nickname the DSM.&lt;/p&gt;

&lt;p&gt;In the latest 5th edition of the DSM, an individual should be diagnosed as depressed if he/she is experiencing five or more of the following symptoms during at least a 2-week period&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;ol&gt;
    &lt;li&gt;Depressed mood most of the day, nearly every day.&lt;/li&gt;
    &lt;li&gt;Markedly diminished interest or pleasure in all, or almost all, activities most of the day, nearly every day.&lt;/li&gt;
    &lt;li&gt;Significant weight loss when not dieting or weight gain, or decrease or increase in appetite nearly every day.&lt;/li&gt;
    &lt;li&gt;A slowing down of thought and a reduction of physical movement (observable by others, not merely subjective feelings of restlessness or being slowed down).&lt;/li&gt;
    &lt;li&gt;Fatigue or loss of energy nearly every day.&lt;/li&gt;
    &lt;li&gt;Feelings of worthlessness or excessive or inappropriate guilt nearly every day.&lt;/li&gt;
    &lt;li&gt;Diminished ability to think or concentrate, or indecisiveness, nearly every day.&lt;/li&gt;
    &lt;li&gt;Recurrent thoughts of death, recurrent suicidal ideation without a specific plan, or a suicide attempt or a specific plan for committing suicide.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;The DSM has been overly criticized for its rigidity and sometimes arbitrary choices (why should five symptoms be enough and not four or six?). Diagnosis criteria have been updated over time, but changes are not always welcome. For example, there have been concerns that the latest edition of the DSM now &lt;a href=&quot;https://www.psychologytoday.com/intl/blog/dsm5-in-distress/201212/dsm-5-is-guide-not-bible-ignore-its-ten-worst-changes&quot;&gt;classifies normal “grief” as major depression&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;assessing-depression-severity&quot;&gt;Assessing depression severity&lt;/h3&gt;

&lt;p&gt;To assist doctors in the diagnosis and monitoring of their patients, a variety of tests and questionnaires have also been developed. Some need to be conducted by a doctor, who questions the patient to observe and rate eventual symptoms, but others can be self-performed by the patients themselves. The outcome of such tests is a final score that classifies the patient into different categories such as &lt;em&gt;no depression&lt;/em&gt;, &lt;em&gt;mild depression&lt;/em&gt;, or &lt;em&gt;severe depression&lt;/em&gt;. The gold standard of such assessment tools is the &lt;a href=&quot;https://en.wikipedia.org/wiki/Hamilton_Rating_Scale_for_Depression&quot;&gt;Hamilton Rating Scale for Depression (HAMD)&lt;/a&gt;, but many more exist and are used in different situations.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/phq-9_scoring.png&quot; alt=&quot;PHQ-9 scoring&quot; width=&quot;600&quot; style=&quot;max-width: 100%; display: block; margin: auto;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A questionnaire worth mentioning is the &lt;a href=&quot;https://en.wikipedia.org/wiki/PHQ-9&quot;&gt;PHQ-9 (Patient Health Questionnaire)&lt;/a&gt;. It is often used for labeling datasets before training machine learning models, mostly because of its simplicity: it consists of only 9 questions about the loss of appetite, energy, sleeping trouble, etc. for which patients can answer from “Not at all” to “Nearly every day”. Patients can self-conduct the questionnaire in less than 3 minutes. This convenience makes it an ideal choice for regular testing over long periods.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;why-automatic-depression-detection-is-a-good-idea&quot;&gt;Why automatic depression detection is a good idea&lt;/h2&gt;

&lt;h3 id=&quot;the-diagnosis-process-is-unreliable&quot;&gt;The diagnosis process is unreliable&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/prozac_ad.jpg&quot; alt=&quot;Prozac advertisement&quot; width=&quot;300&quot; style=&quot;max-width: 50%; float: right; margin-left: 20px;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Despite the standardization efforts mentioned above, health care professionals still don’t agree on the exact requirements and threshold for depression. A &lt;a href=&quot;https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(09)60879-5/fulltext&quot;&gt;meta-analysis across 41 studies&lt;/a&gt; found that &lt;strong&gt;general practitioners are only able to identify depression in 47% of cases&lt;/strong&gt;. Even experienced psychiatrists and psychologists often come up with &lt;strong&gt;different diagnoses for the same patients, &lt;a href=&quot;https://onlinelibrary.wiley.com/doi/10.1002/cpp.693&quot;&gt;in more than 30% of cases&lt;/a&gt;&lt;/strong&gt;. Interestingly, there are about the same number of research papers claiming that depression is over-diagnosed as claiming it is under-diagnosed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;There are important consequences to a wrong diagnosis for treatment.&lt;/strong&gt; The World Health Organization stated that a major barrier to effective care is inaccurate assessment: in countries of all income levels, people who are depressed are often not correctly diagnosed, and others who do not have the disorder are too often misdiagnosed and prescribed drugs. In the US, antidepressants are now the &lt;a href=&quot;https://www.health.harvard.edu/blog/astounding-increase-in-antidepressant-use-by-americans-201110203624&quot;&gt;3rd most common prescription medication&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;doctors-want-better-tools&quot;&gt;Doctors want better tools&lt;/h3&gt;

&lt;p&gt;An extensive study by Google has shown that &lt;a href=&quot;https://blog.x.company/sharing-project-amber-with-the-mental-health-community-7b6d8814a862&quot;&gt;many psychiatrists don’t use current diagnostic tools&lt;/a&gt;, often perceived as too burdensome or not reliable enough. More accurate tools are needed, which should be focused on assisting psychiatrists in their decision-making rather than trying to replace humans in the diagnosis process. The combination of subjective and automated assessments will lead to the most benefits.&lt;/p&gt;

&lt;h3 id=&quot;mental-health-needs-a-more-personalized-approach&quot;&gt;Mental health needs a more personalized approach&lt;/h3&gt;

&lt;p&gt;The current diagnosis process is strongly dependent on a &lt;strong&gt;single point in time&lt;/strong&gt; when the doctor interviews the patient. This can overestimate or underestimate the severity of depression depending on the mood swing of the individual. More meaningful monitoring along longer periods will help set up a personalized “normal baseline” for each individual and detect sudden variations in time.&lt;/p&gt;

&lt;h3 id=&quot;most-sufferers-dont-get-any-kind-of-help&quot;&gt;Most sufferers don’t get any kind of help&lt;/h3&gt;

&lt;p&gt;Between &lt;a href=&quot;https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(07)61414-7/fulltext&quot;&gt;76% and 85%&lt;/a&gt; of depressed people in low- and middle-income countries receive no treatment for their disorder, mostly due to a lack of resources and trained doctors. Machine learning-based approaches could help to scale diagnosis and monitoring solutions to a much larger population worldwide, especially in countries with lower resources.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Social stigma is also stopping people from seeking help.&lt;/strong&gt; 92% of people believe that admitting mental health problems such as depression would damage their career, according to a survey in the United Kingdom. Much too often depressed individuals believe that their condition is the result of personal deficiencies such as “being too weak”, rather than seeing it as a chemical imbalance problem that is out of their control. Such beliefs prevent people from speaking up. This phenomenon is even worst in some parts of Asia where culture tends to put blame on individuals failing to fulfill their role in society.&lt;/p&gt;

&lt;p&gt;Using technology could be a less intimidating first step for many of the people who suffer from depression, helping them to put a word on their trouble and pointing them to potential solutions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;current-approaches-in-machine-learning&quot;&gt;Current approaches in machine learning&lt;/h2&gt;

&lt;h3 id=&quot;electroencephalography&quot;&gt;Electroencephalography&lt;/h3&gt;

&lt;p&gt;EEG or Electroencephalography is used to record the electrical activity of the brain via electrodes placed along the scalp. Already used today to diagnose epilepsy and memory/sleep disorders, it has been a natural candidate to find an objective marker for depression. This is exactly what one of Google X’s moonshot projects decided to do. &lt;a href=&quot;https://blog.x.company/sharing-project-amber-with-the-mental-health-community-7b6d8814a862&quot;&gt;Project Amber&lt;/a&gt;, as it was called, developed a prototype that was as easy to use as possible for medical practitioners.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/project_amber.jpg&quot; alt=&quot;Project Amber’s final EEG prototype&quot; width=&quot;300&quot; style=&quot;max-width: 50%; float: right; margin-left: 20px;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The main challenge when trying to make sense of electroencephalograms is to filter out the noise and extract relevant signals. Project Amber’s team collaborated with DeepMind to solve this problem via unsupervised representation learning, a machine learning technique that tries to extract the most “meaningful” bits of information in the signal by training on large quantities of unlabeled data.&lt;/p&gt;

&lt;p&gt;Unfortunately Project Amber did not succeed in finding a reliable single marker for depression and was shut down in 2020. However, the project’s team still believes in the potential of the technology, and has &lt;a href=&quot;https://github.com/google/x-amber&quot;&gt;open-sourced their hardware design and software&lt;/a&gt; in the hope that others build on top of their work.&lt;/p&gt;

&lt;h3 id=&quot;social-media-and-linguistics&quot;&gt;Social media and linguistics&lt;/h3&gt;

&lt;p&gt;Another line of research has been to use behavioral and linguistics information from social networks like Twitter, Reddit, Facebook, Instagram, etc. Researchers have built algorithms that use everything from the content posted by the user to its activity/interactions (likes, shares, posting frequency), social network graphs, and demographics information.&lt;/p&gt;

&lt;p&gt;Reported results have been promising, but &lt;a href=&quot;https://www.nature.com/articles/s41746-020-0233-7&quot;&gt;concerns have been raised about the design of many studies&lt;/a&gt;, specifically about how users are classified as depressed or not before using the data to train algorithms.&lt;/p&gt;

&lt;h3 id=&quot;facial-expressions-and-body-language&quot;&gt;Facial expressions and body language&lt;/h3&gt;

&lt;p&gt;Computer vision has made tremendous progress over the past decade, and deep learning models are now able to recognize facial expressions (smiling, frowning, surprise, etc.) with a high level of accuracy. Such technology is being applied to recognize mental health issues like depression. For example, subjects are being shown emotional images (both positives and negatives) with their reaction being automatically analyzed. It has been shown that &lt;a href=&quot;https://journals.sagepub.com/doi/abs/10.2466/pms.2001.92.3.857&quot;&gt;depressed subjects present slower reactions to positive visual stimuli&lt;/a&gt;, which a neural network could potentially detect.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;speech-one-of-the-most-promising-avenues&quot;&gt;Speech: One of the most promising avenues&lt;/h2&gt;

&lt;p&gt;The idea that depression can be recognized through speech is not new. Back in 1921 &lt;a href=&quot;https://en.wikipedia.org/wiki/Emil_Kraepelin&quot;&gt;Emil Kraepalin&lt;/a&gt;, often regarded as the founder of modern psychiatry, described depressive voices as follow:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Patients speak in a low voice, slowly, hesitantly, monotonously, sometimes stuttering, whispering, try several times before they bring out a word, become mute in the middle of a sentence.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To understand why depression can affect speech, it is important to have a look at how speech is produced, particularly at the &lt;a href=&quot;https://en.wikipedia.org/wiki/Source–filter_model&quot;&gt;source-filter theory&lt;/a&gt; of speech production. According to this model, speech is a combination of a &lt;strong&gt;sound source (vocal cords)&lt;/strong&gt;, which is modulated by an &lt;strong&gt;acoustic filter (vocal tract)&lt;/strong&gt;. Because of the complexity of the vocal tract, speech is a very sensitive output system: a small change somewhere along the tract could lead to noticeable acoustic changes.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/source_filter.jpg&quot; alt=&quot;Vocal Tract&quot; width=&quot;400&quot; style=&quot;display: block; margin: auto;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href=&quot;https://slideplayer.com/slide/13616725/&quot;&gt;Image Credit&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In fact, &lt;strong&gt;speech production uses more motor fibers than any other human mechanical activity&lt;/strong&gt;. Cognitive issues experienced by depressed subjects have been shown to affect working memory, impacting speech planning and neuromuscular coordination processes. Moreover, changes to some parts of the nervous systems and the level of some neurotransmitters can create changes to muscle tensions and control, thus impacting the vocal cords and vocal tract.&lt;/p&gt;

&lt;h3 id=&quot;how-to-measure-depression-from-speech&quot;&gt;How to measure depression from speech&lt;/h3&gt;

&lt;p&gt;Research has shown strong correlations between many acoustic features and the speaker’s level of depression. Some of the most efficient features yet are called &lt;a href=&quot;https://en.wikipedia.org/wiki/Prosody_(linguistics)&quot;&gt;prosodic features&lt;/a&gt;, which represent variations in the perceived rhythm, stress, and intonation of speech. Such features have also been shown to work well in similar tasks like &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;emotion recognition&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The field of speech processing, however, (and also deep learning in general) is moving towards the use of raw audio waveforms directly, effectively letting neural networks decide which features are the most efficient for the job. These are exciting times, as new approaches are enabling training on large quantities of unlabeled data, improving many tasks including depression detection.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/depression/wavenet_architecture.png&quot; alt=&quot;Vocal Tract&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Speech processing is more and more working with raw audio directly as input (here processed by a dilated convolutional neural network). Image credit: &lt;a href=&quot;https://arxiv.org/pdf/1609.03499.pdf&quot;&gt;Wavenet model from DeepMind&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Speech can also be combined with linguistics features for better performance. A first automatic speech recognition model transcribes the audio to text, and a separate model is used to recognize statistical patterns of expressions from the text.&lt;/p&gt;

&lt;h3 id=&quot;current-state-of-speech-depression-detection&quot;&gt;Current state of speech depression detection&lt;/h3&gt;

&lt;p&gt;In 2016 the Audio-Visual Emotion Challenge organized a competition to detect depression from a &lt;a href=&quot;https://dcapswoz.ict.usc.edu&quot;&gt;dataset of recorded interviews&lt;/a&gt; from depressed and healthy individuals. One of the most performant models was able to successfully screen 100% of depressed patients from &lt;a href=&quot;https://dl.acm.org/doi/abs/10.1145/2988257.2988267&quot;&gt;segments of four seconds of speech&lt;/a&gt; (although the precision was only 35%, meaning that 65% of depression predictions were false positive). Two years later, on the same dataset, an MIT research team improved the &lt;a href=&quot;https://news.mit.edu/2018/neural-network-model-detect-depression-conversations-0830&quot;&gt;precision to 71% (recall 83%)&lt;/a&gt; by modeling the sequence of questions in the interview as well as combining speech features with linguistic features.&lt;/p&gt;

&lt;p&gt;Today, multiple companies claim to detect depression from speech with &lt;a href=&quot;https://www.forbes.com/sites/ganeskesari/2021/05/24/ai-can-now-detect-depression-from-just-your-voice/&quot;&gt;twice the accuracy of human practicioners&lt;/a&gt;, using as little as 20 seconds of voice data. Our team at &lt;a href=&quot;https://www.wondertech.ai&quot;&gt;WonderTech&lt;/a&gt; is currently working on pushing the state-of-the-art through new paradigms in machine learning such as transfer learning and self-supervised learning.&lt;/p&gt;

&lt;h3 id=&quot;the-benefits-of-the-speech-based-approach&quot;&gt;The benefits of the speech-based approach&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Speech can be measured cheaply and non-intrusively.&lt;/strong&gt; Every smartphone can be potentially used. Speech can be monitored naturally and there is no need to ask patients to fill a questionnaire or go through complicated EEG testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Speech can monitor changes compared to each individual’s own baseline.&lt;/strong&gt; As speech is so cheap to monitor, it can be done much more often and allow establishing a “normal” baseline personalized to the unique characteristics of the voices of different persons. Detecting deviation from baselines can then be much more informative than tests performed at a single point in time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Speech can help respect privacy.&lt;/strong&gt; With the improvement of computation for smartphones and wearables, deep learning models are increasingly moving on-device so that no data is sent to the cloud. Apple for example, just announced at this year’s WWDC that they would be handling requests to Siri directly on the iPhone, preventing any audio to leave the device.&lt;/p&gt;

&lt;h3 id=&quot;future-challenges&quot;&gt;Future challenges&lt;/h3&gt;

&lt;p&gt;The field is progressing rapidly but some challenges remain:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Small size of datasets.&lt;/strong&gt; The sensitivity of depression-related data makes it hard to collect a large quantity of high-quality data to train machine learning models. However, progress made in transfer learning and &lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;self-supervised learning&lt;/a&gt; can help mitigate the issues by making use of generic speech data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Model biases.&lt;/strong&gt; For example gender has been shown to have a big influence on models’ predictions. Final solutions also need to function in any kind of environment, and should not be influenced by audio recording conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Privacy.&lt;/strong&gt; Data should be processed on-device as much as possible and should be anonymized when training. Depression is and will remain a sensitive subject, and everything should be done to protect patient’s data.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;The Rise of Self-Supervised Learning&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/gpt2/2020/01/20/slogan-generator.html&quot;&gt;Building a Slogan Generator with GPT-2&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;footnotes&quot;&gt;Footnotes&lt;/h4&gt;

&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;One of the symptoms must be either 1) depressed mood or 2) loss of interest. Moreover, to receive a diagnosis of depression, these symptoms must cause the individual clinically significant distress or impairment in social, occupational, or other important areas of functioning. The symptoms must also not be a result of substance abuse or another medical condition. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Over the past decade, there has been tremendous progress in using artificial intelligence to better understand people. From natural language understanding to recognizing people’s emotions, deep learning has enabled a whole new set of applications that will profoundly change the way we interact with machines.</summary></entry><entry><title type="html">The Illustrated Wav2vec</title><link href="https://jonathanbgn.com/2021/06/29/illustrated-wav2vec.html" rel="alternate" type="text/html" title="The Illustrated Wav2vec" /><published>2021-06-29T08:00:00+00:00</published><updated>2021-06-29T08:00:00+00:00</updated><id>https://jonathanbgn.com/2021/06/29/illustrated-wav2vec</id><content type="html" xml:base="https://jonathanbgn.com/2021/06/29/illustrated-wav2vec.html">&lt;p&gt;Wav2vec is a speech encoder model released by the Facebook AI team in late 2019. It quickly became popular in the speech processing community as it enabled new state-of-the-art performance for various speech tasks like &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-state-of-the-art-speech-recognition-through-self-supervision/&quot;&gt;automatic speech recognition&lt;/a&gt; or &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;emotion recognition&lt;/a&gt;. Since its original version, the model has been upgraded to use the Transformers architecture (the same one behind GPT and BERT) and has been re-trained on &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-20-learning-the-structure-of-speech-from-raw-audio/&quot;&gt;12 different languages&lt;/a&gt; in a multilingual version.&lt;/p&gt;

&lt;p&gt;I haven’t seen resources digging into the internals of the model, so I decided to write this short illustrated tour, inspired by the excellent &lt;a href=&quot;https://jalammar.github.io/illustrated-gpt2/&quot;&gt;Illustrated GPT article&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;like-gpt-but-for-speech&quot;&gt;Like GPT, but for speech&lt;/h2&gt;

&lt;p&gt;Wav2vec is a big deal because it is one of the most promising attempts so far to apply &lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;self-supervised learning&lt;/a&gt; to the field of speech processing. It has the potential to change best practices in the field, just like GPT and BERT changed the field of natural language processing.&lt;/p&gt;

&lt;p&gt;Similar to GPT-2 or GPT-3 for text, wav2vec is trying to &lt;strong&gt;predict the future of an audio sequence&lt;/strong&gt;, although through a different approach. Despite technical differences, the purpose of both models is identical. First, pre-train a large network on unlabeled data to learn useful contextual representations of the text/audio sequence. Second, use these pre-trained representations for a variety of tasks for which not enough data is available.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec_waveform.png&quot; alt=&quot;Wav2vec&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-state-of-the-art-speech-recognition-through-self-supervision/&quot;&gt;Facebook AI Blog&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There are however challenges to model the future of audio sequences compared to text. Audio data has a much higher dimension than text (text has a finite vocabulary), so directly modeling the waveform signal is much harder. Instead, wav2vec first reduces the dimensionality of the speech data by encoding it into a latent space, and then &lt;em&gt;predicting the future in this latent space&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Let’s open the hood and look at the model architecture to see how this is done.&lt;/p&gt;

&lt;h2 id=&quot;dual-model-architecture-encoder--context-network&quot;&gt;Dual model architecture: encoder &amp;amp; context network&lt;/h2&gt;

&lt;p&gt;At the core of wav2vec are two distinct networks: the encoder network and the context network. Both are convolutional neural networks, albeit with different settings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The encoder network&lt;/strong&gt; reduces the dimensionality of the speech data, by encoding 30 milliseconds of audio into a 512-dimensional feature vector &lt;strong&gt;z&lt;sub&gt;t&lt;/sub&gt;&lt;/strong&gt; at each timestep &lt;em&gt;t&lt;/em&gt;, every 10 ms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The context network&lt;/strong&gt; takes as input the encoder output features, encoding 210 ms of raw audio into another 512-dimensional feature vector &lt;strong&gt;c&lt;sub&gt;t&lt;/sub&gt;&lt;/strong&gt;. The objective is to aggregate information over a longer timeframe to model higher-order information. This network outputs &lt;em&gt;contextual representations c&lt;sub&gt;t&lt;/sub&gt;&lt;/em&gt; that are used to predict future audio samples.&lt;/p&gt;

&lt;p&gt;An important detail is the &lt;em&gt;causal&lt;/em&gt; nature of these convolutional networks. Wav2vec should not “peek” into the future when predicting future samples, hence the convolutional layers are structured in a way that each output at time &lt;em&gt;t&lt;/em&gt; never attends to positions after &lt;em&gt;t&lt;/em&gt;. In practice, this is done through left-padding the input as shown in the diagram below.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/model_architecture.png&quot; alt=&quot;Model Architecture&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;maximizing-mutual-information&quot;&gt;Maximizing mutual information&lt;/h2&gt;

&lt;p&gt;The idea behind wav2vec training is called &lt;a href=&quot;https://arxiv.org/abs/1807.03748&quot;&gt;contrastive predictive coding&lt;/a&gt;. Instead of trying to predict directly the future like GPT and model precisely the audio waveform, wav2vec uses a contrastive loss that implicitly models the mutual information between the context and future audio samples.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Mutual_information&quot;&gt;Mutual information&lt;/a&gt; is a concept coming from information theory which indicates &lt;strong&gt;how much information is gained about a given random variable when we observe another random variable&lt;/strong&gt;. If the mutual information is 0, the two variables are independent. If it is 1, then knowing about one variable will tell us everything we need to know about the other.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/mutual_information.png&quot; alt=&quot;Mutual Information&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Wav2vec’s loss has been designed to implicitly maximize the mutual information between the context features and future audio samples. Doing so will push the model to learn useful contextual features which contain higher-order information about the audio signal.&lt;/p&gt;

&lt;p&gt;If you want to know more about how wav2vec loss implicitly maximizes the mutual information, you can have a look at the &lt;a href=&quot;https://arxiv.org/abs/1807.03748&quot;&gt;contrastive predictive coding paper&lt;/a&gt;. This &lt;a href=&quot;https://slideslive.com/38938406/the-infonce-loss-in-selfsupervised-learning&quot;&gt;talk at NeurIPS&lt;/a&gt; by one of the authors also gives the intuition behind the concept.&lt;/p&gt;

&lt;p&gt;Let’s now see how this loss objective is implemented in practice.&lt;/p&gt;

&lt;h2 id=&quot;training-objective&quot;&gt;Training objective&lt;/h2&gt;

&lt;p&gt;The model is trained to &lt;strong&gt;distinguish true future audio samples from fake distractor samples by using the context vector&lt;/strong&gt;. Here “audio samples” actually mean the encoder feature vectors &lt;strong&gt;z&lt;sub&gt;i&lt;/sub&gt;&lt;/strong&gt;. Remember that we are not working with the waveform directly because the dimensionality would be too high. &lt;strong&gt;This prediction process is done &lt;em&gt;k&lt;/em&gt; times at each timestep &lt;em&gt;t&lt;/em&gt;&lt;/strong&gt;, for each one of &lt;em&gt;k=12&lt;/em&gt; steps in the future.&lt;/p&gt;

&lt;p&gt;Concretely, at a given timestep &lt;em&gt;t&lt;/em&gt;, for each step &lt;em&gt;k&lt;/em&gt; = 1 … 12, we do the following:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Extract the true audio sample &lt;strong&gt;z&lt;sub&gt;t+k&lt;/sub&gt;&lt;/strong&gt; at future step &lt;em&gt;k&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;Pick 10 random &lt;em&gt;negative&lt;/em&gt; samples &lt;strong&gt;z̃&lt;sub&gt;1..10&lt;/sub&gt;&lt;/strong&gt; from the &lt;em&gt;same audio sequence&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;Compute a step &lt;em&gt;k&lt;/em&gt;-specific transformation &lt;strong&gt;h&lt;sub&gt;k&lt;/sub&gt;(c&lt;sub&gt;t&lt;/sub&gt;)&lt;/strong&gt; of the context vector at time &lt;em&gt;t&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;Compute the similarity (dot product) of the transformed context vector with all &lt;strong&gt;z&lt;/strong&gt; candidates&lt;/li&gt;
  &lt;li&gt;Compute the final probabilities of positive/negative through a sigmoid activation&lt;/li&gt;
  &lt;li&gt;Compare with the ground truth and penalize the model for wrong predictions (binary cross-entropy loss)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The following illustrates this process for the step &lt;em&gt;k=1&lt;/em&gt; (only four negatives are represented for simplicity):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/predict_future_1.png&quot; alt=&quot;Training Process&quot; /&gt;&lt;/p&gt;

&lt;p&gt;And here is the same thing but for step &lt;em&gt;k=2&lt;/em&gt; for a better understanding of the process:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/predict_future_2.png&quot; alt=&quot;Training Process&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The output of the model is the model computed probabilities for each sample to be the true future sample. A final binary cross-entropy loss is applied to penalize the model for wrongly predicting a negative sample as positive and vice versa. The total loss is the sum of the individual losses at each timestep &lt;em&gt;t&lt;/em&gt; for each future step &lt;em&gt;k&lt;/em&gt; in the future:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/illustrated-wav2vec/wav2vec_loss.png&quot; alt=&quot;Training Process&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;future-applications&quot;&gt;Future applications&lt;/h2&gt;

&lt;p&gt;In the original paper, the authors used wav2vec pre-trained representations as input for a separate speech recognition model. They demonstrated the power of their method by improving the previous best accuracy by 22% while using two orders of magnitude less labeled data.&lt;/p&gt;

&lt;p&gt;However, the use of wav2vec embeddings isn’t limited to speech recognition only. In a previous blog post, I wrote about how using wav2vec embeddings allowed us to &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;improve speech emotion recognition accuracy while using less labeled data for training&lt;/a&gt;. There is also potential to apply to more tasks like speech translation, speaker recognition, &lt;a href=&quot;https://en.wikipedia.org/wiki/Speaker_diarisation&quot;&gt;speaker diarization&lt;/a&gt;, etc.&lt;/p&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/2020/12/31/self-supervised-learning.html&quot;&gt;The Rise of Self-Supervised Learning&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/gpt2/2020/01/20/slogan-generator.html&quot;&gt;Building a Slogan Generator with GPT-2&lt;/a&gt;&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Wav2vec is a speech encoder model released by the Facebook AI team in late 2019. It quickly became popular in the speech processing community as it enabled new state-of-the-art performance for various speech tasks like automatic speech recognition or emotion recognition. Since its original version, the model has been upgraded to use the Transformers architecture (the same one behind GPT and BERT) and has been re-trained on 12 different languages in a multilingual version.</summary></entry><entry><title type="html">The Rise of Self-Supervised Learning</title><link href="https://jonathanbgn.com/2020/12/31/self-supervised-learning.html" rel="alternate" type="text/html" title="The Rise of Self-Supervised Learning" /><published>2020-12-31T04:00:00+00:00</published><updated>2020-12-31T04:00:00+00:00</updated><id>https://jonathanbgn.com/2020/12/31/self-supervised-learning</id><content type="html" xml:base="https://jonathanbgn.com/2020/12/31/self-supervised-learning.html">&lt;p&gt;Since the deep learning wave started in the early 2010s, there has been much hype and disappointments. I feel that a big part of this is due to &lt;strong&gt;high expectations driven by research progress that do not translate so well in real-world applications&lt;/strong&gt;. Hopefully, self-supervised learning might be able to close the gap between these two worlds. This learning paradigm is not new, but it has seen a resurgence of interest over the past few years thanks to mediatized successes like &lt;a href=&quot;https://en.wikipedia.org/wiki/GPT-3&quot;&gt;GPT-3&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/BERT_(language_model)&quot;&gt;BERT&lt;/a&gt;. Many AI pundits have also been relentlessly popularizing the idea, such as Facebook’s AI chief Yann Lecun with his &lt;a href=&quot;https://syncedreview.com/2019/02/22/yann-lecun-cake-analogy-2-0/&quot;&gt;cake analogy&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;what-is-self-supervised-learning-why-do-we-need-it&quot;&gt;What is self-supervised learning? Why do we need it?&lt;/h2&gt;

&lt;p&gt;I will first share a bit about the motivation and idea behind the concept, and then give some examples of how it is used in the main machine learning domains today.&lt;/p&gt;

&lt;h3 id=&quot;todays-deep-learning-success-is-mostly-about-labeled-data&quot;&gt;Today’s deep learning success is mostly about &lt;strong&gt;labeled&lt;/strong&gt; data&lt;/h3&gt;

&lt;p&gt;By now, you must have heard once or twice about the importance of data. Yet not all data is equal. What deep learning practitioners care the most about is &lt;strong&gt;labeled data, manually annotated by humans&lt;/strong&gt;. It is now commonly accepted that deep learning works incredibly well on tasks where large labeled datasets are available.&lt;/p&gt;

&lt;p&gt;The most famous example of such large datasets is &lt;a href=&quot;[AlexNet model architecture](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)&quot;&gt;ImageNet&lt;/a&gt;, a collection of 1+ million of images manually annotated by humans. ImageNet was a critical component of the rise of deep learning, and AI researchers often talk about the &lt;a href=&quot;https://en.wikipedia.org/wiki/ImageNet#Significance_for_deep_learning&quot;&gt;ImageNet Moment&lt;/a&gt;. In 2012, a deep learning model called &lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf&quot;&gt;AlexNet&lt;/a&gt; trained on ImageNet surpassed all other methods on image classification for the first time. The major innovation behind this success was the availability of this huge collection of labeled data, rather than AlexNet’s architecture itself. Indeed, the AlexNet architecture is strikingly similar to the 1998’s &lt;a href=&quot;https://en.wikipedia.org/wiki/LeNet&quot;&gt;LeNet-5&lt;/a&gt; architecture, except of course that it is much larger and deeper&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;

&lt;h3 id=&quot;problem-labels-dont-scale&quot;&gt;Problem: Labels don’t scale&lt;/h3&gt;

&lt;p&gt;While academic research often focuses on large clean labeled datasets like ImageNet, &lt;strong&gt;most data available for real-world applications is incredibly messy, and labels are extremely scarce&lt;/strong&gt;. The problem is even worst for particularly niche applications or unique domains and languages.&lt;/p&gt;

&lt;p&gt;Should we spend more effort to label existing data then? That has been the go-to solution so far, and an entire &lt;a href=&quot;https://www.ft.com/content/56dde36c-aa40-11e9-984c-fac8325aaa04&quot;&gt;labeling industry&lt;/a&gt; is getting established to answer this need. However, deep learning has an insatiable appetite for labeled data. You can quickly need in the order of millions of labeled examples for your model to generalize effectively! Moreover, &lt;strong&gt;labeling data can be extremely costly and time-consuming&lt;/strong&gt;. For many concrete use cases, this is not a practical solution.&lt;/p&gt;

&lt;h4 id=&quot;labels-are-expensive-fortunately-unlabeled-data-is-free&quot;&gt;Labels are expensive. Fortunately, unlabeled data is free!&lt;/h4&gt;

&lt;p&gt;On the other hand, there are more and more data available without labels out there. For many problem domains, you can collect large quantities of data from the Internet. Moreover, companies have access to troves of unstructured, unlabeled data from their day-to-day operations.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/data_growth.png&quot; alt=&quot;Data Growth&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Annual Size of the Global Datasphere (Source: &lt;a href=&quot;https://www.seagate.com/files/www-content/our-story/trends/files/idc-seagate-dataage-whitepaper.pdf&quot;&gt;IDC Data Age 2025&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Is there any way we could leverage this immense pool of data? It turns out that self-supervised learning can help with just that.&lt;/p&gt;

&lt;h3 id=&quot;reducing-the-need-for-human-labels&quot;&gt;Reducing the need for human labels&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Self-supervised learning allows training on unlabeled data&lt;/strong&gt;, thanks to &lt;strong&gt;automatic label generation.&lt;/strong&gt; This is still a form of &lt;a href=&quot;https://en.wikipedia.org/wiki/Supervised_learning&quot;&gt;supervised learning&lt;/a&gt;: the model learns how to map inputs with labels. The only difference is that we don’t need humans to manually annotate the data beforehand.&lt;/p&gt;

&lt;p&gt;How to generate these labels then? The most popular approach is to &lt;strong&gt;use one part of the input as the label itself&lt;/strong&gt;. There exists many possible ways to do this:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Remove a word from a sentence, which becomes the target label&lt;/li&gt;
  &lt;li&gt;Hide one part of an image and let the model re-generate it&lt;/li&gt;
  &lt;li&gt;Ask the model to predict the next frame in a video&lt;/li&gt;
  &lt;li&gt;…&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since we automatically generate the target to be predicted, we can now use all data available, labeled or not. For many use cases, this opens the door to training on an (almost) unlimited amount of data! &lt;strong&gt;This is a game-changing paradigm that effectively shifts the bottleneck from data quantity to compute capacity.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A good example is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Language_model&quot;&gt;language model&lt;/a&gt;: a model trained to predict the next word in a sentence. Text is widely available, and we can automatically split a sentence into its beginning and the final word to predict. It costs nothing to create one labeled example, and the amount of textual data on the Internet is now the limit. As the amount of training data is no longer limited, computing power and model sizes now become the limits for improving performance. The recent GPT-3 model is the perfect example of this: we now need to build enormous models to take advantage of so much data. According to &lt;a href=&quot;https://lambdalabs.com/blog/demystifying-gpt-3/&quot;&gt;some estimates&lt;/a&gt;, training GPT-3 by yourself with current cloud platform offerings would require 355 years and $4,600,000!&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/quotes_language_model.png&quot; alt=&quot;Language Model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A language model like the GPT family predicts the next token based on what came before.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;a-very-short-history-of-self-supervised-learning&quot;&gt;A very short history of self-supervised learning&lt;/h2&gt;

&lt;p&gt;Despite the recent surge of interest in self-supervised learning, this is &lt;strong&gt;not a new idea&lt;/strong&gt;. Back in 2006, Geoffrey Hinton et al. published a &lt;a href=&quot;https://www.cs.toronto.edu/~hinton/absps/ncfast.pdf&quot;&gt;seminal paper&lt;/a&gt; about pre-training Restricted Boltzmann Machines in an unsupervised way followed by a fine-tuning phase. This led to a lot of interest in the method, but it quickly faded as people realized that if you have a large labeled dataset, then it is enough to train directly in a supervised way.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/self_supervised_learning_interest.png&quot; alt=&quot;Interest in Self-Supervised Learning&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Yet the idea might be even older. The earliest usage of the term on Google Scholar is in a 1978 paper, and multiple papers were referencing it &lt;a href=&quot;https://twitter.com/phillip_isola/status/1216902657702617093&quot;&gt;back in the 1990s&lt;/a&gt;. Even before the use of the term itself, related ideas like language models were already quite popular. The first N-Gram language models are at least as old as Claud Shannon’s 1948 seminal paper &lt;a href=&quot;http://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf&quot;&gt;A Mathematical Theory of Communications&lt;/a&gt;, which set the foundation of Information Theory.&lt;/p&gt;

&lt;p&gt;That the concept is now experiencing a resurgence is thus less due to a breakthrough in theory but more to the exponentially available quantity of unlabeled data and the increasing need to extract value from it.&lt;/p&gt;

&lt;h2 id=&quot;bridging-the-gap-between-research-and-real-life&quot;&gt;Bridging the gap between research and real-life&lt;/h2&gt;

&lt;h3 id=&quot;transfer-knowledge-to-generalize-better&quot;&gt;Transfer knowledge to generalize better&lt;/h3&gt;

&lt;p&gt;The true power of self-supervised learning does not lie in using it just for a few tasks like language modeling for which we can generate an infinite amount of labeled data. &lt;strong&gt;The key is to use it as a transfer learning method&lt;/strong&gt;, where we transfer the knowledge contained in a model trained on a task for which plenty of data is available to the objective task for which data is limited. This is usually done in two training steps. In the first step we &lt;em&gt;pre-train&lt;/em&gt; our model in a self-supervised way on a &lt;em&gt;pretext task&lt;/em&gt; such as language modeling (also called the &lt;em&gt;auxiliary task&lt;/em&gt; in the literature). In the second step, we &lt;em&gt;fine-tune&lt;/em&gt; our model on the downstream task, which is the one that we care about. This second step is done in a standard supervised way, trained on human-labeled data.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/transfer_learning.png&quot; alt=&quot;Transfer Learning&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Transfer learning works by re-using knowledge of a model trained on another task for which data is abundant (&lt;a href=&quot;https://datascience.aero/transfer-learning-aviation/&quot;&gt;Image credit&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;An important point here is the choice of the pretext task. This task must make sense such that solving it must be in some way useful to the downstream task. In other words, the pretext task should force the model to encode the data to a meaningful representation that can be re-used for fine-tuning later. For example, a language model trained in a self-supervised way needs to learn about meaning and grammar to effectively predict the next word. This linguistic knowledge can be re-used in a downstream task like predicting the sentiment of a text.&lt;/p&gt;

&lt;h3 id=&quot;improve-performance-on-small-datasets&quot;&gt;Improve performance on small datasets&lt;/h3&gt;

&lt;p&gt;While we still need some domain-specific labeled data for the second fine-tuning step, pre-training first in a self-supervised way has been shown to immensely improve the performance on the downstream task, even when very few labeled data is available for fine-tuning. For example, the &lt;a href=&quot;https://arxiv.org/abs/1801.06146&quot;&gt;ULMFiT paper&lt;/a&gt; showed that it is possible to reach great performance for text classification with only 100 labeled examples. More recently, a new paper from DeepMind outperformed the original AlexNet performance on ImageNet with &lt;strong&gt;only 13 labeled examples per class&lt;/strong&gt;.&lt;/p&gt;

&lt;h4 id=&quot;self-supervised-learning-does-not-remove-the-need-for-labeled-data-but-it-greatly-reduces-the-need-for-it-and-makes-it-practical-to-deploy-deep-learning-models-for-use-cases-in-which-labeled-data-is-very-limited&quot;&gt;Self-supervised learning does not remove the need for labeled data, but it greatly reduces the need for it and makes it practical to deploy deep learning models for use cases in which labeled data is (very) limited.&lt;/h4&gt;

&lt;p&gt;And this is exactly why it might be the key to unlock the promises of deep learning in real-world applications and for the industry. Since the digital revolution began, companies have been collecting tons of proprietary data in the hope of profiting from it in the future. However, they don’t know what to do with it so far as most of it is messy, unstructured, and most importantly unlabeled. Bringing self-supervised learning in the equation could help unleash the latent value from these tons of data.&lt;/p&gt;

&lt;h2 id=&quot;the-state-of-self-supervised-learning-in-2021&quot;&gt;The state of self-supervised learning in 2021&lt;/h2&gt;

&lt;h3 id=&quot;natural-language-processing&quot;&gt;Natural language processing&lt;/h3&gt;

&lt;p&gt;NLP is the first field in which self-supervised learning first became hugely popular, and as such has many examples of the technique. The most straight-forward example that I already mentioned in the language model, predicting the next word in a sentence. Despite being one of the earliest examples of the method, it is still popular today due to big models like GPT-3.&lt;/p&gt;

&lt;p&gt;Language models are far from being the only examples in the field. A variety of word embeddings approaches such as &lt;a href=&quot;https://en.wikipedia.org/wiki/Word2vec&quot;&gt;word2vec&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/GloVe_(machine_learning)&quot;&gt;GloVe&lt;/a&gt; also revolutionized the field back in the 2010s. The idea was simple, instead of predicting the next word, we could just ask the model to predict a word based on its context or vice versa. We then obtain &lt;a href=&quot;https://en.wikipedia.org/wiki/Word_embedding&quot;&gt;distributed representations of words (embeddings)&lt;/a&gt; which encode meaningful information about words and can be re-used in all sorts of problems.&lt;/p&gt;

&lt;p&gt;Today, the most popular self-supervised approach is arguably the masked language modeling one, which the now famous &lt;a href=&quot;https://en.wikipedia.org/wiki/BERT_(language_model)&quot;&gt;BERT model&lt;/a&gt; exemplifies. By “masking” random words in the text and asking the model to fill the holes, we can learn meaningful representations that can be later used or fine-tuned in a variety of downstream tasks.&lt;/p&gt;

&lt;p&gt;The quest for the optimal pretext task is far from complete! Just this month at NeurIPS 2020, Facebook AI shared a promising &lt;strong&gt;new self-supervised learning technique: paraphrasing&lt;/strong&gt;. Their model &lt;a href=&quot;https://arxiv.org/abs/2006.15020&quot;&gt;MARGE&lt;/a&gt; finds related documents and then paraphrases them to reconstruct the original. This approach even allows for good enough performance on some tasks without a fine-tuning step on extra labeled data.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/nlp_paraphrasing.png&quot; alt=&quot;Paraphrasing&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;computer-vision&quot;&gt;Computer vision&lt;/h3&gt;

&lt;p&gt;Unlike NLP, self-supervision has not yet seen widespread adoption here, mostly because current techniques are still a bit too complex to implement. Yet this might change very soon. Influenced by the success of the concept in NLP, research has been very active in the area. This year alone, there has been an explosion of papers on self-supervised learning in image recognition. Performance obtained through self-supervision is starting to match end-to-end supervised models even when labeled data is abundant like for ImageNet.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://www.fast.ai/2020/01/13/self_supervised/&quot;&gt;Many kinds of pretext tasks&lt;/a&gt; are being used today, such as colorization (black &amp;amp; white to colors), patch placement (ordering patches cut from an image like a puzzle), or inpainting (filling an automatically created gap). One of the most interesting ideas of the moment is the one of contrastive learning. A neural network is trained to generate consistent representations between different views of the same image (randomly transformed by cropping or rotation), but distant representations between different images. A good example of the idea is the &lt;a href=&quot;https://ai.googleblog.com/2020/04/advancing-self-supervised-and-semi.html&quot;&gt;SimCLR framework&lt;/a&gt; from Google.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/cpc_self_supervised_performance.png&quot; alt=&quot;Contrastive Predictive Coding&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/pdf/1905.09272.pdf&quot;&gt;Data-Efficient Image Recognition with Contrastive Predictive Coding&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are still some important problems that must be solved before we see wider adoption of self-supervision in vision. Often, many “tricks” (data augmentation, negative sampling…) are used during the self-supervised phase, and these can be very domain-specific and hard to implement. Moreover, the losses can be quite complex, and difficult to optimize properly.&lt;/p&gt;

&lt;h3 id=&quot;speech-processing&quot;&gt;Speech processing&lt;/h3&gt;

&lt;p&gt;Last but not least, self-supervised learning is also just starting to gain traction in speech processing. I am personally very enthusiastic about the future of this field, as I’m currently working on &lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Speech Emotion Recognition&lt;/a&gt;, a hard task for which labeled data is extremely scarce. Using self-supervised learning, we were able to beat strong baselines while &lt;strong&gt;using only 100 examples per emotion&lt;/strong&gt; and &lt;a href=&quot;https://arxiv.org/abs/2011.05585&quot;&gt;improve upon the state-of-the art&lt;/a&gt; when using all data. I deeply believe that self-supervised learning is the key that will allow the emotion recognition field to make large progress in the coming years, and progress from basic emotion detection to more complex characterization of moods and states-of-mind.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-20-learning-the-structure-of-speech-from-raw-audio/&quot;&gt;wav2vec model&lt;/a&gt;, inspired by word2vec, is in my opinion the most successful attempt so far for bringing self-supervised learning into the field. The model saw successive improvement and version 2.0 was just published at NeurIPS this year. While the model was originally only made of convolutional networks, the Facebook AI team then added a Transformer network to the architecture and, inspired by NLP, added an automatic discretization of inputs to be able to use some of the NLP models that work well on discrete data. The method allowed the creation of &lt;a href=&quot;https://arxiv.org/abs/2010.11430&quot;&gt;robust Automatic Speech Recognition (ASR) models with only 10 minutes of labeled data!&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wav2vec_objective.jpg&quot; alt=&quot;Wav2vec Model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Wav2vec uses contextual representations to distinguish between real and fake future samples of audio. Here “CUH” is the correct sample.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Wav2vec is not the only self-supervised approach in this domain. Google AI has been working with the huge &lt;a href=&quot;https://research.google.com/audioset/&quot;&gt;AudioSet dataset&lt;/a&gt; which contains more than 2 million audio clips to create unsupervised embeddings for speech. The &lt;a href=&quot;https://ai.googleblog.com/2020/06/improving-speech-representations-and.html&quot;&gt;resulting embeddings called TRILL&lt;/a&gt; allowed to reach very competitive performance and even state-of-the-art on a variety of tasks such as speaker identification, language identification, emotion detection, or even dementia detection.&lt;/p&gt;

&lt;h3 id=&quot;the-future-will-likely-be-self-supervised&quot;&gt;The future will likely be self-supervised&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/self_supervised_learning_papers.png&quot; alt=&quot;Number of Self-Supervised Learning Papers&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Number of papers containing the term “self-supervised learning”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I believe that self-supervised learning will soon become the gold standard in most fields of machine learning. As the techniques become better and deep learning frameworks remove implementation complexity, there will be wider adoption across all areas. We are also starting to see public repositories of models trained in a self-supervised way that anyone can download for their use case, such as on the &lt;a href=&quot;https://huggingface.co/models&quot;&gt;HuggingFace website&lt;/a&gt;. The mass sharing of already trained self-supervised model will help democratize the use of the technique to every application.&lt;/p&gt;

&lt;h4 id=&quot;read-next&quot;&gt;Read next&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/nlp/2020/08/30/gpt2-gpt3-creativity.html&quot;&gt;Unleash GPT-2 (and GPT-3) Creativity through Decoding Strategies&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;footnotes&quot;&gt;Footnotes&lt;/h4&gt;

&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Despite its similarity with LeNet-5, AlexNet was also the first model to stack convolutional layers directly on top of each other, removing intermediary pooling layers. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;</content><author><name>Jonathan Boigne</name></author><summary type="html">Since the deep learning wave started in the early 2010s, there has been much hype and disappointments. I feel that a big part of this is due to high expectations driven by research progress that do not translate so well in real-world applications. Hopefully, self-supervised learning might be able to close the gap between these two worlds. This learning paradigm is not new, but it has seen a resurgence of interest over the past few years thanks to mediatized successes like GPT-3 or BERT. Many AI pundits have also been relentlessly popularizing the idea, such as Facebook’s AI chief Yann Lecun with his cake analogy.</summary></entry><entry><title type="html">Detecting Emotions from Voice with Very Few Training Data</title><link href="https://jonathanbgn.com/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html" rel="alternate" type="text/html" title="Detecting Emotions from Voice with Very Few Training Data" /><published>2020-10-31T09:00:00+00:00</published><updated>2020-10-31T09:00:00+00:00</updated><id>https://jonathanbgn.com/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec</id><content type="html" xml:base="https://jonathanbgn.com/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html">&lt;p&gt;&lt;img src=&quot;/assets/images/boy_singing.jpg&quot; alt=&quot;Speech Emotion Recognition&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Full paper available on &lt;a href=&quot;https://arxiv.org/abs/2011.05585&quot;&gt;arXiv&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Speech emotion recognition has become more and more popular over recent years, largely because of the large range of applications enabled by the technology in fields ranging from human-computer interaction to healthcare. Tech giants have also seen this future potential and have been launching new products such as the &lt;a href=&quot;https://www.theverge.com/2020/8/27/21402493/amazon-halo-band-health-fitness-body-scan-tone-emotion-activity-sleep&quot;&gt;Amazon Halo&lt;/a&gt; which can detect emotions in real-time from the voice. However, there are still some challenges that need to be surpassed to unleash the full potential of Emotion AI.&lt;/p&gt;

&lt;p&gt;Recently, I’ve been collaborating with WonderTech, a leader in Emotion AI, to improve emotion recognition in situations where training data is scarce. Long story short, we obtained &lt;strong&gt;very competitive performance with a little more than 100 training examples per emotion&lt;/strong&gt; (each example is ~5 seconds). Our model was able to perform well thanks to the use of pre-trained representations, extracted from &lt;strong&gt;Facebook AI’s wav2vec model&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;challenges&quot;&gt;Challenges&lt;/h2&gt;

&lt;p&gt;There are many challenges to accurate emotion recognition like dealing with noise, but the most important ones are the &lt;strong&gt;lack of labeled data&lt;/strong&gt; and the fact that we still &lt;strong&gt;don’t know which features are the most suitable for the task&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;lack-of-labeled-data&quot;&gt;Lack of labeled data&lt;/h3&gt;

&lt;p&gt;A big hurdle for emotion detection is the lack of available data. For example &lt;strong&gt;IEMOCAP&lt;/strong&gt;, the most popular benchmark dataset for speech emotion recognition, only contains &lt;strong&gt;8 hours&lt;/strong&gt; of labeled data. Compare that to the large datasets available for Automatic Speech Recognition (ASR), where modern systems are trained on more than 10,000 hours of data.&lt;/p&gt;

&lt;p&gt;There are also other data challenges in these datasets, such as an uneven number of classes, diversity issues with a few speakers or few different domains, “acted” speech vs “natural” speech…&lt;/p&gt;

&lt;h3 id=&quot;choice-of-features&quot;&gt;Choice of features&lt;/h3&gt;

&lt;p&gt;Researchers have been experimenting with many different features to understand which ones contain the &lt;strong&gt;most salient emotion signal&lt;/strong&gt;. However, it is still unclear which ones are the most suitable. Here is a quick overview of what’s currently out there.&lt;/p&gt;

&lt;h4 id=&quot;low-level-descriptors&quot;&gt;Low-level descriptors&lt;/h4&gt;

&lt;p&gt;These are hand-engineered features that were found to work well in other speech-related tasks such as automatic speech recognition or speaker identification. They are usually computed on short time frames of speech of around 20-50 milliseconds. There exist hundreds of such features related to various aspects of the audio signal such as energy or pitch.&lt;/p&gt;

&lt;p&gt;The most popular are &lt;strong&gt;MFCCs or Mel-Frequency Cepstrum Coefficients&lt;/strong&gt;. These coefficients are computed in a way that is able to represent the shape of a person’s vocal tract speaking.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/vocal_tract.png&quot; alt=&quot;Vocal Tract&quot; /&gt;&lt;/p&gt;

&lt;p&gt;While MFCCs and other low-level descriptors work reasonably well, critics point out that such features are often too simple and can lose many important information from the original signal.&lt;/p&gt;

&lt;h4 id=&quot;spectrogram-and-filter-banks&quot;&gt;Spectrogram and filter banks&lt;/h4&gt;

&lt;p&gt;Another approach is to use the variation of the audio signal frequencies across time. Proponents of this approach argue that such features are more natural, flexible, and less opinionated than the manually crafted features above. Indeed, most low-level descriptors are computed after first extracting frequency information from the audio signal, including MFCCs. By feeding the model with a more “pure” representation of the signal, we can &lt;strong&gt;let the model learn the best features by itself&lt;/strong&gt; without influencing it with potentially biased human prior.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/spectrogram.png&quot; alt=&quot;Spectrogram&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;raw-audio&quot;&gt;Raw audio&lt;/h4&gt;

&lt;p&gt;Yet, even spectrograms are an imperfect representation of the “raw signal”. There are still the result of a &lt;a href=&quot;https://en.wikipedia.org/wiki/Fast_Fourier_transform&quot;&gt;mathematical transformation&lt;/a&gt; that loses some information from the source. This is why using the raw audio signal is theoretically the best approach if we want to give the model complete freedom in identifying the best features by itself. This idea is in line with other domains of machine learning such as vision or natural language processing, where the most performant models are deep ones trained directly on the raw input.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/raw_audio_waveform.png&quot; alt=&quot;Audio Waveform&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This approach has been proven to work well, as demonstrated by DeepMind’s &lt;a href=&quot;https://deepmind.com/blog/article/wavenet-generative-model-raw-audio&quot;&gt;WaveNet&lt;/a&gt; or Facebook’s &lt;a href=&quot;https://github.com/facebookresearch/wav2letter&quot;&gt;wav2letter&lt;/a&gt;. However, the model needs to be much deeper in order to be able to detect meaningful patterns across the raw signal. And to train a deeper model we need… more data! We are back to our first problem of small labeled datasets.&lt;/p&gt;

&lt;h2 id=&quot;transfer-learning-to-the-rescue&quot;&gt;Transfer learning to the rescue&lt;/h2&gt;

&lt;p&gt;Over the past decade, great progress has been made in other domains like NLP or computer vision. A big part of it is due to the rise of transfer learning, which transfers knowledge gained from one bigger dataset (usually for a more general task) to a target dataset.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In computer vision&lt;/strong&gt;, it is now standard to re-use a model pre-trained on the large ImageNet dataset before fine-tuning it on a smaller dataset for the target task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In natural language processing&lt;/strong&gt;, large pre-trained models like BERT or GPT are now being fine-tuned on a multitude of tasks and &lt;a href=&quot;https://gluebenchmark.com/leaderboard&quot;&gt;perform much better than other approaches&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Surprisingly, however, transfer learning has not taken off for speech yet, mainly because it is still unclear which task is the most suitable for pretraining.&lt;/p&gt;

&lt;h3 id=&quot;learning-unsupervised-representations-with-wav2vec&quot;&gt;Learning unsupervised representations with wav2vec&lt;/h3&gt;

&lt;p&gt;Wav2vec is a recent model &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-state-of-the-art-speech-recognition-through-self-supervision/&quot;&gt;released by Facebook in 2019&lt;/a&gt;. It was inspired by &lt;a href=&quot;https://en.wikipedia.org/wiki/Word2vec&quot;&gt;word2vec&lt;/a&gt;, a now very popular technique to learn meaningful embeddings (vectors) from raw textual data. Similarly, wav2vec was trained on unlabeled speech data, meaning that only the raw audio signal (no transcriptions) was used during training. This is a potential game-changer for speech applications as the model can be trained on any language or domain without needing to spend time and resources labeling the data.&lt;/p&gt;

&lt;p&gt;The model consists of two convolutional networks stacked on top of each other: the encoder network and the context network. While the encoder can attend to only ~30 milliseconds of speech, the context network can combine multiple encoder outputs to model around 1 second of raw audio. The model then &lt;strong&gt;uses this contextual representation to predict what comes next&lt;/strong&gt;. More specifically, it learns to distinguish between real future 10ms samples and distractor samples that were taken randomly from other sections of the clip.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wav2vec_objective.jpg&quot; alt=&quot;Wav2vec Model&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Wav2vec uses contextual representations to distinguish between real and fake future samples of audio. Here “CUH” is the correct sample.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;After training wav2vec on 1,000 hours of unlabelled data, Facebook then used the learned contextual representations to train an independent ASR model, replacing the previous spectrogram features. This resulted in 22 percent accuracy improvement over Deep Speech 2, the best system at the time while using two orders of magnitude less labeled data.&lt;/p&gt;

&lt;h3 id=&quot;using-wav2vec-representations-to-recognize-emotions&quot;&gt;Using wav2vec representations to recognize emotions&lt;/h3&gt;

&lt;p&gt;Although wav2vec was made in the objective of Automatic Speech Recognition, we wanted to know if the contextual representations also contained emotional content. We decided to feed wav2vec’s contextual representations in a variety of classification models and to compare performance with traditional features like low-level descriptors or log-Mel spectrograms.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/emotion_wav2vec_comparison.png&quot; alt=&quot;Results&quot; /&gt;&lt;/p&gt;

&lt;p&gt;We trained our models on the IEMOCAP dataset, the most popular benchmark for speech emotion recognition. The results were conclusive, with the contextual representations performing much better than any other feature set that we experimented with. &lt;strong&gt;We were able to get better performance than with hand-crafted features with 8 times less data!&lt;/strong&gt; This indicates that wav2vec is indeed capable of learning emotional information by itself without explicitly told so (remember, the training objective was only to distinguish true future samples from fake ones).&lt;/p&gt;

&lt;h3 id=&quot;combining-speech-with-linguistic-features&quot;&gt;Combining speech with linguistic features&lt;/h3&gt;

&lt;p&gt;In one last experiment, we decided to combine the wav2vec representations with textual representations to provide our model with extra information about the linguistic content of speech. We decided to encode the text transcriptions of each IEMOCAP dialog using &lt;a href=&quot;https://en.wikipedia.org/wiki/BERT_(language_model)&quot;&gt;BERT&lt;/a&gt;, another model often used for transfer learning in NLP. When combining audio and text, an important challenge is the one of &lt;strong&gt;alignment&lt;/strong&gt;. For example, how can the model learn which segment of audio corresponds to a given word?&lt;/p&gt;

&lt;p&gt;To answer this, we built a multimodal model using attention to align the speech representations (wav2vec) with textual representations (BERT) along the time dimension. When cross-validating our multimodal model on the 5 sessions of the IEMOCAP dataset, we were able to reach an &lt;strong&gt;unweighted accuracy of 73.9%, more than all the other multimodal techniques that we reviewed&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Our research clearly shows the potential of transfer learning for emotion recognition. The re-use of unsupervised representation allows for accurate models even when training data is scarce. Still, enough labeled data will be needed to reach optimal performance and mitigate risk in sensitive applications such as mental health. &lt;strong&gt;Data diversity&lt;/strong&gt; is especially important to allow models to work for any person speaking, &lt;strong&gt;no matter the language, dialect, accent, gender, or age&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The research in transfer learning and self-supervised learning for speech applications is also moving fast. Since the original version of wav2vec, Facebook has been releasing two subsequent iterations of the model: &lt;a href=&quot;https://research.fb.com/publications/vq-wav2vec-self-supervised-learning-of-discrete-speech-representations/&quot;&gt;vq-wav2vec&lt;/a&gt; and &lt;a href=&quot;https://ai.facebook.com/blog/wav2vec-20-learning-the-structure-of-speech-from-raw-audio/&quot;&gt;wav2vec 2.0&lt;/a&gt;, the latter inspired by the masked language modeling objective function of BERT.&lt;/p&gt;

&lt;p&gt;For more details about our methodology and model, you can go &lt;a href=&quot;https://arxiv.org/abs/2011.05585&quot;&gt;here&lt;/a&gt; to read our full research paper.&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><category term="speech" /><summary type="html"></summary></entry><entry><title type="html">Build a Collaborative Chatbot with Google Sheets and TensorFlow</title><link href="https://jonathanbgn.com/nlp/2020/09/29/chatbot-universal-sentence-encoder.html" rel="alternate" type="text/html" title="Build a Collaborative Chatbot with Google Sheets and TensorFlow" /><published>2020-09-29T14:00:00+00:00</published><updated>2020-09-29T14:00:00+00:00</updated><id>https://jonathanbgn.com/nlp/2020/09/29/chatbot-universal-sentence-encoder</id><content type="html" xml:base="https://jonathanbgn.com/nlp/2020/09/29/chatbot-universal-sentence-encoder.html">&lt;p&gt;&lt;img src=&quot;/assets/images/taipei.jpg&quot; alt=&quot;Taipei&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Currently living in Taiwan, I recently joined the &lt;a href=&quot;https://github.com/taiwangoldcard/taiwan-bot&quot;&gt;Taiwan Bot 🤖&lt;/a&gt; project along with &lt;a href=&quot;https://www.linkedin.com/in/shawn-lim-0a307550&quot;&gt;Shawn&lt;/a&gt; and &lt;a href=&quot;https://erickhun.com/about/&quot;&gt;Eric&lt;/a&gt;. The idea is to build a go-to assistant to help foreigners answer their questions about moving to, working, and living in Taiwan (pro-tip: ask the bot where to find cheese or chocolate).&lt;/p&gt;

&lt;p&gt;Building a functional and useful chatbot is a non-trivial project. Fortunately, there has been impressive progress in the fields of machine learning and &lt;strong&gt;natural language processing (NLP)&lt;/strong&gt; in the past few years. Moreover, the democratization and open-source sharing of cutting-edge deep learning models from research work at large tech companies like Google or Facebook is making it possible for anyone to implement the latest state-of-the-art solutions.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://ai.googleblog.com/2018/05/advances-in-semantic-textual-similarity.html&quot;&gt;Universal Sentence Encoder&lt;/a&gt;, recently released by Google AI, is one of these new models available via &lt;a href=&quot;https://tfhub.dev/google/universal-sentence-encoder/4&quot;&gt;Tensorflow Hub&lt;/a&gt;. Trained in a &lt;strong&gt;multi-tasking&lt;/strong&gt; fashion, the model can encode sentences into meaningful continuous representations that work well on a range of different tasks. It is thus ideal for &lt;strong&gt;transfer learning&lt;/strong&gt; and performs competitively with more complex models like &lt;a href=&quot;https://en.wikipedia.org/wiki/BERT_(language_model)&quot;&gt;BERT&lt;/a&gt;. Moreover, it can run much faster than BERT or other similar &lt;a href=&quot;https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)&quot;&gt;Transformer&lt;/a&gt; models and is thus more applicable to real-world problems. There is even a &lt;a href=&quot;https://tfhub.dev/google/universal-sentence-encoder-lite/2&quot;&gt;Lite version&lt;/a&gt; of the model, small enough to run in Javascript on the client-side.&lt;/p&gt;

&lt;h2 id=&quot;the-project&quot;&gt;The project&lt;/h2&gt;

&lt;p&gt;Despite being an amazing place to live, &lt;strong&gt;Taiwan is still misunderstood by most foreigners&lt;/strong&gt;. We think that a fun and approachable chatbot could help people understand a lot more about all the great things this place has to offer, as well as answer most of the questions they might have about living here.&lt;/p&gt;

&lt;p&gt;We decided to start with a limited scope first and to focus on answering practical questions about moving to and living in Taiwan. Specifically, we chose to focus on visa issues and the recently created &lt;a href=&quot;https://taiwangoldcard.com&quot;&gt;Gold Card program&lt;/a&gt;. We plan to expand the bot capabilities in future versions.&lt;/p&gt;

&lt;p&gt;When it comes to chatbots, there are a lot of ways to go, and many tools and libraries out there to help you make your plan a reality. However, being just a small team of 3 doing this in our spare time, we didn’t have enough resources and time to build something very sophisticated. We also didn’t want to spend a lot of time to compile a large training dataset. So we looked for the best way to build a system that would be:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;🧩 Easy and quick to build&lt;/li&gt;
  &lt;li&gt;⚡️ Lightweight and runnable on a small server&lt;/li&gt;
  &lt;li&gt;🔧 Iterable and easy to improve&lt;/li&gt;
  &lt;li&gt;🧠 Focused on finding relevant answers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We chose to build our bot with Microsoft’s &lt;a href=&quot;https://github.com/microsoft/botframework-sdk&quot;&gt;Bot Framework SDK&lt;/a&gt; for easy development, user management and to be able to easily publish it to multiple platforms like Messenger or Line, the most popular messaging platform in Taiwan. &lt;strong&gt;The only thing remaining was to build the brain behind the messages.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;understanding-the-meaning-behind-a-question&quot;&gt;Understanding the meaning behind a question&lt;/h2&gt;

&lt;p&gt;The main challenge when building a bot is &lt;strong&gt;relevancy&lt;/strong&gt;, and this starts by having a clear understanding of what the user’s intention is. There are many approaches possible to make sense of what the user wants. At the most simple, one could simply look for some keywords such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hello&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;restaurant&lt;/code&gt;, or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;visa&lt;/code&gt;. However, this doesn’t take at all into account all the nuances of the language.&lt;/p&gt;

&lt;p&gt;We didn’t have the resources to build a full-scale bot that could recognize the user intention among thousands of possibilities, yet we wanted to create something that could be relevant enough so that people would find it useful. So we needed to find an ideal middle ground between complexity and performance.&lt;/p&gt;

&lt;p&gt;One of the most important concepts in NLP is one of &lt;strong&gt;distributed representations&lt;/strong&gt;, inspired by the linguistic field of &lt;a href=&quot;https://en.wikipedia.org/wiki/Distributional_semantics&quot;&gt;distributional semantics&lt;/a&gt;. The core idea is to encode linguistic items (words, sentences) into &lt;strong&gt;embeddings&lt;/strong&gt; (vectors in a large dimensional space) such that items with similar properties should be closer in the resulting space.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;You shall know a word by the company it keeps.&lt;/p&gt;

  &lt;p&gt;&lt;em&gt;- John Rupert Firth (1957)&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example, similar words will cluster together in the vector space:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/word-embeddings.png&quot; alt=&quot;Word Embeddings&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Image from &lt;a href=&quot;https://blog.tensorflow.org/2020/08/introducing-semantic-reactor-explore-nlp-sheets.html&quot;&gt;TensorFlow Blog&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You could do the same as the above but with sentences, effectively encoding them into large vectors which can be compared between themselves using &lt;strong&gt;similarity functions&lt;/strong&gt;. Hence sentences with similar vector representations are sentences with similar meaning, topic, syntax…&lt;/p&gt;

&lt;h2 id=&quot;encoding-questions-with-the-universal-sentence-encoder&quot;&gt;Encoding questions with the Universal Sentence Encoder&lt;/h2&gt;

&lt;p&gt;The &lt;a href=&quot;https://arxiv.org/abs/1803.11175&quot;&gt;Universal Sentence Encoder&lt;/a&gt; is a powerful Transformer model (in its large version) allowing to extract &lt;a href=&quot;https://developers.google.com/machine-learning/crash-course/embeddings/video-lecture&quot;&gt;embeddings&lt;/a&gt; directly from sentences instead of from individual words. It already powers some impressive Google projects such as &lt;a href=&quot;https://books.google.com/talktobooks/&quot;&gt;Talk to Books&lt;/a&gt; or &lt;a href=&quot;https://google.github.io/mysteryofthreebots/&quot;&gt;Mystery of the Three Bots&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For our chatbot project, we are first using the model to encode all the questions that we think users would want to ask to the bot. This can be done in a few lines of code thanks to the convenient TensorFlow Hub library:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;tensorflow&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;tensorflow_hub&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tfhub&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tfhub&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;load&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;https://tfhub.dev/google/universal-sentence-encoder/4&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;questions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# questions most likely to be asked to the bot
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;answers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;....&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# all answers to the questions above
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;questions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;questions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;questions_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;concat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Then whenever a user asks a question, we can just extract its embedding and find the most similar question in our database of embeddings. In our case we use a simple vector dot product as a similary function:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;find_best_answer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;question&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;embedding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;question&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# compute dot product with each question:
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;questions_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;answers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;google-sheets-as-a-collaborative-database&quot;&gt;Google Sheets as a collaborative database&lt;/h2&gt;

&lt;p&gt;We built our dataset using a simple Google spreadsheet with 2 columns: questions and answers. Whenever a user asks a question, we just find the most relevant question and return the appropriate answer.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/taiwan-bot-database.png&quot; alt=&quot;Questions Answers Dataset&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This approach, while relatively simple, is a flexible enough for efficiently working together. Querying the data is done once during startup with a few lines of code:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;client&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gspread&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;authorize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ServiceAccountCredentials&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;from_json_keyfile_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SERVICE_ACCOUNT_INFO_DICT&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'https://spreadsheets.google.com/feeds'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'https://www.googleapis.com/auth/drive'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sheet&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;client&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SPREADSHEET_FAQ_FILE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;worksheet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SPREADSHEET_SHEET_NAME&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;questions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sheet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;answers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sheet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here is an example of a conversation with the bot:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/taiwan-bot-conversation.jpg&quot; alt=&quot;Conversation with the bot&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;continuous-improvement&quot;&gt;Continuous improvement&lt;/h2&gt;

&lt;p&gt;We did our best to think about what would be the most commonly asked questions but, of course, we cannot predict everything people will ask. This is why if you ask a question that is not present in our database, the bot can answer with something completely unrelated. To prevent this, we built a small logging system to be able to track the questions asked to the bot and which question it thought was the most similar (along with the similarity score).&lt;/p&gt;

&lt;p&gt;For example, here is what happened behind the scenes during the small conversation above. The first column is the user message. The second column is the most similar question (as based on the embeddings similarity). The third column is the best answer and the last column the computed similarity score. If the similarity score is not good enough, the bot will answer with a generic reply &lt;em&gt;” Sorry, I cannot help with that yet “&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/taiwan-bot-logs.png&quot; alt=&quot;Conversation Logs&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This logging system will also help us improve our answers as more people use the bot and new edge cases are found. Still, no chatbot is perfect, and we think the bot will be most useful in a context where humans can take over when the bot fails. For example, on Slack, we added the bot to a general FAQ channel where people can get assistance from both the bot and humans for more specific information.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/taiwan-bot-slack.png&quot; alt=&quot;Chatbot on Slack&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Building an effective chatbot doesn’t have to be a complex project. As long as the scope is relatively narrow, it is possible to use a general encoder model like the Universal Sentence Encoder to build something useful. The hard part is collecting enough questions/answers for the bot to be able to answer most questions. It is also important to regularly monitor what users are asking and complement new data whenever the bot can’t find a relevant answer.&lt;/p&gt;

&lt;p&gt;If you are also living or considering to move to Taiwan, you can &lt;a href=&quot;https://m.me/thetaiwanbot&quot;&gt;chat with Taiwan bot on Messenger here&lt;/a&gt;!&lt;/p&gt;

&lt;h3 id=&quot;read-next&quot;&gt;Read next&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;/nlp/2020/08/30/gpt2-gpt3-creativity.html&quot;&gt;Unleash GPT-2 (and GPT-3) Creativity through Decoding Strategies&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/speech/2020/10/31/emotion-recognition-transfer-learning-wav2vec.html&quot;&gt;Detecting Emotions from Voice with Very Few Training Data&lt;/a&gt;&lt;/p&gt;</content><author><name>Jonathan Boigne</name></author><category term="nlp" /><summary type="html"></summary></entry></feed>