<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bruno Lima on Medium]]></title>
        <description><![CDATA[Stories by Bruno Lima on Medium]]></description>
        <link>https://medium.com/@limazix?source=rss-b212f3a73528------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S5WIPLaN8xk1ahEpmO7DYQ.jpeg</url>
            <title>Stories by Bruno Lima on Medium</title>
            <link>https://medium.com/@limazix?source=rss-b212f3a73528------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:12:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@limazix/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Audio Classifier with Fast.ai]]></title>
            <link>https://medium.com/@limazix/audio-classifier-with-fast-ai-2b4f9e1d11d0?source=rss-b212f3a73528------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b4f9e1d11d0</guid>
            <category><![CDATA[urban-sound]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[raw-audio]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Bruno Lima]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 18:59:49 GMT</pubDate>
            <atom:updated>2020-06-20T18:59:49.897Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>The recreation of the PyTorch tutorial for audio classification using the Fastai framework.</p><p><strong>Author</strong>: Bruno Lima &lt;https://github.com/limazix&gt;</p><ul><li><a href="https://github.com/pytorch/audio">torchaudio</a></li><li><a href="https://docs.fast.ai/">fastai</a></li></ul><p>First, let’s import the common packages pandas and numpy.</p><pre>%matplotlib inline<br>import os</pre><pre>import pandas as pd<br>import numpy as np</pre><h4>Importing the Dataset</h4><p>We will use the UrbanSound8K dataset to train our network. It is available for free here &lt;https://urbansounddataset.weebly.com/&gt;_ and contains 10 audio classes with over 8000 audio samples! Once you have downloaded the compressed dataset, extract it to your current working directory. First, we will look at the CSV file that provides information about the individual sound files. pandas allows us to open the CSV file and it uses the method <em>.iloc()</em> to access the data within it.</p><p>After the download at the data folder, let’s map the data paths into global variables.</p><pre>DATA_ROOT_DIR=os.path.normpath(os.path.join(os.getcwd(), &#39;data/UrbanSound8k&#39;))<br>DATA_META_FILE=os.path.join(DATA_ROOT_DIR, &#39;metadata/UrbanSound8k.csv&#39;)<br>DATA_AUDIO_DIR=os.path.join(DATA_ROOT_DIR, &#39;audio&#39;)</pre><pre>data_meta = pd.read_csv(DATA_META_FILE)<br>print(data_meta.iloc[0, :])</pre><pre>slice_file_name    100032-3-0-0.wav<br>fsID                         100032<br>start                             0<br>end                        0.317551<br>salience                          1<br>fold                              5<br>classID                           3<br>class                      dog_bark<br>Name: 0, dtype: object</pre><p>The 10 audio classes in the UrbanSound8K dataset are: air_conditioner, car_horn, children_playing, dog_bark, drilling, enginge_idling, gun_shot, jackhammer, siren, and street_music.</p><p>Each class has its own folder and id. For instance, the last print shows that the audio file has:</p><ul><li><strong>class</strong> — dog_bark</li><li><strong>id</strong> — 3</li><li><strong>folder</strong> — 5</li></ul><p>We will need the classID and the full file path only.</p><pre>def build_file_path(item):<br>    item[&#39;path&#39;] = &#39;fold{}/{}&#39;.format(item[&#39;fold&#39;], item[&#39;slice_file_name&#39;])<br>    item[&#39;label&#39;] = item[&#39;class&#39;]<br>    return item[[&#39;path&#39;, &#39;label&#39;]]</pre><pre>data = data_meta.apply(build_file_path, axis=1)<br>data.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 8732 entries, 0 to 8731<br>Data columns (total 2 columns):<br> #   Column  Non-Null Count  Dtype <br>---  ------  --------------  ----- <br> 0   path    8732 non-null   object<br> 1   label   8732 non-null   object<br>dtypes: object(2)<br>memory usage: 136.6+ KB</pre><h4>Fast.ai Data Structure</h4><p>In order to run DNN with Fast.ai, it’s necessary to create a DataBunch, the basic framework data structure.</p><p>The Fast.ai has a few built-in DataBanch, such as ImageDataBunch for image processing and TextDataBunch for NLP, but none for audio processing yet. Therefore, we’ll have to create a custom one.</p><p>The simplest way to do that is by using the ItemList and ItemBase classes. The first one creates a structure that allows operations to manipulate the dataset, while the second one defines the operation behavior for one single item.</p><pre>import torchaudio<br>from fastai.data_block import ItemList, ItemBase</pre><pre>class AudioItem(ItemBase):</pre><pre>    def apply_tfms(self, tfms):<br>        if not tfms: return self<br>        <br>        for t in tfms:<br>            self.data = t(self.data)<br>        return self<br>        <br>class AudioItemList(ItemList):<br>    <br>    def get(self, i):<br>        fn = super().get(i)<br>        file_path = os.path.join(self.path, fn)<br>        return self.open(file_path)</pre><pre>    def open(self, fn):<br>        audio, sample_rate = torchaudio.load(fn)<br>        return AudioItem(audio[0, :].view(1, -1))</pre><p>To keep it simple, we create two methods for the custom ItemList:</p><ul><li><strong>get</strong> — Method to retrieve one single item from the dataset given its position;</li><li><strong>open</strong> — Method used to load the audio file and build the AudioItem object.</li></ul><p>And one for the custom ItemBase:</p><ul><li><strong>apply_ftms</strong> — Method used to apply transformations in each data from the dataset.</li></ul><h4>Data Transformation</h4><p>Like any machine learning system, it’s necessary to perform a few preprocessing steps on the data in order to run the intent algorithm. The original tutorial performs three transformations:</p><ul><li>Resample — It performs a downsample from 44.1KHz to 8KHz</li><li>MaxClips — It uses a fixed sample size of 160000 clips by completing with zeros or remove when necessary</li><li>ClipFrequency — It group every 5th clip to the final sample and ignore de rest</li></ul><p>For the first transformation, the torchaudio library already has an implementation. But not for the last two, so we need to create then.</p><pre>import torch</pre><pre>class MaxClips(object):<br>    <br>    def __init__(self, max_clips):<br>        self.max_clips = max_clips</pre><pre>    def __call__(self, sound_base):</pre><pre>        sound_base = sound_base.long()</pre><pre>        #tempData accounts for audio clips that are too short<br>        sound = torch.zeros([self.max_clips, 1])<br>        if sound_base.numel() &lt; self.max_clips:<br>            sound[:sound_base.numel()] = sound_base.view(-1, 1)[:]<br>        else:<br>            sound[:] = sound_base.view(-1, 1)[:self.max_clips]</pre><pre>        return sound</pre><pre>class ClipFrequency(object):<br>    <br>    def __init__(self, size, frequency):<br>        self.frequency = frequency<br>        self.size = size<br>        <br>    def __call__(self, sound_base):<br>        sound = torch.zeros([self.size, 1])<br>        #take every fifth sample of soundData<br>        sound[:self.size] = sound_base[::self.frequency]<br>        sound = sound.permute(1, 0)<br>        <br>        return sound</pre><p>Now, we can create the transformation pipeline.</p><pre>from torchaudio.transforms import Resample</pre><pre>transforms = [<br>    Resample(orig_freq=44100, new_freq=8000),<br>    MaxClips(max_clips=160000),<br>    ClipFrequency(size=32000, frequency=5)<br>]<br>print(transforms)</pre><pre>[Resample(), &lt;__main__.MaxClips object at 0x12e1e2ef0&gt;, &lt;__main__.ClipFrequency object at 0x12e1e28d0&gt;]</pre><h4>DataBunch Creation</h4><p>We already have the minimum necessary to create the DataBunch. Here, we perform five operations:</p><ul><li><strong>from_df</strong> — It transforms the DataFrame with two columns into an AudioItemList instance;</li><li><strong>split_subsets</strong> — It splits the dataset in two, train and validation dataset, based on the given proportions;</li><li><strong>label_from_df</strong> — It informs the ItemList to use the column label from the dataset as the item class;</li><li><strong>transform</strong> — It applies the transformation pipeline to both datasets, train, and validation;</li><li><strong>databunch</strong> — It creates the databunch with a batch size of 128 inputs per batch</li></ul><pre>data_bunch = (AudioItemList.from_df(data, path=DATA_AUDIO_DIR)<br>              .split_subsets(train_size=0.8, valid_size=0.2)<br>              .label_from_df(cols=&#39;label&#39;)<br>              .transform((transforms, transforms))<br>              .databunch(bs=128))</pre><h4>Model</h4><p>The tutorial built de model class after the M5 CNN architecture for audio processing and classification as presented by <a href="https://arxiv.org/pdf/1610.00087.pdf">Wei Dai Et al.</a></p><pre>from torch import nn<br>from torch.functional import F</pre><pre>class M5Model(nn.Module):</pre><pre>    def __init__(self, n_classes):<br>        super(M5Model, self).__init__()<br>        self.conv1 = nn.Conv1d(1, 128, 80, 4)<br>        self.bn1 = nn.BatchNorm1d(128)<br>        self.pool1 = nn.MaxPool1d(4)<br>        self.conv2 = nn.Conv1d(128, 128, 3)<br>        self.bn2 = nn.BatchNorm1d(128)<br>        self.pool2 = nn.MaxPool1d(4)<br>        self.conv3 = nn.Conv1d(128, 256, 3)<br>        self.bn3 = nn.BatchNorm1d(256)<br>        self.pool3 = nn.MaxPool1d(4)<br>        self.conv4 = nn.Conv1d(256, 512, 3)<br>        self.bn4 = nn.BatchNorm1d(512)<br>        self.pool4 = nn.MaxPool1d(4)<br>        #input should be 512x30 so this outputs a 512x1<br>        self.avgPool = nn.AvgPool1d(30)<br>        self.fc1 = nn.Linear(512, n_classes)<br>        self.softmax = nn.LogSoftmax(dim=2)<br>        <br>    def forward(self, x):<br>        x = self.conv1(x)<br>        x = F.relu(self.bn1(x))<br>        x = self.pool1(x)<br>        x = self.conv2(x)<br>        x = F.relu(self.bn2(x))<br>        x = self.pool2(x)<br>        x = self.conv3(x)<br>        x = F.relu(self.bn3(x))<br>        x = self.pool3(x)<br>        x = self.conv4(x)<br>        x = F.relu(self.bn4(x))<br>        x = self.pool4(x)<br>        x = self.avgPool(x)<br>        #change the 512x1 to 1x512<br>        x = x.permute(0, 2, 1)<br>        x = self.fc1(x)<br>        return self.softmax(x)</pre><h4>Wrap-up</h4><p>After defined the databunch and the model, it is time to create the main responsible by the learning operations, the Learner.</p><p>Usually, with pytorch, that&#39;s the moment to define the optimizer, the learning rate(lr), the loss function and methods for training and testing for each epoch. All those things are defined manually.</p><p>With time, it becomes clear that not everything has to be custom made for each experiment scenario. The <a href="https://docs.fast.ai/basic_train.html#Learner">Learner</a> class provides all those setups already built-in and it uses the concept of partial to allow a few enhancements.</p><p>Tho original tutorial uses the Adan optimizer with lr 0.1. The Learner use the same optimizer by default but, if the experiment requests a different one, it can be changed by using the opt_func parament from the constructor. Likewise, the loss function with the parameter loss_func.</p><pre>from fastai.callbacks import EarlyStoppingCallback, ReduceLROnPlateauCallback<br>from fastai.metrics import accuracy, partial, error_rate<br>from fastai.basic_data import DataBunch<br>from fastai.basic_train import Learner</pre><pre>model = M5Model(n_classes=data_bunch.c)</pre><pre>learn = Learner(data_bunch, model, metrics=[error_rate, accuracy],<br>               callback_fns=[<br>                   partial(EarlyStoppingCallback, monitor=&#39;accuracy&#39;, patience=10, min_delta=5e-4),<br>                   partial(ReduceLROnPlateauCallback, monitor=&#39;accuracy&#39;, patience=5, factor=0.2, min_delta=0)<br>               ])</pre><p>It’s important to notice that the above setup is using error_rate and accuracy as metrics to evaluate the performance of the model while it performs the training and validation phases.</p><p>In addition, there are two partials:</p><ul><li><strong>EarlyStoppingCallback</strong> — It stops the training if a given metric, in this case accuracy, does not increase 5e-4 in 10 epochs</li><li><strong>ReduceLROnPlateauCallback</strong> — It changes the lr by 0.2 times if the accuracy does not increase in 5 epochs</li></ul><p>Those two partials avoid overtraining and it helps to escape from possible plateaus.</p><p>To run the training and the validation phases, the Learner has a method called fit. In the following example, it receives two parameters: the number of epochs and the lr.</p><pre>learn.fit(40, 0.01)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Z61mxlZHXpaC50qofiJkHA.png" /></figure><pre>Epoch 12: reducing lr to 0.002<br>Epoch 17: early stopping</pre><h4>Final Considerations</h4><p>It shows how simpler and cleaner is to wright using fast.ai even when no previous module exists, such as vision or text.</p><p>Now, it is possible to dig a little deeper into the audio processing universe using fast.ai. For the next article, I’ll try to improve the accuracy of the model used here by playing with the input data in the preprocessing phase and with the parameters in the training phase.</p><p>The notebook used in this tutorial is available <a href="https://github.com/limazix/audio-processing">here</a>.</p><p><strong>Ps.:</strong> If you find any error or misleading in this article, few free to contact me and make it better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b4f9e1d11d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>