<?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 Kumar Gaurav on Medium]]></title>
        <description><![CDATA[Stories by Kumar Gaurav on Medium]]></description>
        <link>https://medium.com/@krgaurav45?source=rss-1af63ce8da47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AhnJKChf0OOaJss8.jpg</url>
            <title>Stories by Kumar Gaurav on Medium</title>
            <link>https://medium.com/@krgaurav45?source=rss-1af63ce8da47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:14:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krgaurav45/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[Cornell Birdcall Identification]]></title>
            <link>https://medium.com/@krgaurav45/cornell-birdcall-identification-afc43ca90b13?source=rss-1af63ce8da47------2</link>
            <guid isPermaLink="false">https://medium.com/p/afc43ca90b13</guid>
            <category><![CDATA[birdcall-detection]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[audio-classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[birdcall-identification]]></category>
            <dc:creator><![CDATA[Kumar Gaurav]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 09:28:18 GMT</pubDate>
            <atom:updated>2020-09-26T09:28:18.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cornell Bird-call Identification</h3><p>Identifying the species of the bird based on the the sound(call) it makes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kbmEdwiZioUoJTKh.jpg" /><figcaption>Bird-Call Image</figcaption></figure><p>Do you hear the birds chirping outside your window? Over 10,000 bird species occur in the world, and they can be found in nearly every environment, from untouched rain forests to suburbs and even cities. Birds play an essential role in nature. They are high up in the food chain and integrate changes occurring at lower levels. As such, birds are excellent indicators of deteriorating habitat quality and environmental pollution. However, it is often easier to hear birds than see them. With proper sound detection and classification, researchers could automatically intuit factors about an area’s quality of life based on a changing bird population.</p><h3>Business Problem</h3><h4>Description</h4><p>There are already many projects underway to extensively monitor birds by continuously recording natural soundscapes over long periods. However, as many living and nonliving things make noise, the analysis of these datasets is often done manually by domain experts. These analyses are painstakingly slow, and results are often incomplete. Data science may be able to assist, so researchers have turned to large crowdsourced databases of focal recordings of birds to train AI models. Unfortunately, there is a domain mismatch between the training data (short recording of individual birds) and the soundscape recordings (long recordings with often multiple species calling at the same time) used in monitoring applications. This is one of the reasons why the performance of the currently used AI models has been subpar.</p><p>To unlock the full potential of these extensive and information-rich sound archives, researchers need good machine listeners to reliably extract as much information as possible to aid data-driven conservation.</p><p>The Cornell Lab of Ornithology’s Center for Conservation Bio-acoustics (CCB)’s mission is to collect and interpret sounds in nature. The CCB develops innovative conservation technologies to inspire and inform the conservation of wildlife and habitats globally. By partnering with the data science community, the CCB hopes to further its mission and improve the accuracy of soundscape analyses.</p><p>In this case study, we will identify a wide variety of bird vocalizations in soundscape recordings. Due to the complexity of the recordings, they contain weak labels. There might be anthropogenic sounds (e.g., airplane overflights) or other bird and non-bird (e.g., chipmunk) calls in the background, with a particular labeled bird species in the foreground. we will try to bring new ideas to build effective detectors and classifiers for analyzing complex soundscape recordings!</p><p>CREDITS:- <a href="http://www.kaggle.com/">Kaggle</a></p><h4>Problem Statement</h4><blockquote>For each time window, we need to predict the bird species that made a call beginning or ending in that time window. If there are no bird calls in a time window, we will predict no-call.</blockquote><h4>Real world/Business Objectives and Constraints</h4><blockquote>CPU Notebook &lt;= 9 hours run-time.<br>GPU Notebook &lt;= 2 hours run-time.<br>External data, freely &amp; publicly available, is allowed. This includes pre-trained models.</blockquote><p>Now that we have understood the problem that we are going to solve and constraints that we need to keep in mind. Let us have a look at the data that we are going to work with.</p><h3>Data</h3><h4><strong>Data Overview</strong></h4><p>The data is downloaded from <a href="https://www.kaggle.com/c/birdsong-recognition/data">kaggle’s birdcall identification competition</a>. The downloaded data is a zipped file which contains multiple files as described below.</p><h4><strong>train_audio</strong></h4><p>The train data consists of short recordings of individual bird calls collected with generous help of users of <a href="http://www.xenocanto.org/">xenocanto.org</a>.</p><h4><strong>test_audio</strong></h4><p>The hidden test_audio directory contains approximately 150 recordings in mp3 format, each roughly 10 minutes long. They will not all fit in a notebook’s memory at the same time. The recordings were taken at three separate remote locations in North America. Sites 1 and 2 were labeled in 5 second increments and need matching predictions, but due to the time consuming nature of the labeling process the site 3 files are only labeled at the file level. Accordingly, site 3 has relatively few rows in the test set and needs lower time resolution predictions.<br> Two example soundscapes from another data source are also provided to illustrate how the soundscapes are labeled and the hidden data set folder structure. The two example audio files are BLKFR-10-CPL_20190611_093000.pt540.mp3 and ORANGE-7-CAP_20190606_093000.pt623.mp3. These soundscapes were kindly provided by Jack Dumbacher of the California Academy of Science’s Department of Ornithology and Mammology.</p><h4><strong>test.csv</strong></h4><p>The test set csv file have the following columns:</p><ul><li>site: Site ID.</li><li>row_id: ID code for the row.</li><li>seconds: the second ending the time window, if any. Site 3 time windows cover the entire audio file and have null entries for seconds.</li><li>audio_id: ID code for the audio file.</li></ul><h4><strong>example_test_audio_metadata.csv</strong></h4><p>Complete metadata for the example test audio. These labels have higher time precision than is used for the hidden test set.</p><h4><strong>example_test_audio_summary.csv</strong></h4><p>Metadata for the example test audio, converted to the same format as used in the hidden test set.</p><ul><li>filename_seconds: a row identifier.</li><li>birds: all ebird codes present in the time window.</li><li>filename_seconds: the second ending the time window.</li></ul><h4><strong>train.csv</strong></h4><p>A wide range of metadata is provided for the training data. We will look at all the features of the train data in data analysis part in detail while the most directly relevant fields are:</p><ul><li>ebird_code: a code for the bird species. You can review detailed information about the bird codes by appending the code to <a href="https://ebird.org/species/">https://ebird.org/species/</a>, such as <a href="https://ebird.org/species/amecro">https://ebird.org/species/amecro</a> for the American Crow.</li><li>recordist: the user who provided the recording.</li><li>location: where the recording was taken. Some bird species may have local call ‘dialects’, so you may want to seek geographic diversity in your training data.</li><li>date: while some bird calls can be made year round, such as an alarm call, some are restricted to a specific season. You may want to seek temporal diversity in your training data.</li><li>filename: the name of the associated audio file.</li></ul><h3>First Cut Approach</h3><p>The main challenge of this case study is to identify which birds are calling in long recordings, given training data generated in meaningfully different contexts. This is the exact problem facing scientists trying to automate the remote monitoring of bird populations.</p><p>Based on the problem we are facing the first solution comes to the mind is to treat this one as a multi-class classification problem where for each time window we predict the species of bird that made a call in that audio sample, if no bird made a call we predict nocall. So, in simple words this is going to be an Audio classification problem similar to image classification problem where we classified the the image based on the objects of which the image is for example cat or dog in case of animal classification tasks. The difference as well as challenge is here that we need to do that for audio here.</p><p>Now that we know the problem, problem type and approach to solution, so let us decide the performance measure or error metric that we need to optimize and find best of it for the task.</p><h4>Performance Metric</h4><blockquote><a href="https://www.kaggle.com/c/birdsong-recognition/overview/evaluation"><strong>Row-wise micro averaged F1 score</strong></a></blockquote><blockquote>For a given recording, we predict the birds calling in the between a given time range and measure micro averaged f1-score for each recordings. There might be many birds call in a long recording.</blockquote><h3>Exploratory Data Analysis</h3><p>We have discussed the problem statement, constraints, brief solutions, metrics and had a glance of features data contains. So, let us dive deep into those features and look at what they have to say. In this section, I will take you through the exploratory analysis of the data. So, let us start by observing the features we have in our train data csv file.</p><pre>#   Column            Non-Null Count  Dtype  <br>---  ------            --------------  -----  <br> 0   rating            21375 non-null  float64<br> 1   playback_used     19575 non-null  object <br> 2   ebird_code        21375 non-null  object <br> 3   channels          21375 non-null  object <br> 4   date              21375 non-null  object <br> 5   pitch             21375 non-null  object <br> 6   duration          21375 non-null  int64  <br> 7   filename          21375 non-null  object <br> 8   speed             21375 non-null  object <br> 9   species           21375 non-null  object <br> 10  number_of_notes   21375 non-null  object <br> 11  title             21375 non-null  object <br> 12  secondary_labels  21375 non-null  object <br> 13  bird_seen         19575 non-null  object <br> 14  sci_name          21375 non-null  object <br> 15  location          21375 non-null  object <br> 16  latitude          21375 non-null  object <br> 17  sampling_rate     21375 non-null  object <br> 18  type              21375 non-null  object <br> 19  elevation         21375 non-null  object <br> 20  description       15176 non-null  object <br> 21  bitrate_of_mp3    21367 non-null  object <br> 22  file_type         21375 non-null  object <br> 23  volume            21375 non-null  object <br> 24  background        8300 non-null   object <br> 25  xc_id             21375 non-null  int64  <br> 26  url               21375 non-null  object <br> 27  country           21375 non-null  object <br> 28  author            21375 non-null  object <br> 29  primary_label     21375 non-null  object <br> 30  longitude         21375 non-null  object <br> 31  length            21375 non-null  object <br> 32  time              21375 non-null  object <br> 33  recordist         21375 non-null  object <br> 34  license           21375 non-null  object <br>dtypes: float64(1), int64(2), object(32)</pre><p>The above table shows the features present in the data frame with its datatype and number of instances. The maximum number of instance present in the data frame is 21375 suggesting that we have around 21375 recordings belonging to different bird’s call. From the table we gather that the these columns mainly describe the audio files that we have collected and gives the idea of our class labels from the column species and ebird_code. Now that we have talked about our class labels let us look at that next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*J1tn6lfaOCOg90v9zAYN5A.png" /><figcaption>Checking Bird Species</figcaption></figure><p>The above code snippet finds the number of unique bird species we have in the data frame. From the output we found that we have recordings of 264 different bird species present in the data. Also, from the second output in the snippet we observe that the bird species are abbreviated to ebird code of length 6 alphabets for ease of labeling and readability. For example, <strong>Alder Flycatcher</strong> species is abbreviated as <strong>aldfly</strong> where the first three letter is taken from word Alder while last three from Flycatcher. Similarly, <strong>American Avocet</strong> as <strong>ameavo</strong> in the same manner. To learn more about class labels let us look at the distribution of the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*2IPNhX4rhbbf5OAHz6skcw.png" /><figcaption>distribution of class labels</figcaption></figure><p>The distributions above shows the number of the instances present for bird species. From we the plot we observe that maximum recordings/instance present for a single bird is 100. Around 40% of the 264 bird species have less than 90 recordings present for them in the data set.</p><p>Let us look at the other features of data now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*rm6NUIM4Hjtp75rq6jj3Ig.png" /></figure><p>The plot describes the distribution of the audio recordings. From the plot we can see that 75% of the audio recordings provided for the training are of rating greater than 3 indicating the good quality of the audio recordings. Among them, 5 being the highest rating given is the rating which is given to around 6000 of the recordings out of 21k recordings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*6l59sQaE6dwO0xk-l_HqPQ.png" /></figure><p>Let us look at the distribution of the pitch of the sound. <strong>Pitch</strong>:-The sensation of a frequency is commonly referred to as the pitch of a sound. A high pitch sound corresponds to a high frequency sound wave and a low pitch sound corresponds to a low frequency sound wave. Generally, we have low and high pitch sound but as shown in graph, more than 70% of the recordings provided does not give any info on the pitch of the sound i.e is it either increasing or decreasing. For some examples less than 2%, the pitch is specified as increasing or decreasing meaning some birds call is a high pitched sound while for some it is low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*w_0d4va0BEafWkwiUmh5Nw.png" /></figure><p>The above plot shows the types of channels used in the recordings. Basically, number of channels used is the number of signals in the sound.</p><p><a href="https://music.stackexchange.com/questions/24631/what-is-the-difference-between-mono-and-stereo">https://music.stackexchange.com/questions/24631/what-is-the-difference-between-mono-and-stereo</a><br>In monaural sound one single channel is used. It can be reproduced through several speakers, but all speakers are still reproducing the same copy of the signal.<br>In stereophonic sound more channels are used (typically two). You can use two different channels and make one feed one speaker and the second channel feed a second speaker (which is the most common stereo setup). This is used to create directionality, perspective, space.<br>So, from our plot we observe that more than 50% of the data have recordings with number of channels as 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*DGo7fRRr_E0m8TKwC5jSTg.png" /></figure><p>The playback used in the audio is similar to the feedback concept meaning it is way to reproduce audio, video recording to recheck them. The playback not used in the audio means that the audio recorded has not been reproduced or altered and is provided as it is. As from our distribution above we can see that around 18000 out of 21000 recordings provided have not used playback audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*vLycNvz96FjGq_ZI45yNzw.png" /></figure><p>The distribution plot above shows the files available in the data set is recorded at what speed i.e normal, fast forwarded or in slow mode. From the plot we observe that similar to pitch distribution, most of them is not specified. Around 70% of them belongs to the column not specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*upabkCKhZLGLUdtUotiH0g.png" /></figure><p>The plot above shows the year in which the recordings of the bird call is made. From the plot it is observed that 90% of the recordings have made in the last 10 years or so while year 2014 being the year when highest number(around 14% of the total) of the recordings has been done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*U1uY_QYdfQiWo-dM9NN15Q.png" /></figure><p>This plot distribution shows the month in which the recordings has been done or the month in which birds called or sang. From the plot it is observed that 80% of the bird’s call is from the months March to August i.e 6 months interval which suggests that the most of the birds called during season `<strong>Spring</strong>` March to May and `<strong>Summer</strong>` June to Aug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*jUfebfegbxBPDn0v0IbKuA.png" /></figure><p>The plot titled `Top 10 countries where recording is done` shows top 10 countries where recordings has been done based on the number of recordings per country. From the plot it is obvious that around 70% of the recordings is from USA and more than 75% from the North America continent itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*RkRJo__BmjGwNwQTpcRWng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*cf4ydH6RHm1JAVN5prOySA.png" /></figure><p>The plot titled `<strong>Recordings File Types</strong>` is plot showing the distribution of file types of the recordings. From the plot it is evident that the the recordings are available in four types of file:- mp3, wav, aac and mp2. But, around 99% of the recordings provided are in mp3 format.</p><p>The plot titled `<strong>sampling rate</strong>` show the distribution of sampling rate at which the recordings has been sampled i.e the number of samples of audio carried per second, measured in Hz or kHz. From the graph we can see that recordings we have contains 8 types of sampling rate while more than 95% of them are sampled at 44100 and 48000 Hz. The sampling rate at which most of the recordings is made is 44100 Hz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*UWqUrjRyICZmptGSru_ZPQ.png" /></figure><p>The duration distribution plot above is done to observe the duration of the recordings file. The distribution starts at 0 and is rightly skewed. The minimum duration of the recordings is 0 seconds and around 70% of the recordings duration is below 100 seconds, while around 99% of recordings have duration less than 500 seconds.<br>From the above distribution plots titled `<strong>Distribution of duration of audio files</strong>` and `<strong>Commulative distribution of Duration</strong>`respectively we observe that 98% of the data is less than 250 seconds long while 99 percent of the data is less than 500 seconds (8 minutes) long. <br>To have a clear idea we printed the percentiles of the duration and observed that 90 percent of the data is around 2 minutes long in length.</p><p>Now, We have looked at almost all the important features of the data frame and have idea of data that we are dealing with. So, let us keep the pace and see some feature extraction technique which can help in converting/extracting these audio recordings into features which can be used to train classification model on it.</p><h3>Feature Extraction</h3><p>To extract and load these audio files we will be using the librosa library which is have similar audio processing functions to scipy. The librosa is chosen over other audio processing library is because of its functionality to load various types of audio files as well as fast processing. The library also have some beautiful audio processing technique like short term Fourier transform and spectrogram and many more but we will only focus on some of the techniques here.</p><p>Before we go deep into feature extraction let us understand the simple processing librosa do while loading an audio file. The librosa library load the audio files into two major components:<br>1. <strong>Sound(samples) :</strong> sequence of vibrations in varying pressure strengths as array of numbers<br>2. <strong>Sample Rate </strong>: (sample_rate) is the number of samples of audio carried per second, measured in Hz or kHz</p><p>let us look at code snippet and output we get after loading an audio file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*2BKdtNeEGEfEY6GWsPwVUg.png" /><figcaption>loading and sampling audio</figcaption></figure><p>Here, we used librosa load function to read the audio files. The load function takes two arguments audio file path and sample rate at which it samples the audio file and returns array of samples and the sample rate. As observed, we used sample rate of 44100Hz that means we sampled 44100 samples per second from the audio file. From the the analysis we found that most of audio given in the data set is sampled at 44100Hz and according the reference papers of audio processing we found 44100Hz to be the standard sampling rate. So, we will go ahead with this sampling rate for our data processing. The samples is an array of shape (1601280,) got using sample_rate multiplied by duration of the file. <br>As seen above the duration of the audio files differ so we will get different and much larger or even smaller samples array for every file.</p><p>let us understand the sound waves graphically for better understanding as they say human’s perceive better with visuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*_CY9AR3sRLjGkIpLDrf_Kg.png" /></figure><p>Now, we observed above that we now samples array for audio files but we cannot say anything from that expect the duration and sampling rate of the audio. So, we plotted 2D representation of the audio signal where x-axis represents time and y-axis represents the amplitude of the sound wave at that time. From the first plot we see some spike in the graph which suggests the presence of the bird sound at that point. The plot shows some points where the amplitude decreases that suggests that the bird is not calling continuously or that it’s pitch differ for the entire call.</p><p>So, it might be possible that we can get the bird call in smaller samples i.e smaller duration of the file. let us check our theory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*KJaf603snYxiBOP1KAlZSQ.png" /></figure><p>Yeah, from the plot we observe that we are correct with our theory. Even the smaller samples have the bird calls. As we know generally bird calls are short while their song is long which is also verified by this graph. Now, that we can have bird calls in smaller duration we can divide the files in 5 seconds sample each and check for the presence of the call and in this way we can have equal sample size for every bird’s call which will help in data preparation during our model training. let us look at some more ways of processing audio and see we can find some more insights.</p><p>We have observed the sound waves in 2D representation where we saw the variation of amplitude with time. Now, we will look at some other features of the sound waves where the other parameters like frequency varies with time.</p><h4>Spectrogram</h4><p>We have seen 2D representation of audio in the above plot which does not describe anything more about the sound recording rather than its frequency and amplitude. so, to explore more about the audio files we came across another sound features called spectrogram. According to Wikipedia, A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. When applied to an audio signal, spectrograms are sometimes called sonographs, voiceprints, or voicegrams.</p><p>Spectrograms are used extensively in the fields of music, linguistics, sonar, radar, speech processing,seismology, and others. Spectrograms of audio can be used to identify spoken words phonetically, and to analyze the various calls of animals. A spectrogram can be generated by an optical spectrometer, a bank of band-pass filters, by Fourier transform.</p><p>A spectrogram is usually depicted as a heat map, i.e., as an image with the intensity shown by varying the color or brightness.</p><p>As learned above, spectrogram can be generated by many methods and one of them is Fourier transform. let us learn more about fourier transform as it is widely used mathematical method to generate spectrogram from audio recordings.</p><p>In simple terms, sound is a sequence of vibrations over time which we have seen through above plot. Fourier transform is another mathematical way of representing sound.<br>In mathematics, a Fourier transform (FT) is a mathematical transform that decomposes a function (often a function of time, or a signal) into its constituent frequencies, such as the expression of a musical chord in terms of the volumes and frequencies of its constituent notes. The term Fourier transform refers to both the frequency domain representation and the mathematical operation that associates the frequency domain representation to a function of time.<br>So, let us see how FT affects the sound wave from below operations on the aldfly audio call.</p><p><a href="https://musicinformationretrieval.com/stft.html"><strong>Short-Time Fourier Transform</strong></a><br>Musical signals are highly non-stationary, i.e., their statistics change over time. It would be rather meaningless to compute a single Fourier transform over the entire song length.</p><p>The short-time Fourier transform (STFT) (Wikipedia; FMP, p. 53) is obtained by computing the Fourier transform for successive frames in a signal.</p><p>X(m,ω)=∑nx(n)w(n−m)e−jωn<br> <br>As we increase m , we slide the window function w to the right. For the resulting frame, x(n)w(n−m) , we compute the Fourier transform. Therefore, the STFT X is a function of both time, m , and frequency, ω .</p><p><strong>librosa.stft computes a STFT. We provide it a frame size, i.e. the size of the FFT, and a hop length, i.e. the frame increment</strong> and plot the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*j_YrWRuw7RhBUGjy3WEkSQ.png" /></figure><p>Yes I know we cannot make much sense out of this image. So, let us see what we can do to achieve more. In music processing, we often only care about the spectral magnitude and not the phase content.<br>And as defined above the spectrogram shows the the intensity of frequencies over time. A spectrogram is simply the squared magnitude of the STFT(X) which we calculated above:</p><p>S(m,ω)=|X(m,ω)|2</p><p>But there is one more thing the human perception of sound intensity is logarithmic in nature i.e we cannot visualize and make sense to a sound out of a certain frequency range. Therefore, we are often interested in the log amplitude. so, we convert the output to log scale and plot it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*SbiAdXPNxYep8N6VUZ8D3A.png" /></figure><p>This is what a spectrogram is. we can see the call part of the audio as highlighted and rest are dark.</p><h4><strong>Mel-Spectrogram</strong></h4><p>When we applied log transformation to the STFT(short time fourier transform), we got the above spectrogram. So, how is this Mel-spectrogram different than that. Actually, The Mel-spectrogram is a normal Spectrogram, but with a Mel Scale on the y axis rather than log scale where the <strong>Mel Scale</strong>, mathematically speaking, is the result of some non-linear transformation of the frequency scale. <br>We can use Mel spectrogram feature of librosa library to easily get this feature of the audio signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*4OH_7K_usm6KiYUdEifxuw.png" /></figure><p>We can clearly see the changes from the previous plot. Here, we have used Mel scale for y-axis rather than linear as used in the previous approach. We have learnt about quite a features like Fourier transform, spectrogram and Mel-spectrogram. It is now time to understand how can be use these features properly.</p><p>From the pre-processing part we have found that 5 seconds samples contain the bird’s call. So, let us go ahead and check the spectrogram features for these samples and also verify some other parameters like frequency and window length etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a17015862d6c94a3140cf325e1e8b5c4/href">https://medium.com/media/a17015862d6c94a3140cf325e1e8b5c4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*9WPe8fsBee5C_MVKV4dO9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*-SdDHIQXRNhXB_KEEz6v1w.png" /></figure><p>The above two plots are the <strong>Mel-spectrogram feature for the 5 seconds</strong> audio samples. The parameters we used above like n_fft(window length) and hop length are referenced from the audio pre-processing paper and the parameters used above is found to be working best so, we plotted the final ones using them.</p><p>Also, in the first plot we used n_mels=128 and in second one we used n_mels=256 while the frequency below 20Hz and above 16000Hz is discarded as this range is the human’s hearing range. From the plots above we see that the first graph looks good where the bright contrasting bell shape shows the presence of the bird call. While the second plot looks same to first one but we have some lines and distortion in lower half part suggesting that the higher number of mels introduces the distortion in the image. So, we can conclude that the spectrogram with n_fft=1024, hop_length=512, n_mels=128 and freq range of 20–16000Hz gives the best features for the audio and we have our bird’s call properly represented. let us summarize what we gathered so far.</p><h3>Observation on EDA and Feature Extraction</h3><p>1. We have 264 unique bird species in our data.<br>2. 50% of the bird species have 100 recordings per bird while rest of them have recordings between 1 to 100 available to us.<br>3. Recordings contain bird call, songs and many different kind of bird sounds as well as background sounds.<br>4. Pitch and speed of the audio is not specified in the data for 90% of them.<br>5. 90% of the recordings provided has been rated more than 3 where 1 being the least and 5 being the highest.<br>6. Most of the bird call were recorded in the Spring and Summer season of North America:- USA, Canada and Mexico, USA being the country where highest number of recordings has been done for past 9 years from 2011 to 2019.<br>7. The minimum duration of the recorded audio is zero seconds while 85% of them having duration less than 100 seconds.<br>8. 99% of the recordings provided is of mp3 format with more than 55% of them having sampling rate of 44100 Hz.</p><p>Moving ahead let us see what we observed in FE part:-<br>1. librosa library is used to load and process the data<br>2. librosa load the sound as sequence of vibrations stored in form of ndarray and sample rate, the rate at which the sound is processed.<br>3. We have learned how to visualize sound wave in 2D representation with time on x-axis and amplitude of the sound on y-axis.<br>4. Using librosa we extracted many features from sound like zero crossing rate( the number of times the waves crossed horizontal x-axis) and for the Alder Flycatcher’s call sound crossed the horizontal x-axis 431290 times.<br>5. We observed how to convert audio signals into image using spectrogram feature of the sound waves.<br>6. Fourier transform a mathematical way to convert sound wave from time domain to frequency domain plays an important role in these feature generation.<br>7. Another important feature Mel-spectrogram is observed which is the same as spectrogram but is calculated on Mel scale rather than a log scale. And provides more readable image than the previous as observed.<br>8. Features like harmonics and perceptual helped us in learning the pitch and color of the sound.<br>9. We learned that we can use 5 seconds sample of the audio file instead of using the whole audio at a time which can cause size mismatch for each file and we might need to put extra efforts in padding the sequence.<br>10. The 5 seconds sample is taken after analyzing file for less than 5 seconds sample and found that 5 seconds is optimal duration and every audio contains bird’s call in this interval. So, we should not run into silence or noise sample only.<br>11. The Mel-spectrogram with n_mels=128 and signal between 20–16000 Hz showed the best image feature of the 5 seconds sample audio and we observe the presence of the sound quite clearly.<br>12. The frequency range is decided from the harmonics and 2d-representation of the sound where we found that this range has minimum distortion.</p><h3>Data Preparation</h3><p>Now, that we have learnt about the features that can be generated from an audio files. we can go ahead and prepare data accordingly. As per research done in audio classification we have found that LSTM and CNN models are widely used for this type of task. But for CNN we know that we need data either text or image and for LSTM it needs to be sequential data. So, as per our requirements we decide to generate the raw samples generated by librosa and spectrogram data as sequence data for LSTM model while we will convert the spectrogram to image feature by stacking it to 3-dimensions. Also, we have our class labels as ebird code which we converted to integer values as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddf85313dc3d16eb99878667b9ff0654/href">https://medium.com/media/ddf85313dc3d16eb99878667b9ff0654/href</a></iframe><p>As per the discussions above, we will sample the files for 5 seconds duration and generate the features for it and store them as compressed npz file with data and labels. We used batches of 32 audio file at a time to generate the data and store it in npz file. Look at below code snippet to understand what I did.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e4112cf5f612af49a0bb123efd31840/href">https://medium.com/media/2e4112cf5f612af49a0bb123efd31840/href</a></iframe><p>So, we have created data loader which loads the data in batches process it, extract features make it ready for model use. It is time to go ahead and experiment with some classification task models and observe the results. But, before that let us have a look at some of the augmentation techniques which might come in handy in improving the data samples as well as performance of the models.</p><h4>Data Augmentation</h4><p><strong>Data augmentation</strong> is a strategy that enables practitioners to significantly increase the diversity of <strong>data</strong> available for training models, without actually collecting new data. <strong>Data augmentation</strong> techniques such as cropping, padding, and horizontal flipping are commonly used to train large neural networks in case we are having image data. But, unfortunately we have sound data, wait don’t worry, thanks to domain experts we have various data augmentation techniques for sound data as well and among them the most widely used ones are time stretching, pitch shifting and frequency stretching.</p><p>Before going further let us understand these techniques first. According to Wikipedia, <strong>Time stretching</strong> is the process of changing the speed or duration of an <a href="https://en.wikipedia.org/wiki/Audio_signal_processing">audio signal</a> without affecting its <a href="https://en.wikipedia.org/wiki/Pitch_(music)">pitch</a>. <strong>Pitch scaling</strong> is the opposite: the process of changing the pitch without affecting the speed. <a href="https://en.wikipedia.org/wiki/Pitch_shift">Pitch shift</a> is pitch scaling implemented in an <a href="https://en.wikipedia.org/wiki/Effects_unit">effects unit</a> and intended for live performance.</p><p>For our task, we used addition of some white noise, reducing the background noise, time stretching and pitch shifting techniques as these are found to be giving the best results which we will further verify in our model training section. We can easily implement these techniques using the audiomentations transform functionality as shown in the below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7433fe973c9d835c4f19be0a5c875100/href">https://medium.com/media/7433fe973c9d835c4f19be0a5c875100/href</a></iframe><p>As seen in the above code snippet we increased/decreased the time by 30 percentage while for pitch we shifted it by 5 percentage only as large shift is observed to be causing noticeable change in the file which we don’t want as these could impact the model in a bad way.</p><h3>Modeling</h3><p>There is no certain rule to know which model will work best on the data and we have and hence it is important to play with some models related to the context of the problems and observe which is performing best and then go for it. We start our experiment with some machine learning models like decision tree and random forest but found that sue to the complexity of the data, it is taking a lot of time for them to train as well as the results we achieved is poor than our simple neural network model which will see below. Hence, we decided to experiment with some of the famous neural network architecture as well as come up with some of other deep learning models of our own. The models we experiment with are:</p><ol><li>Different LSTM Architectures</li><li>VGG16</li><li>ResNet50</li><li>Inceptionv3</li><li>DenseNet</li><li>Ensemble of one or two CNN Architectures</li></ol><p>They are discussed in more details below.</p><h4>LSTM Architectures</h4><p>Now that we have done feature extraction, created data loading pipeline it ti time to decide some more things before we go and build neural network model and start training. we now have a idea of what will be the input and what will be the output for our model the performance metric we want to maximize as discussed in above metrics sections. Also, we need to decide what will be the loss we will minimize while training. So, let us discuss these things before we go ahead and discuss the model architecture and training. Since we are dealing with a multi-label classification we will go with binary cross-entropy loss for each 264 classed and then get its average. The performance metric we will use is f1-score with weighted average technique. To keep track of the parameters during training we will be using various callbacks like changing the learning rate if the update is not happening significantly, saving model at checkpoints to avoid re-training as well as early stopping to stop the training we have achieved the results beforehand. The below code snippets describes the implementations all these mentioned loss, metrics and callbacks things.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a32e86f0345db10e8a4496d4815e0501/href">https://medium.com/media/a32e86f0345db10e8a4496d4815e0501/href</a></iframe><p>Since, we are working with a multi-class multi-label classification, we want our model to take as input the processed audio file and give as output the class to which the data belongs to. Now, we have 264 class labels so we will create a simple 4-layer LSTM network which takes 3D input of shape (batch_size, sequence length, time-step) and output sigmoid probabilities of each 264 classes. let us have a look at the model creation and training in below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a61618131f13bbb88005d42ab09d48/href">https://medium.com/media/14a61618131f13bbb88005d42ab09d48/href</a></iframe><p>The above code shows how to build a model, define relevant callbacks to keep track of the training of the model, defining your own metrics as per your requirement, compiling your model and finally training in the same order. In the above model you see that we used output layer, metrics and callbacks as specified above.</p><p>The model is trained for 20 epochs with adam optimizer and learning rate 0.01 which is found to be working best among all the other parameters in previous trainings. We used the weighted f1-score and averaged binary cross-entropy loss as metrics for the model as we have multi-label outputs. The result found at the end of the training is 0.12 f1-score which is better than nothing so, let us go ahead and experiment with some more models and check the performance.</p><h4>Another LSTM based Architecture</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e54f84d8a417cf117145ce2bd4d0eb59/href">https://medium.com/media/e54f84d8a417cf117145ce2bd4d0eb59/href</a></iframe><p>As learned from previous model, we still go with LSTM models but changed some layers in this model. Also, instead of taking raw data as input we decided to go with spectrogram features extracted from the audios while processing. So, now the input data to the model is spectrograms generated for 5 seconds sample for which 50 samples taken at a time of shape (batch, 128, 50) and output is 264 class sigmoid layer to get probability for each class.</p><p>The best initialization is found to be glorat with relu activation and adam optimizer with 0.01 learning rate. The model is trained similar to previous one with best parameters as well as regularization introduced between layers like batch normalization and dropout with whole training data and the results are observed. The results obtained is better than previous model. We have achieved quite good result here from the previous model.</p><p>In this approach we used LSTM network on spectrogram data but only for 50 samples per 5 seconds sample and found that we achieved better results. So, we decided to again train this same architecture with full spectrogram for 5 seconds sample of the audio file. We tried the same network with small change in the input layer to shape (None, 128, 451). The model is trained in batch of 10 epochs each for around 5 times and results is observed. We used reduceLRonplateau callback to track the learning rate while training, we used other callbacks too to keep an eye on the training. The results obtained is better than the previous one but we don’t see any significant improvement. So, let us experiment with some different architectures.</p><h4>VGG16</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2785757cef3ab6dcf2341445e1dd3d6a/href">https://medium.com/media/2785757cef3ab6dcf2341445e1dd3d6a/href</a></iframe><p>The above code shows implementation of the VGG16 model. We used this model architecture as feature extractor for our spectrogram and Mel-spectrogram data and then trained simple NN architecture for the classification purpose. The model trained on both spectrogram and Mel-spec found to performing better than the previous results with score 0.54 and 0.69 respectively suggesting that the CNN models are working well and even better with Mel-spec images. To further improve and verify our results let us try some more complex networks.</p><h4>ResNet50</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc4b35e0d9f6cf4bdf5275189254244/href">https://medium.com/media/ebc4b35e0d9f6cf4bdf5275189254244/href</a></iframe><p>Here, We tried the famous ResNet50 architecture to try some more complex network than VGG16. We used this architecture as feature extractor and trained similarly to previous model with spec and Mel-spec images and got score as 0.44 and 0.72 respectively. From the results obtained we found that the model is performing better than VGG for Mel-spec input while worsen for the spec image data. To understand if this is due to complexity in architecture or the spec feature itself, let us train some more complex architecture.</p><h4>Inceptionv3</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfa37ba34aa2ee42c73da43d08685f51/href">https://medium.com/media/cfa37ba34aa2ee42c73da43d08685f51/href</a></iframe><p>As observed from previous results, we tried another deep CNN architecture InceptionV3 similar to the previous approach. We tried and evaluated the model for both spec and Mel-spec images and got the score as 0.56 and 0.67 respectively. We observe that the InceptionV3 gives better result for spec images than ResNet but not that significant suggesting that the feature itself is not helping much in learning of the model. While the score for Mel-spec features for InceptionV3 decreased than that of ResNet50, to verify if it is due the complexity of the architecture we decide to go with deep CNNs like DenseNet.</p><h4>DenseNet</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda49014232f7468371e5c2b7e3e18ce/href">https://medium.com/media/cda49014232f7468371e5c2b7e3e18ce/href</a></iframe><p>To further verify our observation of the InceptionV3, we trained a deep CNN dense-net model and found that yes the more complex models is not performing better than that of our previous models with score we got around 0.48. Now, that we have observed that ResNet with Mel-spec images features and is performing best among all but the score we achieved is not that promising. So, to further improve our score we decided to try ensembling some of these good performing models. Let us see how can we combine these models and achieve more.</p><h4>Ensembles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*w_MFiXkRZ-xKx_q8A838rA.png" /></figure><p>To ensemble the multiple architectures, we referred the above attached image and tried various combination. For example, we used the ResNet and VGG, ResNet and Inception as well as Inception and VGG for either feature extractor and did feature fusion on extracted features or result fusion on the results obtained by these individual models depending on the shape of the extracted features or result we got from each model architecture. The below code snippet shows an example of the ensemble model we tried.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f671265ca8980136b547b5c35a664e3a/href">https://medium.com/media/f671265ca8980136b547b5c35a664e3a/href</a></iframe><p>Now, for the outputs we got from either the feature fusion or result fusion we tried some machine learning algorithms or simple NN architectures with sigmoid activation to get the prediction. The results we obtained from ML models is around 0.57 suggesting that they are not learning well either due to the complex features generated by these architectures or the amount of data.</p><p>So, we take our focus to the other method where we observe that ensembles with result fusion with sigmoid activation as last layer are doing good with best score of 0.76 which is indeed better than our previous best achieved by ResNet50 while the ensemble with feature fusion of ResNet50 and VGG16 on Mel-spec images have achieved the best results of all with average f1-score of 0.83.</p><h3>Conclusion</h3><p>We have done a lot of things including model implementation and training. So,let us conclude what we have done and observed so far.<br>1. We used raw audio samples, spectrogram images and Mel-spectrogram images for processed features.<br>2. The low and high frequency have been removed from the data.<br>3. In Mel-spectrogram data the Mel values is converted to power scale with exp value 0.5 to reduce the background noises.<br>4. Augmentation is done with introduction of Gaussian noise, white noise and pitch shifting of the audio.<br>5. These augmentations is implemented with the help of audiomentations library.<br>6. The Mel-spec and spectrogram images are extracted as 5 seconds clip and is properly normalized, cropped/padded etc. while feeding to the training.<br>7. The Mel-spec and spectrogram images extracted is stacked to make is usable by the CNN architectures.<br>8. Keras sequence generator and data loader is used to the load the data in batches while training and evaluation.<br>9. Multiple networks are used during training and their performance is observed as shown in the above summary table.<br>10. The first part of the table shows the networks trained with raw data and spectrogram data with LSTM and CNN architectures.<br>11. As shown in the first part of the summary table not too complex and deep 3-layered with 32 LSTM units network with proper dropout and batch normalization is trained with spectrogram and raw data. They achieved quite good results up-to 0.34 f1-score until we experiment with CNN models.<br>12. From CNN architectures to deep CNN we tried four different CNN architectures like VGG16, ResNet50, InceptionV3, and Dense Net. The deep CNN&#39;s seemed to be not performing as good as the other architectures as shown in the table.<br>13. The Inception architecture is found to be working best for the spectrogram images data with around 0.56 f1-score and ResNet and VGG comparatively good with around 0.54 score.<br>14. The ML ensemble models trained on the features extracted by these CNN models seemed to achieve good results but does not meet our expectations.</p><p>15. Failing to achieve performance more than 60%, we tried these same CNN architectures with some custom ensembling and combination but with different features i.e Mel-spectrogram data and some augmentation as well. <br>16. The same models for this feature data seemed to be performing well as you can verify from the results in the summary table.<br>17. The VGG16 model achieved the better result from models from part 1 with around 69% performance score.<br>18. Among all the single architectures the ResNet50 achieves the best result of around 0.72% score with Inception trying to keep up with only 0.67% score.<br>19. We tried ensembling the features and output generated by these models one by as shown in the summary table.<br>20. Two of the best performing networks like VGG16 and ResNet50 when their features is combined together to train another model to classify the calls achieves the best results of 0.83 f1-score.<br>21. Other ensembles do good as well as can be seen in the summary table.We tried every combination like VGG with ResNet, inception, and ResNet with inception so that we can know what is working well and what is not.</p><p>Now, that we have discussed what worked and best let us discuss what did not work.</p><p>1. The simple LSTM network trained is found to performing worst of all with around 0.12 f1-score as shown in the summary table.<br>2. Among all the optimizers and learning rate adam with learning rate 0.001 worked best for almost all the models while sgd and adadelta behaved poorly except for some models as shown in the summary table.<br>3. Only the good performing training results for each individual model is here in the notebook as the bad performing ones are overwritten with each training sequence.<br>4. Spectrograms performed poor that Mel-spectrogram as the later reduced the background noise and low and high frequency sound from the audio.<br>5. Ensembling of features generated by VGG and other CNN networks with spec and Mel-spec data performed poorly due to the difference in input shape(spec and Mel-spec) as well as and features shape generated by the last conv block except for the ResNet and VGG which achieved best results due to their similarity in the architectures. <br>6. The ML ensembles did not work well due the complexity of the features generated by the networks.<br>7. Overall LSTMs performed poor due to inconsistency in the audio files like presence of noise, background sounds and even no sound at all as well as discontinuous calls.</p><h3>Existing Approaches and Improvement</h3><p>Now, that we have discussed and observed our approach quite closely, it is time to discuss if we have made improvements to the existing approaches if we have any.</p><p>The Existing approach we have referenced have used resnet50 CNN network trained on the spectrogram generated for the audio files which has achieved average mAP of around 0.54. Here, we tried various models as shown above and found that our Inception model achieved better results than the existing approach. We achieved best result of around 0.83 f1-score.</p><h3>Summary</h3><p>Now, that we have covered almost all the aspects of the case study from data processing, analysis to model building and training. We have also concluded what we have learnt so far in the above section. Therefore, let us summarize the results for better and easy understanding of the our approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*wW24OpNIz1h3kMfc7LE5hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*HQqWdSBi1hklig2ZJMrVpQ.png" /></figure><p>The above two tables shows the results we obtained with each model and hyper parameters we tried.</p><blockquote><strong><em>For the full implementation of the case study</em></strong></blockquote><blockquote><em>Refer this </em><a href="https://github.com/krgaurav45/Birdcall-Identification"><strong><em>GitHub repository</em></strong></a><em>. For any queries, connect with me on </em><a href="https://www.linkedin.com/in/krgaurav45"><strong><em>LinkedIn </em></strong></a><em>and </em><a href="https://github.com/krgaurav45/"><strong><em>GitHub</em></strong></a><em>.</em></blockquote><h3>Future Works</h3><p>Before going away let us also have a look at if we missed something or we couldn’t do because of some limitations.</p><p>As, while training and evaluation we have found that when we introduced more background sounds and noise mostly overlapping with the bird calls and found that the model does not generalizes well and give even poorer results. So, We can gather some more data like these and train the models again for these outlier data. More deep and tuned LSTM networks as well as other Convolution networks like Efficient Net and XceptionNet can be tried as CNN networks like Res-Nets have been found to be working best. Tuning parameters and data augmentation techniques can be tried to achieve better results.</p><h3>References</h3><ol><li>Source:- <a href="https://www.kaggle.com/c/birdsong-recognition">https://www.kaggle.com/c/birdsong-recognition</a></li><li>Data:- <a href="https://www.kaggle.com/c/birdsong-recognition/data">https://www.kaggle.com/c/birdsong-recognition/data</a></li><li><a href="https://www.kaggle.com/c/birdsong-recognition/discussion/158933">https://www.kaggle.com/c/birdsong-recognition/discussion/158933</a></li><li><a href="https://www.kaggle.com/c/birdsong-recognition/discussion/162688">https://www.kaggle.com/c/birdsong-recognition/discussion/162688</a></li><li><a href="https://www.kaggle.com/cwthompson/birdsong-making-a-prediction">https://www.kaggle.com/cwthompson/birdsong-making-a-prediction</a></li><li><a href="https://www.researchgate.net/publication/328418948_Bird_Call_Recognition_using_Deep_Convolutional_Neural_Network_ResNet-50">https://www.researchgate.net/publication/328418948_Bird_Call_Recognition_using_Deep_Convolutional_Neural_Network_ResNet-50</a></li><li><a href="http://ceur-ws.org/Vol-2380/paper_68.pdf">http://ceur-ws.org/Vol-2380/paper_68.pdf</a></li><li><a href="http://ceur-ws.org/Vol-2380/paper_52.pdf">http://ceur-ws.org/Vol-2380/paper_52.pdf</a></li><li><a href="https://arxiv.org/ftp/arxiv/papers/1803/1803.01107.pdf">https://arxiv.org/ftp/arxiv/papers/1803/1803.01107.pdf</a></li><li><a href="https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly">https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly</a></li><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afc43ca90b13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Satisfaction Prediction — Brazillian e-Commerce Public Dataset]]></title>
            <link>https://medium.com/@krgaurav45/customer-satisfaction-prediction-brazillian-e-commerce-public-dataset-5bb9ed841bf1?source=rss-1af63ce8da47------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bb9ed841bf1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[customer-satisfaction]]></category>
            <category><![CDATA[binary-classification]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kumar Gaurav]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 18:17:38 GMT</pubDate>
            <atom:updated>2020-09-05T08:48:13.671Z</atom:updated>
            <content:encoded><![CDATA[<h4>Customer Satisfaction Prediction — Brazilian e-Commerce Public Data-set</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*qaC1mtjRjN5DxpQhv7uStw.png" /><figcaption>satisfaction score</figcaption></figure><p>The emergence of internet has revolutionized the way of doing things either it business, education talking to your friend and even shopping. One of the most emerging and now crucial part of the society is the E-Commerce sector where you order a product online and get it delivered to your desired location. But, as per the human comfort goes the e-commerce is best if it satisfies your requirements otherwise we don’t hesitate to criticize the same. And in this era of internet as said earlier it revolutionized every thing even the way of putting your thoughts to the world. Similarly, In the e-commerce sector for every order made by the customer they provide some review either good or bad for their purchase experience. Now, these reviews put by the consumers can help in taking many business decisions for example which product is selling most which one is getting good response from consumer and which is being disliked and why ! Based on the reviews and other data of the purchase we can find answer to these problems but, the problem is we have around thousands and even lakhs of order reviewed in a day and we cannot find insights on such data by mere human efforts. So, the machine learning comes into play where we make our machine to answer all our questions and even predict the customer satisfaction based on these data. Therefore, let us dive deep into the the problem we need to solve and how!</p><h3><strong>Business Problem</strong></h3><h4><strong>Description</strong></h4><p>This is a Brazilian eCommerce public data-set of orders made at Olist Store. The data-set has information of 100k orders from 2016 to 2018 made at multiple marketplaces in Brazil. Its features allows viewing an order from multiple dimensions: from order status, price, payment and freight performance to customer location, product attributes and finally reviews written by customers. A Geo-location data-set that relates Brazilian zip codes to lat/lng coordinates has also been released.</p><p>This data-set was generously provided by Olist, the largest department store in Brazilian marketplaces. Olist connects small businesses from all over Brazil to channels without hassle and with a single contract. Those merchants are able to sell their products through the Olist Store and ship them directly to the customers using Olist logistics partners. See more on the website: <a href="http://www.olist.com/"><strong>olist</strong></a><strong>.</strong><br>After a customer purchases the product from Olist Store a seller gets notified to fulfill that order. Once the customer receives the product, or the estimated delivery date is due, the customer gets a satisfaction survey by email where he can give a note for the purchase experience and write down some comments.</p><p>CREDITS:- Kaggle</p><h4><strong>Problem Statement</strong></h4><blockquote>Predict Customer satisfaction (0 for negative and 1 for positive) of the purchase from the brazilain e-commerce site Olist.</blockquote><p>Now, that we have understood the problem we need to solve let us understand how we can map this problem to ML/DL problem and things we need to keep in mind.</p><h4><strong>Mapping to Machine Learning Problem</strong></h4><blockquote>For a given order, we need to predict the customer satisfaction score given its different features like price, item description, on time delivery, delivery status etc. So, the given problem can be solved as a <strong>Binary Classification Problem.</strong></blockquote><p>Now that we decided the type of problem let us see the constraints and metrics that we will need to keep in mind while solving the problem.</p><h4><strong>Performance metric</strong></h4><ul><li>F1-score</li><li>Binary Confusion Matrix</li></ul><h4><strong>Real world/Business Objectives and Constraints</strong></h4><blockquote>Minimize False positive rate.<br> No strict latency concerns.<br> Interpret-ability is important.</blockquote><h3>Data</h3><p><strong>Source:- </strong><a href="https://www.kaggle.com/olistbr/brazilian-ecommerce"><strong>https://www.kaggle.com/olistbr/brazilian-ecommerce</strong></a></p><p>As we have defined our problem statement, performance metric and constraints, it is time to look for the data that we are going to work on. The data is made openly available at kaggle website by the Brazilian e-commerce company Olist in the form of multiple tables for better understanding and organization related using one or more keys as shown in the below data schema image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fq_t7wuF4K9h7R1-.png" /><figcaption>Data Schema</figcaption></figure><p>The data in above state cannot be useful in fulfilling our purpose. So, we merge the tables to get one master data set using the relationship provided in the data schema. The data is merged and stored in final data set as df_final.csv for easy processing and analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37fa03f43bc59070de5e8c6649d97c6/href">https://medium.com/media/c37fa03f43bc59070de5e8c6649d97c6/href</a></iframe><p>Now, that we have our final data set let us look at features of the data set.</p><h4><strong>Data Description</strong></h4><p>In the final data set we have 31 features. let us briefly understand those features one by one.</p><ul><li><strong>order_id </strong>:- The unique id of order made by the customers.</li><li><strong>order_item_id </strong>:- Unique Id given to each item ordered in the order.</li><li><strong>product_id </strong>:- Unique Id given to each product available on the site.</li><li><strong>seller_id </strong>:- Id of the seller selling the product through the online store.</li><li><strong>shipping_limit_date </strong>:- The date before which shipping of the ordered product must be completed.</li><li><strong>price </strong>:- price of the products ordered .</li><li><strong>freight_value </strong>:- price of the packaging of the products and freights.</li><li><strong>product_name_lenght </strong>:- length of the string which species the name given to the products ordered.</li><li><strong>product_description_lenght </strong>:- length of the description written for each product ordered on the site.</li><li><strong>product_photos_qty </strong>:- Number of photos of each product ordered available on the shopping portal.</li><li><strong>product_weight_g </strong>:- weight of the products ordered in grams.</li><li><strong>product_length_cm </strong>:- length of the products ordered in centimeters.</li><li><strong>product_height_cm </strong>:- height of the products ordered in centimeters.</li><li><strong>product_width_cm </strong>:- width of the product ordered in centimeters.</li><li><strong>product_category_name_english </strong>:- category to which the products belong to.</li><li><strong>review_score </strong>:- review score given by the customer for each order on the scale of 1–5.</li><li><strong>review_comment_message </strong>:- review comments posted by the consumer for each order.</li><li><strong>customer_id </strong>:- Id of the consumer who made the purchase.</li><li><strong>order_status </strong>:- status of the order made i.e delivered, shipped etc.</li><li><strong>order_purchase_timestamp </strong>:- Timestamp of the purchase.</li><li><strong>order_approved_at </strong>:- Timestamp of the order approval.</li><li><strong>order_delivered_carrier_date </strong>:- delivery date at which carrier made the delivery.</li><li><strong>order_delivered_customer_date </strong>:- date at which customer got the product.</li><li><strong>order_estimated_delivery_date </strong>:- estimated delivery date of the products.</li><li><strong>payment_sequential </strong>:- sequences of the payments made in case of EMI.</li><li><strong>payment_type </strong>:- method used to pay for the purchase.</li><li><strong>payment_installments </strong>:- Installments value in case of EMI purchase.</li><li><strong>payment_value </strong>:- Amount paid for the orders.</li><li><strong>customer_unique_id </strong>:- unique id of the customer.</li><li><strong>customer_zip_code_prefix </strong>:- zip address of the consumer who made the order.</li><li><strong>customer_city </strong>:- city of the consumer.</li><li><strong>customer_state </strong>:- state of the consumer.</li></ul><h3>Exploratory Data Analysis</h3><p>Since, we have our final data set and we have brief idea on the features the data set contain it is time for us to dive deep and see more insights on the data set and see the type of the features, distributions and correlations etc. To do so we have done extensive exploratory data analysis of each feature with respect to the target feature i.e review_score. First let us start by seeing the distribution n of our target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*Uk2bs5LixezyDgcYT86QEg.png" /><figcaption>review_score plot</figcaption></figure><p>The above plot shows the distribution of the class labels(review_score) in the data set. From the plot, we can see that more than 50% of the data points belong to the class label 1 i.e positive class and rest of them to the negative class suggesting that we have class imbalanced data set.</p><p>As per our problem approach our objective to classify the data into two class .So, all the analysis we do is to find insights(rule) on how we can classify the data to correct labels. Let us look at some statistics of the numerical features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JECWA4YA6xGZ6QbbhGK4rQ.png" /><figcaption>statistics of data</figcaption></figure><p>We observe from above table that we have 12 useful numerical features except zip code, our target variable review score and order_item_id. let us observe the statistics of the price and freight value of an order. The maximum price of an order is 6735 while max freight went to around 410 Brazilian real. The average price of an order is around 120 Brazilian real and freight value is around 20 Brazilian real. The order with minimum price of 0.85 Brazilian real have been made. Let us look at distribution of these features and see how they help in classifying the class labels and find other insights.</p><p>Now, let us do some uni-variate analysis on the features with respect to review_score.</p><h4>Uni-variate Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Eh5F0m0FrWlb5OMtC1Ng_g.png" /><figcaption>product price distribution</figcaption></figure><p>The distribution plot above shows the distribution of price for both the positive and negative classes. The overlap of both the distribution for positive and negative class suggests that it is not possible to classify them based only on price feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*mEmCxdATmvCYc3dQPBLZNg.png" /><figcaption>product freight value distribution</figcaption></figure><p>From the plot above titled `Distribution plot of freight value`, we observe that freight value is somewhat normally distributed but it too is overlapping for both the classes and hence provide much info in the classification.<br>Let us look at some more distributions and see if we get something important from any of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*wGo3jROKZV617By7j8MMLw.png" /><figcaption>product height in centimeters distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*uG5vAuuRYK1oc7cVytlxVg.png" /><figcaption>product weight in grams distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*DBSq8LPXMF3r-3akfpooUg.png" /><figcaption>payment value distribution</figcaption></figure><p>From all the above uni-variate plots, we observed that almost all of them have overlapping distributions for the class labels. We can infer from that values of features lying in any range of their distribution have almost equal chance of getting a positive or negative review. So, if that is the case how can we train the model to classify the positive and negative points if we cannot properly differentiate based on the features value(distribution).<br>So, let us go and do some bi-variate analysis and see if we use more than one feature at time, can we come with something to classify these features.</p><h4><strong>Bi-variate Analysis</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*3g7X7WCsuQTlXZWFOj1YzA.png" /><figcaption>price vs freight value per class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*j11GV9uMM4hCIX8B3IVQbQ.png" /><figcaption>Distribution of price vs product_weight_g per class</figcaption></figure><p>From the above two scatter plots titled `<strong>Distribution of price vs freight_value per class</strong>` and `<strong>Distribution of price vs product_weight_g per class</strong>` respectively, we tried to observe how are the features price and freight_value distributed for the class labels in the first plot. From the plots we observe that the points are mixed together for the both the classes suggesting us that algorithms like KNN might not be good in classifying these points. Therefore, we will observe the distribution of few more features with each other and see we find something more important. Let us look at the pair plot below to understand the relationship between more features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3VyelSGBq5RGM0a-tg7aw.png" /><figcaption>Distribution of two features at a time per class</figcaption></figure><p>In the pair plot above we see distribution of one feature with rest of them for each class labels. In the pair plot above, we can see some of the blue points from the orange points while in the uni-variate analysis we observed overlapping for almost all the cases. The distribution of freight value with all the other features like price, product length etc. shows that we might be able to classify positive and negative class using some non-linear techniques where the uni-variate analysis showed that it is nearly impossible to classify them based on some straight forward conditions or linear way. The results in the pair plot are better than uni-variate analysis but it is not promising to come any sure shot conclusion so, in next step we can engineer some new features on the data and try to see if we can find any relations that can differentiate between positive and negative class.</p><h4><strong>Analysis of Categorical Features</strong></h4><p>We have extensively analyzed the numerical features so, it is time to analyze our categorical features as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*0WOxBLgxVn4DzgXPeAM93w.png" /><figcaption>review score vs payment method</figcaption></figure><p>The plot above shows the distribution of the categorical variable payment type w.r.t the review score. From the plot we observe the around 55% of the positive review given by customers have used credit card for the payments. Similarly, for negative review around 18% of customers made payment using credit cared while in the second position we have boleto — digital currency provided by the eCommerce site for their regular and registered customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*5de-1GcUJI0H_0ExycRC9A.png" /><figcaption>review vs order fullfillment</figcaption></figure><p>The plot above is a very simple plot which shows the distribution of review score given per order status of the order. From the plot we can observe that out of all the orders which got positive review 99% of them has been successfully delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*8c-Q_Pqse2TKT7mw9fk4dA.png" /><figcaption>top ten consumer states</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*tryym1VkZQfCflRbk8ZGBg.png" /><figcaption>top ten product categories</figcaption></figure><p>In the above two plots titled `<strong>top 10 consumer states of Brazil</strong>` and `<strong>top 10 products categories sold</strong>` respectively we tried to observe the top ten states of the Brazil which shopped mostly online and the top ten product categories from which products have been sold. In plot 1, we observe that around 45% of the consumers who shopped online is from the state <strong>SP</strong> while top 2 state constitute only around 15% of the total consumer shopping of the data.</p><p>From the second plot, we observe that most of the products sold is from category bed_bath_table. The top two products category health_beauty and bed_bath_table constitutes around 20% of the sells of the site.</p><p>We have observed from the above plots that the features does not help very much classifying the positive and negative points. They show overlapping plot for most of them. So, In the next step we will engineer some new features and observe these new features behaviour.</p><h4>Feature Engineering and Analysis</h4><p>Let us explore some new features we are going to engineer using one or more features of the data.</p><ol><li><strong>Sellers Count</strong>:- Number of sellers for each product as a feature.</li><li><strong>Products count</strong>:- Number of products ordered in each order as a feature.</li><li><strong>Estimated Delivery Time(in number of days)</strong>:- Gets the days between order approval and estimated delivery date. A customer might be unsatisfied if he is told that the estimated time is big.</li><li><strong>Actual Delivery Time:-</strong> Gets the days between order approval and delivered customer date. A customer might be more satisfied if he gets the product faster.</li><li><strong>Difference in delivery days</strong>:- The difference between the actual and estimated date. If negative was delivered early, if positive was delivered late. A customer might be more satisfied if the order arrives sooner than expected, or unhappy if he receives after the deadline.</li><li><strong>Is Late</strong>:- Binary variable indicating if the order was delivered after the estimated date.</li><li><strong>Average Product Value</strong>:- Cheaper products might have lower quality, leaving customers unhappy.</li><li><strong>Total Order Value</strong>:- If a customer expends more, he might expect a better order fulfillment.</li><li><strong>Order Freight Ratio</strong>:- If a customer pays more for freight, he might expect a better service.</li><li><strong>Purchase Day of Week</strong>:- Day of week on which purchase was made.</li><li><strong>is_reviewed</strong>:- If the review comment is given or not.</li></ol><p>Now, that the features have been created let us do some analysis on those features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5eJrWZThh42-ITIJ4YcNQQ.png" /><figcaption>statistics of new features</figcaption></figure><ol><li>The sellers count for total products ordered in a order have minimum number of sellers as 1 while maximum sellers of 527.</li><li>The number of products ordered in a single order have maximum value as 21 and minimum as 1.</li><li>The maximum estimated delivery time is 154 days with mean value of 23 days.</li><li>The maximum actual delivery time is 208 days and with average delivery time of 12 days.</li><li>Average total order cost 140 Brazilian real with minimum value of 6 real.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*YpMZqL_MjB9suAe24p1Spw.png" /><figcaption>actual delivery time distribution</figcaption></figure><p>For all the uni-variate distribution up until now, we have observed complete overlap for both classed while in the above plot we can see some difference in distributions for positive and negative classed. The negative class is more skewed to right than the positive class inferring that the increase in delivery time affects the review score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*jzQKL7NPz6nGXmrkylJQfQ.png" /><figcaption>order freight ratio distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*RZzdJrrgZweN_49yOL_Orw.png" /><figcaption>reviews vs delivery status</figcaption></figure><p>From plot titled `<strong>distribution of order freight ratio</strong>` we observe overlap for both the classes. So, we will go for bi-variate/multivariate analysis for this features.<br>Also, from the plot titled `<strong>review score by order fulfillment</strong>` we observe that out of all the review classified as positive 90% of them were delivered on or before time to the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*86jSx5EEGNbwQOVd0aXJZQ.png" /><figcaption>actual vs estimated delivery time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*wHwMw2qzozapW3-E32VNDA.png" /><figcaption>sellers vs actual delivery time</figcaption></figure><p>From the uni-variate analysis, we have seen that actual delivery time’s distribution is partially overlapping for both the class labels and we cannot derive any certain rule to classify them based on the actual delivery time. So, we plotted the above scatter plots to see if we can derive any relation with more than one features. From the plots above we observe that we can separate the blue points from the orange points with a linear line with some errors. Thus, now we can say that we can derive some linear relation to classify them. let us verify our observation from below pair plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hMbqLu-NfWnMhdO9O0zmg.png" /><figcaption>Distribution of two features at a time per class</figcaption></figure><p>The Pair-plot above is the bi-variate analysis of 8 newly engineered features like sellers count, product count, delivery time in days etc. From the above plot we observe that actual delivery time vs sellers count plot separates the positive and negative classed more visibly than others. We can say that the number of sellers available and the actual delivery time affects the review score either positively or negatively which we can see in details in the correlation analysis of the features.</p><h3>EDA Takeaways</h3><p>Let us see what we gathered from our whole EDA:-</p><ol><li>The class label is not balanced.</li><li>It is impossible to differentiate the classes based on any single feature.</li><li>The numerical feature like price and freight value have skewed distribution suggesting the presence of high boundary values.</li><li>The freight_value vs product photo qty plot shows good result for classifying the class labels.</li><li>The most used payment method is credit card.</li><li>We also found that around 45% of the consumers belong to single state and most shopped product category among them is bed,bath,table,health and beauty.</li><li>As observed in the analysis, 10 different features were created referencing some features in the data like:- products count, sellers count, total order cost, actual delivery time etc. and the previous features like delivery date, product_id etc. is dropped.</li><li>we learnt that the feature actual delivery time provide partial differentiation between positive and negative class.</li><li>The scatter plots plotted in the first part of these analysis do not show any significant results in classifying the positive and negative points while the scatter plots in the second analysis after feature engineering shows significant difference in the positive and negative class points as evident from plot `Distribution of sellers_count vs actual_delivery_time per class`.</li><li>The pair plot shows that with these features can classify the positive class from negative class with some non linear transformation.</li><li>As evident from scatter plots and pair plots , it is clear that linear algorithms or KNN might not be good choice in classifying these points. But, at-least we learnt that with these set of features we can classify them into two classes.</li></ol><h3>Handling Missing Values</h3><p>Now, we have found some good features as observed from the analysis. So, let us drop the irrelevant features like customer Id, shipping date etc. check for the null values in the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b839425d2afdf644e1f9b5ad1e5bd58f/href">https://medium.com/media/b839425d2afdf644e1f9b5ad1e5bd58f/href</a></iframe><pre>price                                0<br>freight_value                        0<br>product_name_lenght               1709<br>product_description_lenght        1709<br>product_photos_qty                1709<br>product_weight_g                    20<br>product_length_cm                   20<br>product_height_cm                   20<br>product_width_cm                    20<br>product_category_name_english     1734<br>review_score                         0<br>review_comment_message           67650<br>order_status                         0<br>payment_sequential                   0<br>payment_type                         0<br>payment_installments                 0<br>payment_value                        0<br>sellers_count                        0<br>products_count                       0<br>estimated_delivery_time             15<br>actual_delivery_time              2603<br>diff_in_delivery_time             2603<br>on_time_delivery                     0<br>avg_product_value                    0<br>total_order_cost                     0<br>order_freight_ratio                  0<br>purchase_dayofweek                   0<br>is_reviewed                          0</pre><p>As in the uni-variate analysis of the features we have seen that the values of some of the features are quite extreme, hence to avoid outlier impact we used median imputing technique to fill the null values and for categorical features we used the most occurring ones to impute the null ones. The null value in the feature review comment message is filled with ‘nao_reveja’ meaning no_reviews in portugese.</p><h3>Data Preparation</h3><p>We have created final data set, dropped irrelevant features, handled missing values and even curated new features. It is now time to prepare the data for model training and evaluation. First, we split our data into train and validation set where train set is used for training and validation set is used for evaluation of the model’s performance.</p><h4>Train and Test split</h4><p>We split our data set into 80:20 split using scikit-learn train test split with stratified splitting technique to avoid the class bias.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/914692cbe0d3dcfed5cb1cefc630e44e/href">https://medium.com/media/914692cbe0d3dcfed5cb1cefc630e44e/href</a></iframe><h4><strong>Encoding Features</strong></h4><p>After splitting the data it is time to make the train data model ready and to do so we need to encode and normalize the features accordingly. The feature encoding technique is a way to encode texts, strings value to some integral value which model can read and perform operation on. The numerical features can also be encoded i.e standardized to avoid the effect of outlier in the model. To make your task easy let us divide the features into numerical and categorical as shown in below image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53d09d9a7aed0a27730dc7980a100cc0/href">https://medium.com/media/53d09d9a7aed0a27730dc7980a100cc0/href</a></iframe><h4><strong>Encoding review comment message</strong></h4><p>The feature review comment message is a text feature and we have various text encoding features like count vectorizer, tfidf vectorizer, word2vec etc. But, before encoding we need to clean the text like removing punctuation, numbers, hyperlinks, patterns and stopwords etc. Once the data is processed we encoded the features using averaged tfidf w2v model. Since, we have review message in portugese language we trained our own w2v model on own corpus and then encoded the features as shown in below image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6844339b1ce01942119d1d92c28a3ef6/href">https://medium.com/media/6844339b1ce01942119d1d92c28a3ef6/href</a></iframe><h4><strong>Encoding Categorical features</strong></h4><p>For the features <strong>order_status</strong> and <strong>payment_type</strong>, and <strong>product_category </strong>we used one hot encoding to encode these features.</p><h4><strong>Handling Numerical features</strong></h4><p>Numerical features can be tricky to handle due to different range of minimum and maximum values for different types of features. In this section, we will handle the numerical features before feeding into our machine learning models. Since numerical features can be of different scale values, we have normalized our features and assigned an uniformity so as not to train models with scale differences between features. Sci-kit Learn has an inbuilt Normalize library to normalize values in range of 0 to 1. The snippet shows encoding of categorical and numerical features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03294f6d3c10d4f77d26783a0f0a393a/href">https://medium.com/media/03294f6d3c10d4f77d26783a0f0a393a/href</a></iframe><p>In above all the encoding techniques, the estimators are calculated using the train data only and transformation is applied based on that to both train and validation to avoid data leakage.</p><h4><strong>Merging all features in a matrix</strong></h4><p>Now, the data is ready for model training but is scattered in bit and pieces so we will assemble these pieces into one place to feed into the model. To do so we used scipy hstack method and merged all the features column-wise. You can see the shape of train and test data below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642042de7113c161cb9e77b7601a3566/href">https://medium.com/media/642042de7113c161cb9e77b7601a3566/href</a></iframe><h3>Machine Learning Modelling</h3><p>As we are done with all the data per-processing task, feature engineering, analysis the next step is to train some model and select best performing one as the final model.</p><p>According to our objective and first cut approach we have decided to solve this problem as a binary class classification problem. So, we will train some classification models and observe the results. There are many machine learning algorithms to try when you are working on a specific problem. You never know which ML model would work the best for you before hand. However, domain knowledge and expertise with practice do play a role sometimes. But the best choice for anybody who wants to master his skills is by experimenting. So, I have experimented with a couple of classification models and checked which performs the best.</p><p>We start with simple ML classification models to simple NN models. The models we experiment with in this case study are as follows:-</p><ol><li>Logistic Regression</li><li>Linear Support Vector Machine</li><li>Decision Tree Classifier</li><li>Random Forest Classifier</li><li>Boosting Classifier (XGBoost/LightGBM/AdaBoost)</li><li>Stacking/Voting Ensemble techniques</li><li>Simple NN model</li><li>CNN(conv-1d) and LSTM</li></ol><h4><strong>Hyper-parameters Tuning</strong></h4><p>Before we find the best model that fits on our data and achieves our task it is important to first find the best parameters for each model that performs best on the training and validation data without over-fit/under-fit. It is very important to tune your hyper-parameters of the models when you use them. The set of hyper-parameters that you choose for a ML model is crucial, so keep that in mind. That is why first we find best parameters for our model and then do the final training.</p><p>To do this we have various techniques like RandomisedSearch cross validation, Grid Search cross validation, K-fold statrified sampling etc. I have used RandomisedSearch with k-fold cross validation technique to tune hyper-parameters of the models.The reason of choosing Random Search is its faster training speed compared to Grid Search as the later checks on all configuration of parameters. The final model is trained using these best hyper-parameters found and the performance is calculated using the validation data set.</p><p>We are going to use scikit-learn library to implement all these models and parameter selection method. It is extremely easy to build models with Sci-kit Learn because of its simplicity. Let us look at illustrated implementation of some of the models.</p><h4>Logistic Regression</h4><p>We start with our simple logistic regression classification model. The best parameters is selected using RandomisedSearch CV and then model is trained using that best parameters as shown in below code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7919952f0a16f965c11cbac88d3e9db7/href">https://medium.com/media/7919952f0a16f965c11cbac88d3e9db7/href</a></iframe><p>The first model trained is Logistic Regression and f1-score is used as the metric. The implementation can be seen in the above code snippet. We used randomized search cross validation technique to tune the parameters of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*9hQ58yuH_jBolhnxuBOeNA.png" /><figcaption>performance measure of LR</figcaption></figure><p>The best parameters are fed into the model and again and trained to get the final estimation and then the performance of the model is observed.</p><h4><strong>Linear SVM</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8151c231d0fd0d4136c1d7ce9fa1152a/href">https://medium.com/media/8151c231d0fd0d4136c1d7ce9fa1152a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*jHEU_eWZ12k6gf3xNA0tog.png" /><figcaption>performance measure of linear svm</figcaption></figure><p>Here, we tried linear SVM classifier and used same approach as before to fine tune and train the model. Looking at the results we got, we observe that SVM is performing slightly better than Logistic Regression. From CM we observe that SVM is doing better for FPs than LR. let us look at some non-linear models.</p><h4>Decision Tree Classifier</h4><p>After not getting promising results with linear models, we go with non linear models i.e tree and used Decision Tree Classifier as classification model. Firstly we trained the model for various values of depth of the tree to get the range of the parameters while fine tuning the parameters during randomized search cross validation. Keeping the results in last step as base line, the score obtained by this model during training is 0.92 which is better than previous model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55d7607957338a20c40f0e841b377e0/href">https://medium.com/media/b55d7607957338a20c40f0e841b377e0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*5LyzfbnvVM0oXb6_nsorEA.png" /><figcaption>performance measure of decision tree</figcaption></figure><p>Also, looking at the confusion matrices we see that we made some improvement in False Positives but while lost some in False Negatives suggesting that model is obviously learning differently than linear models. So, keeping these results in mind let us try ensemble techniques to further verify our hypothesis and try to achieve improved results.</p><h4>Random Forest Classifier</h4><p>From the previous models we observed that we were getting good results but the improvement was not that significant. So, we thought of going with ensemble models and the first one we will try is RandomForest. Let us see how this model do. We followed the same method for fine tuning and training the model as used in decision tree with some additional parameters like number of estimators etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3919ca035b4c51dbdbc30beb41c59c/href">https://medium.com/media/ac3919ca035b4c51dbdbc30beb41c59c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Kb_VTYhJktjRSkhsfCg39A.png" /><figcaption>performance measure of random forest</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*IuJSb2XpblsnnCOGyzePYw.png" /><figcaption>feature importance</figcaption></figure><p>Now, looking at results of the model trained at best tuned parameters, we observe that model is performing better than all the previous models suggesting that ensemble are working well for this task so we will tray some more ensemble technique and see we can make an improvement or not. As it is asked in the constraints to have interpret-able model so we tried feature importance plot to check if model is making sense or not. From the graph we can see that among top features we have delivery time suggesting that review of consumer is indeed affected by delivery of the company. Also, we have some positive and negative words which suggests why consumer gave that review.</p><h4>Gradient Boosting Classifier</h4><p>For Boosting Classifier techniques we tried three models, XGBoost, LightGBM and AdaBoost where XGB and LGBM works similar on the concept of gradient boosting while AdaBoost tries to minimize the error generated in each training step. Among all these three the XGBoost is found to working best with around 0.96 f1-score. The implementation and performance is shown in below snippets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3927aabd768630b66e3bfbfc3ddaf1a1/href">https://medium.com/media/3927aabd768630b66e3bfbfc3ddaf1a1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*_Ob2-QOYrdPi5OMl839BKw.png" /><figcaption>performance measure of xgboost</figcaption></figure><p>From above results we found that we got our best performing models till now but we observe that there is still room for improvement especially on validation data set. So, we will see some ensemble technique like Stacking and Voting classifiers.</p><h4><strong>Stacking/Voting Classifier</strong></h4><p>To further enhance our performance we tried stacking classifier and voting classifier. In this approach, we kept our models tried so far as base estimators and trained another model on the predictions made by these models to learn some relation and improve our performance. We tried different models for meta classifier and observed the result. We found best result with XGB as meta classifier with 0.96 f1-score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5257df87edb12e9da259fc2d4f372292/href">https://medium.com/media/5257df87edb12e9da259fc2d4f372292/href</a></iframe><p>Similarly, for voting classifier we kept our models tried so far as base estimators and trained another model on the probabilistic values as well as predicted labels for each class predicted by the models. We will use sklearn Voting classifier model for this task with LR,DT,RF,and LGBM as base estimators and voting= soft/hard. The results obtained for both are similar but it does not surpass the results achieved by best stacking classifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8073f0ab6f811c2c6ae6123087053d2e/href">https://medium.com/media/8073f0ab6f811c2c6ae6123087053d2e/href</a></iframe><h4><strong>2-layer NN model</strong></h4><p>As said it is important to experiment if we want to find the best. It seems from above model that we might have find best. so, to verify our guess we tried some simple DL models. The model graph is shown below. We used default initialization while creating the model. We used binary_crossentropy as loss metric and custom f1 score as performance metric for all the DL models. The inputs are resized according to the models. We trained the models for 50 epochs with adam optimizer for learning rate of 0.001 and applied various callbacks like early stopping, model checkpoint to keep track of the training. Regularization like Batch Normalization and Dropout are used to avoid over fitting and under fitting. Tensor board callback is used to track the vanishing and exploding gradient in case of LSTM etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*T9B6QHs67a_1su3DYjW92w.png" /><figcaption>2-layer neural network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2c37bTr4T3y-oXjPl3FovA.png" /><figcaption>training neural network</figcaption></figure><h4><strong>CNN Models</strong></h4><p>As seen above, the model is performing good but cannot surpass the best result achieved yet. so, we tried two conv1D architectures. The best performing among them is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*u3xcCytKwndc9Q4BkvQLiw.png" /><figcaption>cnn model with two inputs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EeA21aAYGalXf-a5-FeQA.png" /><figcaption>performance measure of cnn model</figcaption></figure><h4><strong>LSTM</strong></h4><p>We see some improvement in CNN model but it still does not surpass our best result so, we tried two lstm model and best among them is shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*5mh-Awy4OmEoF3R8fChTAg.png" /><figcaption>lstm model with two inputs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*1iaIhUYZ92j_S1l8GZZ_FQ.png" /><figcaption>performance measure of lstm model</figcaption></figure><p>Even the this model did beat the best result we have achieved yet. We tried some ensemble techniques on the predictions of these models and observe that they still did perform better. Sample ensemble can be seen in the below snippets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c01b53357d6e4cb3e6b1db710b15c2d7/href">https://medium.com/media/c01b53357d6e4cb3e6b1db710b15c2d7/href</a></iframe><p>We have done quite a experiment in search for the best. So, it is time to summarize what we worked and what not.</p><h3>Results</h3><p>So, let us have a look at what we learned:-</p><ul><li>The categorical features are encoded using one-hot encoding technique and numerical ones are standardized using sklearn normalizer modules to reduce the effect of outliers.</li><li>The text feature used for training is encoded using tfidf averaged word2vec technique.</li><li>The data is divided as train and test into 80:20 split for training and validation of the models.</li><li>Various classification models like Logistic Regression, Decision Tree, Random Forest and LightGBM are trained and results were observed.</li><li>The f1-score is used as performance metric to compare the performance of the models.</li><li>The models are fine-tuned using randomized search cross validation hyper-parameters tuning technique and finally trained on the best parameters obtained.</li><li>Confusion matrix is used to better understand the predictions of the models.</li><li>Feature importance is also measured to look at some of the top features of the data and find the reasoning behind models predictions.</li><li>The non-linear models are found to be performing well. Among them, XGBoost performed best with 0.96 f1-score.</li><li>The performance results for each model can be observed in the below summary table.</li><li>Other ensemble techniques like Stacking and Voting as well as NN models are used to further improve the results and reduce the errors.</li><li>Voting performed better than some techniques but could not beat the performance of XGBoost.</li><li>The Stacking classifier gave best results with train score of 0.964 and test score of 0.939 as provided in the above summary table.</li><li>The NN models performed better then some linear models but couldn’t beat the performance achieved by the stacking classifier suggesting that we need more data for them to achieve score better than this.</li><li>The ensemble technique applied on the outputs of the NN’s models showed some improvement in the results but could not achieve better than our previous best.</li></ul><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*fPboTCNcsNmFMddudz4srw.png" /><figcaption>performance summary table</figcaption></figure><p>The summary table is attached for easy comparison of the models performance.</p><h3>Improvements to Existing Approaches</h3><p>The Existing approach as referenced in the reference section is a regressor model with RMSE of 0.58. The existing approach model used only numerical features and many features were discarded. In the approach we followed we achieved very good result than the existing approach and also learnt that there are some features which plays important role in customer satisfaction and they should not be dropped.</p><h3>Future Work</h3><p>More parameters tuning of the DL models can be done to achieve better result. Also, training with more data than provided can improve the model’s performance.</p><blockquote><strong>For the full implementation of this case study refer this </strong><a href="https://github.com/krgaurav45/Customer-Satisfaction-Prediction"><strong>github repo</strong></a><strong>.</strong></blockquote><blockquote><strong>Feel free to connect with me on </strong><a href="https://www.linkedin.com/in/krgaurav45"><strong>LinkedIn </strong></a><strong>and </strong><a href="https://github.com/krgaurav45/"><strong>GitHub</strong></a><strong>.</strong></blockquote><h3>References</h3><ol><li>Source:- <a href="https://www.kaggle.com/olistbr/brazilian-ecommerce">https://www.kaggle.com/olistbr/brazilian-ecommerce</a></li><li>Data Description:- <a href="https://www.kaggle.com/andresionek/understanding-the-olist-ecommerce-dataset">https://www.kaggle.com/andresionek/understanding-the-olist-ecommerce-dataset</a></li><li>Discussion:- <a href="https://www.kaggle.com/olistbr/brazilian-ecommerce/discussion/66466">https://www.kaggle.com/olistbr/brazilian-ecommerce/discussion/66466</a></li><li>Data Analysis:- <a href="https://www.kaggle.com/duygut/brazilian-e-commerce-data-analysis">https://www.kaggle.com/duygut/brazilian-e-commerce-data-analysis</a></li><li>Existing Approach:- <a href="https://www.kaggle.com/andresionek/predicting-customer-satisfaction">https://www.kaggle.com/andresionek/predicting-customer-satisfaction</a></li><li>Ensemble:- <a href="https://pdfs.semanticscholar.org/449e/7116d7e2cff37b4d3b1357a23953231b4709.pdf">https://pdfs.semanticscholar.org/449e/7116d7e2cff37b4d3b1357a23953231b4709.pdf</a></li><li>Sentiment:- <a href="https://www.kaggle.com/thiagopanini/e-commerce-sentiment-analysis-eda-viz-nlp">https://www.kaggle.com/thiagopanini/e-commerce-sentiment-analysis-eda-viz-nlp</a></li><li><a href="https://radimrehurek.com/gensim/models/word2vec.html">https://radimrehurek.com/gensim/models/word2vec.html</a></li><li><a href="https://www.aclweb.org/anthology/W17-6615">https://www.aclweb.org/anthology/W17-6615</a></li><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb9ed841bf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>