<?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 Kunal D. Baidya on Medium]]></title>
        <description><![CDATA[Stories by Kunal D. Baidya on Medium]]></description>
        <link>https://medium.com/@kunalbaidya?source=rss-4f3416896fb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ciUwu5qfoMKHS9o3Q1Z47g.jpeg</url>
            <title>Stories by Kunal D. Baidya on Medium</title>
            <link>https://medium.com/@kunalbaidya?source=rss-4f3416896fb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:47:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunalbaidya/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[LEARN BASIC REGEX FOR TEXT CLEANING IN LESS THAN 20 MINUTES.]]></title>
            <link>https://kunalbaidya.medium.com/learn-basic-regex-for-text-cleaning-in-less-than-20-minutes-4b9d73cf7d3e?source=rss-4f3416896fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9d73cf7d3e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[string-manipulation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal D. Baidya]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 11:26:52 GMT</pubDate>
            <atom:updated>2023-02-28T11:26:52.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWej8MA2fhVK14WPs_0dbA.jpeg" /><figcaption>IMAGE SOURCE: <a href="https://pixabay.com/vectors/emojis-face-expressions-emotions-6058763/">https://pixabay.com/vectors/emojis-face-expressions-emotions-6058763/</a></figcaption></figure><ol><li><strong>INTRODUCTION</strong></li></ol><p>We all know the importance and need for textual data cleaning for natural language processing(NLP). New slang are created every passing day and people have started using alpha-numeric texts in day-to-day life for replying to messages quickly.</p><p>Let us look at some examples of modern-day written conversations with shortened texts which people have started using very often:</p><p>1. Let’s go 2 the cafe @ the corner. (Here ‘at’ is replaced by ‘@’ and ‘to’ is replaced by ‘2’)</p><p>2.Let’s have dinner 2gether toni8. (Here ‘together is replaced by ‘2gether’ and ‘tonight’ is replaced by ‘toni8’.</p><p>3. Use of the number ‘8’ has become very popular for replacing the words ending with ‘ight’, like right = ri8, night =ni8, flight =fli8, etc.</p><p>With people getting used to conversations using such short terms there are more chances of committing mistakes i.e. writing such abbreviated forms in official documents, important articles, etc. On top of these, there are always typing mistakes, punctuations, and deliberately inserted numbers and special characters.</p><p>For machine learning models/tools like BOW and TFIDF vectorizer, which are used to convert textual data into vectors or numerical forms we first need to extract pure text from the given data which means we need to clean the data from all such alpha-numeric terms and special characters.</p><p>For the above-mentioned purpose, regular expressions (also known as RegEx) come in very handy, but the problem is, for using them we need to know some syntax related to it which at first look seems very intimidating to those who are new to it. For example, RegEx like <strong>[^a-zA-Z0–9]+ </strong>may not make any sense to those who are new to this.</p><p>But actually, they are very easy to understand and very useful for textual data cleaning.</p><p>So let me start by explaining all such syntax with code examples. I use Jupyter notebook to write all my python codes, so all my code snippets will be screenshots of Jupyter notebook.</p><p><strong>2. REGEX PATTERNS AND WHAT THEY DO</strong></p><p>What actually RegEx does is that it finds you a match for the type of text or text pattern you want to find, replace or remove. Below are the various RegEx and their uses:</p><p><strong>a). Single character and group of characters:</strong></p><p><strong>[abc] </strong>means it will match with all the letters a, b, &amp; c in a given document. Code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*V0oaiqDwHQHY41-cvoqmKA.png" /></figure><p>In the sentence “Tanjiro is a demon slayer” we replaced ‘d’ with ‘l’ and ‘s’ with ‘p’.</p><p>For working with RegEx in the Jupyter notebook we need to import the “re” module.</p><p>re.sub() is the function used for replacing strings, sub stands for substitute.</p><p><strong>re.sub( “</strong>str/char you need to replace<strong>”</strong> , <strong>“</strong>str/char you need to replace with<strong>” </strong>, <strong>“</strong>the str you want to replace in<strong>” )</strong></p><p>So in the above example, we replace ‘d’ with ‘l’ in the string str1 and save it in a new string named nstr1. Then in nstr1 we replace ‘s’ with ‘p’ and again save it as nstr1.</p><p>As you can see in the final string, “demon” has become “lemon” and “slayer” has become “player” and “is” has become “ip”.</p><p>Here we replaced single characters, now let’s try it with a group of characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*kK4PQBIPWEKLOlKSFbCeCg.png" /></figure><p>In the above example we are replacing <strong>[igh] </strong>with <strong>@ </strong>which means in the given string wherever “i”, “g” or “h” is encountered they are substituted with “@”.</p><p>Now suppose you want to replace every other letter except “i”, “g”, &amp; “h” with @ then you simply write <strong>[^igh] </strong>in place of <strong>[igh] </strong>and our work is done.</p><p>As you can see that after substitution in the sentence only the letters “i”, “g” and “h” remain and rest all is replaced with @.</p><p><strong>b). Range of characters:</strong></p><p><strong>[a-z] </strong>means every letter a to z, <strong>[^a-z] </strong>means all other characters except the letters a to z.</p><p>Notice that since we have written a &amp; z in lower case only lower case letters will be considered, if we write <strong>[A-Z] </strong>only upper case A to Z will be considered.</p><p>If we want to take into consideration both the upper and lower case letters then we have to write <strong>[a-zA-Z], </strong>this will do our work. Code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*PL-scvad5_6T3Cny4db1Dg.png" /></figure><p>In the above example all the characters except the letters a-z are removed. If we want to remove characters then in the place where we pass the argument of “with what to replace” just type <strong>‘’ “. </strong>So all the numbers, punctuation, hyphen, brackets etc. are removed.</p><p>But notice that even the space is considered as a character and all the spaces are removed. We can avoid this by specifying that except a-z and spaces remove all. This can be written as,<strong> [^a-z\s] here \s denotes blank space. </strong>Code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*89LF2KtU9xmFjcwVbZzPJA.png" /></figure><p>See now that all the spaces remain the same as in the original string.<strong> </strong>Now suppose you need to retain the numerical characters also in the string then we can use the expression <strong>[^a-z\s0–9] </strong>which means, except the letters a-z, blank spaces and numbers 0–9, match all the other characters. Code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*EkG0rJ1ouMJMRLYn.png" /></figure><p>See now that the number “6” is not removed from the string.</p><p><strong>c) Meta-characters</strong></p><p>Meta-characters are used to write some of the above-described expressions in short form.</p><p><strong>[0–9] </strong>can be written as <strong>\d (lower case d)</strong></p><p><strong>[^0-9] </strong>can be written as <strong>\D (upper case d)</strong></p><p><strong>[a-zA-Z0–9] </strong>can be written as <strong>\w (lower case w)</strong></p><p><strong>[^a-zA-Z0–9] </strong>can be written as <strong>\W (upper case w)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*fdXRZbhuHimO4-oU.png" /></figure><p><strong>d) Quantifiers</strong></p><p>Quantifiers are used to specify how many consecutively repeated characters to match. In our case of character substitution:</p><p><strong>[e]* </strong>-:<strong> </strong>asterisk means replace 0 or more consecutive <strong>“e”</strong>. 0 means that after every other character the replacement character will be placed once.</p><p><strong>[e]? </strong>-:<strong> </strong>? means replace 0 or 1 consecutive <strong>“e”</strong>. 0 means that after every other character the replacement character will be placed once.</p><p><strong>[e]+ </strong>-:<strong> +</strong> means replace 1 or more consecutive <strong>“e”</strong>.</p><p>Note the word consecutive in above explanation.</p><p>That’s all for now folks. Hope this helps you in your text cleaning tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9d73cf7d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[END TO END MODEL(ML & DL) BUILDING FOR TWEET CLASSIFICATION AND DEPLOYMENT USING STREAMLIT]]></title>
            <link>https://kunalbaidya.medium.com/end-to-end-model-ml-dl-building-for-tweet-classification-and-deployment-using-streamlit-dff0a2100cd?source=rss-4f3416896fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff0a2100cd</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <dc:creator><![CDATA[Kunal D. Baidya]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 12:35:17 GMT</pubDate>
            <atom:updated>2022-03-23T16:24:15.542Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>END TO END MODEL BUILDING FOR TWEET CLASSIFICATION AND DEPLOYMENT USING STREAMLIT</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiVuPPQgr4SNVjiZi9WKvw.jpeg" /><figcaption>SOURCE:https://landerapp.com/blog/6-promoting-tweets-tips/</figcaption></figure><p>People raising their concerns through social media platform is a common practice in today’s age, the reason being wide spread reach of the concerns being raised. Since internet and mobile devices are ubiquitous nowadays many people make use of social media platforms like Twitter, Facebook, Instagram etc. to make their voice reach as many people as possible. But this also leads to the misuse of same. Many people also try to spread false news and rumors which causes even more trouble and unrest among the people. For this very reason it is necessary to classify the disaster related tweets into those which are about real disasters and those which are not.</p><p><strong>Problem objective &amp; ML formulation:</strong> As described in the introduction the objective here is to identify from whether the tweets are related to real disaster or not. Since the tweets are in the form of text for ML perspective the first step here is NLP (Natural Language Processing) i.e. to convert the text into numerical form so that the ML/DL model which will be used for prediction can understand it. Once the texts are processed this will be a binary classification problem</p><p>(Class 1: Tweets are related to real disaster, Class 0: Tweets are not related to real disaster), the classification can be done using various ML/DL models.</p><p><strong>The Dataset:</strong> Since this problem is hosted on Kaggle as a competition the dataset is available on Kaggle platform itself.</p><p>The data consists of the following features except the target column.</p><p> <strong>id —</strong> a unique identifier for each tweet</p><p><strong> text —</strong> the text of the tweet</p><p> <strong>location —</strong> the location the tweet was sent from (may be blank)</p><p><strong> keyword —</strong> a particular keyword from the tweet (may be blank)</p><p>The target column has 1 for tweets which are about real disaster and 0 for tweets which are not.</p><p>The training data set consists of 7613 tweets.</p><h3>LOAD THE DATA AND VISUALIZE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*i4prfCTlAYYMBMhCnOkS0g.png" /></figure><p>We load the data as pandas data-frame named “df”.</p><h3>EXPLORATORY DATA ANALYSIS</h3><ol><li><em>PERCENTAGE NULL VALUES IN EACH FEATURE</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vb3Gt0APIxqQrfKV8DIBfg.png" /></figure><p>Since location feature has many null values (33.27%) this feature is dropped.</p><p>2. <em>VISUALIZE CORRELATION COEFFICIENTS BETWEEN FEATURES AND TARGETS</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*tmxKRRUQqLrbSj4QAeRmkA.png" /></figure><p>From the above correlation heat-map we can observe that “keyword” feature has correlation value with target is 0.55 also, only 0.8% null values also so we will retain this feature.</p><p>We can also observe that our main feature “text” is highly correlated to the target with a correlation coefficient of 1.</p><p>Since “id” feature do not contribute towards identifying whether the tweet is related to disaster or not “id” feature will be dropped.</p><p>3. <em>VISUALIZE COUNT PLOTS FOR TARGETS AND FEATURES</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*sTsg_oG_wmVnriDi_wPx0Q.png" /></figure><p>As observed from above imbalance is not huge between classes, so first approach will be w/o any under-sampling or oversampling technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYhOpylJjKQr7B9yTh0tyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZYCRy-Hd07Tyz3Wp52kZQ.png" /></figure><p>As observed from above, some keywords have equiprobable disaster and non-disaster tweets, whereas some have more probability of disaster related tweets.</p><p>4. <em>VISUALIZE WORD CLOUD FOR BOTH THE CLASSES</em></p><p>WordCloud is a way of visualizing frequency of words in a corpus. Words which are more frequent are displayed in bigger font-size and less frequent in smaller font-size. So the font-size gives the relative idea of frequency of words in the given corpus. Code snippet of plotting the word cloud is as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/009275524ba08653f2e53160cf582873/href">https://medium.com/media/009275524ba08653f2e53160cf582873/href</a></iframe><p>The above code snippet plots the word cloud as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*AfK1lS4W8qVjndXAMOJiVg.png" /></figure><p>Similarly word cloud for disaster related tweets was plotted as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*VXB_vH0DpHAejUSHkNXv2w.png" /></figure><p>From the above we can observe that except some words like (new,one,people &amp; dont) which have high frequency in both class of tweets, there is difference in other high frequency words, for eg. in tweets related to disaster, words like (fire, storm, police, attack, flood) are more frequent and these are not more frequent in non-disaster tweets.</p><p>Before plotting the word clouds the tweet texts were preprocessed so lets take a look at the text preprocessing procedure followed.</p><h3>TEXT PREPROCESSING</h3><p><strong>Steps followed for text preprocessing:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a498af8b6075734d50dc8d7bb5d454ad/href">https://medium.com/media/a498af8b6075734d50dc8d7bb5d454ad/href</a></iframe><ol><li>Remove HTML tags.(Using Beautiful Soup library shown in the above code snippet)</li><li>Remove URLs (Using REGEX)</li><li>Remove text after @ alongwith @ (Using REGEX)</li><li>Expand contracted words (Using REGEX)</li><li>Remove punctuations , : ; “ ‘ . ? (Using REGEX)</li><li>Remove special characters { } ( ) [] &lt; &gt; = + — _ # $ % ^ * / | \ &amp; \n \t \r (Using REGEX)</li><li>Remove all digits (Using REGEX)</li><li>Convert entire text to lower case.</li><li>Remove stop words (Using nltk library): Stop words are frequently occurring words in sentences like “the”, “is”, “and” etc. These words do not contribute much towards determining a context of a given sentence using ML or DL models, which is why they are removed before feeding the text to ML/DL models.</li><li>Perform lemmatization. (Using nltk library) : Lemmatization is the process of converting words to its root form called lemma. It is similar to stemming with the only difference that the root words called stem in stemming may not necessarily be dictionary words but lemma are dictionary words. For eg. “running” will get lemmatized to run, “sleeping” will get lemmatized to sleep.</li></ol><p>The utility function used for text preprocessing which contains the entire pipeline for preprocessing is as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf78e51b85e75faf1faff2113a9060e/href">https://medium.com/media/ebf78e51b85e75faf1faff2113a9060e/href</a></iframe><h3>TRAINING VARIOUS MODELS TO SELECT THE BEST ONE</h3><h4>1. VARIOUS ML MODELS WITH TF-IDF VECTORIZED TEXT</h4><p>The first approach will be converting the text to vectors using TFIDF vectorization and then training Naive-Bayes and Random Forest models with these vector inputs.</p><p>TF-IDF stands for Term Frequency-Inverse Document Frequency which is a method of weighing words in document thus giving us importance of each word in the document and in the collection of documents (also called corpus).</p><p>Term Frequency(TF) is the number of times a word occurs in a document often divided by the total number of words in a document.</p><p>IDF is the number of times a document containing the word occurs in the collection of documents, thus IDF offsets the weight of high term frequency words like “the”, “for”, “and” etc. which occur frequently but are not important for information retrieval.</p><p>We will use Scikit-Learn’s TfidfVectorizer for converting our texts into vector for further feeding into various ML models.</p><p>While training the TFIDF vectorizer we can choose to look at single words in the documents (unigram) or pair/group of words (n-grams) where n = the number of words we want to look collectively at while training the vectorizer.</p><p>Two approaches have been considered here, one with only unigram and other with both unigram and bi-gram(n-gram with n=2).</p><p>The entire dataset is split into training set and cross-validation set. The TF-IDF vectorizer is trained on training set only.</p><p>We convert both the “text” and “keyword” features into vectors using the TFIDF vectorizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*uCTTjc7J-U6eEphcuA6cdw.png" /></figure><p>Now the above generated vectors from texts are fed to Multinomial Naive-Bayes model for training. The Naive-Bayes model uses the following rule for prediction of classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*SN6vM9n5E-Ifo_Lw-4-sxQ.png" /></figure><p>Here P(y) is the relative frequency of a class y in the dataset and P(xi|y) is the probability of a word xi in the text given that it belongs to class y. For whichever class y the value of y-hat is higher, will be selected as the predicted class for the given text. Code for MNB classification is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*F9jfJamaEkMoRwKqByDEJA.png" /></figure><p>Using the TFIDF vectors Decision Tree and Random Forest classifiers are also trained.</p><p>Decision tree model uses a series of nested if and else statements to reach a final decision of assigning a class to the given query, whereas Random Forest model uses many decision trees , it samples subset of data at random and trains many decision trees with them, after which it uses majority vote to assign the class to given query. For a detailed understanding of Decision Tree models work refer my blog : <a href="https://kunalbaidya.medium.com/decision-trees-in-machine-learning-46a7cc730b59">https://kunalbaidya.medium.com/decision-trees-in-machine-learning-46a7cc730b59</a></p><p>Code snippet for training the above mentioned models is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz2TZ29NcOfHy3qx5ikQQA.png" /><figcaption>Training Random Forest Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72Ofz7As-cWF3W1MPAl4Kw.png" /><figcaption>Training Decision Tree Model</figcaption></figure><p>Just as mentioned above we again train the 3 types of classifier models mentioned but this time with TFIDF vectorizers with both unigram and bigram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*DD3QfaJBQFdKpEnDvwdxMw.png" /></figure><p>We can observe that with bigrams also involved the TFIDF vectorizer now considers both individual words as well as pair of words while converting the given text into vectors and hence the number of features has increased to 43142 compared to 110001 in case of unigrams only.</p><h4>2. VARIOUS DEEP LEARNING MODELS FOR CLASSIFICATION</h4><p><strong><em>(A.)</em></strong><em> USING WORD EMBEDDING WITH CNN FOR TEXT CLASSIFICATION</em></p><p>In the first approach the word embeddings for each word in our data vocabulary from the GloVe set are used to initialize the Embedding layer weights. While training the CNN 1D network, Embedding layer is set as non-trainable so it will use the GloVe embeddings only for training.</p><p>In the second approach let the Embedding layer learn the weights while training so the layer is set as trainable.</p><p>In both the above approach after the Embedding layer the architecture used is same:</p><p>2 blocks of conv1D layers, each block having 3 conv1D layers with 32 units followed by concatenation of the 3 layers in the block and then followed by a Max pool layer.</p><p>Above two blocks are followed by 1 conv1D layers → 1 Flatten Layer → 1 Dropout layer → 1 Dense layer → 1 output layer with sigmoid activation for binary classification.</p><p>Adam optimizer is used for optimization and binary_crossentropy as the loss to be minimized.</p><p>For monitoring model performance ROC-AUC score and accuracy score metrics are used.</p><p>We select some prominent words from the WordCloud plotted before and check whether they are present in the GloVe corpus or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MRhXHKb_M2adSvLsbwnRQ.png" /></figure><p>As observed out of selected 27 prominent words from wordcloud, only 4 of them are not present in GloVe set, so it is fair enough to try GloVe embeddings for training the model for text classification.</p><p>In case of our ML models we converted the textual data to vectors using TFIDF vectorizer. In case of CNN model we will convert the textual data to vectors using keras tokenizer, which creates a vocabulary of words from the given dataset and assigns a unique number to each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*R6Wf5w6ZD7ecON-jy9a7sQ.png" /></figure><p>As seen in the above code snippet the text sequences have also been padded i.e. for sequences whose length is shorter than the longest sequence zeros are added to the end of sequence to make their length equal to max_length which is the length of longest sequence/text in the dataset.</p><p>The neural_network model summary which is trained with the above mentioned data is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*7cVHlnGRn_12uQY7TkoVHQ.png" /></figure><p>The code-snippet for creating the above mentioned model architecture is given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/720ae3b08787698628d9855c4811127b/href">https://medium.com/media/720ae3b08787698628d9855c4811127b/href</a></iframe><p>In the Embedding layer of the architecture we pass a matrix emb_mat as weight_initializer. This matrix emb_mat has each row as a 300 dimensional embedding vector of each word in the vocabulary created by tokenizer and the embedding vector is fetched from the GloVe set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14189197b1b497d39e89ecc5fed25bb/href">https://medium.com/media/c14189197b1b497d39e89ecc5fed25bb/href</a></iframe><p>In the second approach we set the Embedding layer as trainable and let the model learn the embedding along with training of entire network.</p><p><strong><em>(B.)</em></strong><em> USING BI-DIRECTIONAL LSTM</em></p><p>In Bi-directional LSTM there are two layers side-by-side, providing the input sequence as-is as input to the first layer and providing a reversed copy of the input sequence to the second. It provides one more context to the word to fit in the right context from words coming after and before, this results in faster and fully learning and solving a problem.</p><p>The model architecture used is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Q3ex_oDwrFc0IrerUfxiTg.png" /></figure><p>The code for building this architecture is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1c7738bfbf3f7891732a65e7933893/href">https://medium.com/media/ce1c7738bfbf3f7891732a65e7933893/href</a></iframe><p><strong><em>(C.)</em></strong><em> COMBINING BOTH CNN AND BI-DIRECTIONAL MODELS</em></p><p>Both CNN &amp; Bi-directional models are combined to try and achieve even better performance score.</p><p>A similar existing approach mentioned below achieves above 0.9 accuracy in sentiment analysis :</p><p>“Bi-LSTM Model to Increase Accuracy in Text Classification: Combining Word2vec CNN and Attention Mechanism” by Beakcheol Jang , Myeonghwi Kim, Gaspard Harerimana, Sang-ug Kang and Jong Wook Kim * Department of Computer Science, Sangmyung University, Seoul 03016, Korea; <a href="/service/mailto:bjang@smu.ac.kr">bjang@smu.ac.kr</a> (B.J.); <a href="/service/mailto:nopkgogo3@gmail.com">nopkgogo3@gmail.com</a> (M.K.); <a href="/service/mailto:gharelim@alumni.cmu.edu">gharelim@alumni.cmu.edu</a> (G.H.); <a href="/service/mailto:sukang@smu.ac.kr">sukang@smu.ac.kr</a> (S.-u.K.) Correspondence: <a href="/service/mailto:jkim@smu.ac.kr">jkim@smu.ac.kr</a>”</p><p>The authors have used word2vec for word embedding whereas for this case GloVe is used for word embedding.</p><p>The main idea of this approach is that 1D CNN is used for feature extraction where it processes text as a one-dimensional image and is used to capture the latent associations between neighboring words whereas LSTM is used to extract contextual information from the features obtained from the 1D CNN layers.</p><p>The authors have also used attention mechanism along with LSTM, which assigns weights to input components that are highly correlated with classification.</p><p>Also for attention mechanism both dot-scoring and Bahdanau scoring will be used to compare the performance.</p><p>Attention mechanism is a process which measures the association of each word in a sentence with other words. The association is measured with a score , higher the score higher the probability of association between words. The scoring can be performed in various ways, two of the methods used here are dot-scoring and Bahdanau scoring.</p><p>The code snippet for creating custom layer for attention is given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b817b22a9f32913589f3912697b754/href">https://medium.com/media/b5b817b22a9f32913589f3912697b754/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5253892f1a8fbd228ca332a66cd895f2/href">https://medium.com/media/5253892f1a8fbd228ca332a66cd895f2/href</a></iframe><p>The architecture for CNN+Bi-directional model is as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*6yepTJx690Rbnq3ZXUQaKQ.png" /></figure><p><strong><em>(D.)</em></strong><em> USING PRE-TRAINED BERT MODEL</em></p><p>In this approach the pre-trained BERT model is used to fetch the encoding of the text and the encoded text is then passed through two dense layers of 768 units each and finally through a dense layer sigmoid activation function for binary classification.</p><p>BERT model used is <strong>bert_en_uncased_L-12_H-768_A-12/2 </strong>which is available is tensorflow_hub library. This pretrained model has 12 encoder layers and 12 attention heads and 768 hidden units.</p><p>BERT stands for Bidirectional Encoder Representations from Transformers. Each encoder in the BERT is a transformer block</p><p>The BERT model requires 3 inputs</p><p>i) the token id : these are the words converted to tokens using the BERT tokenizer unlike keras tokenizer used previously.</p><p>ii) mask input : these are arrays with “0” values for [PAD] tokens and “1” values for the rest. [PAD] tokens are used for padding the texts having length less than maximum text length in the dataset.</p><p>iii) segment id : If there is only one sentence for the classification, total seg vector is 0. If two sentences with [sep] token separation is given , first seq segment vectors are zeros and second seq segment vector are 1’s and so on. Tweet texts being short sequences we preprocess the tweets to convert them into a single sentence by removing all punctuations, so in this case segment id will be array of 0’s with lengh of maximum sequence length.</p><p>The utility function for preparing these inputs is given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d844a90e3b88de678916ebd5dbc5b6/href">https://medium.com/media/18d844a90e3b88de678916ebd5dbc5b6/href</a></iframe><p>The code snippet for creating the network to extract features from text using pretrained BERT model is as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a2277a875ee2263fd60927a22291e08/href">https://medium.com/media/7a2277a875ee2263fd60927a22291e08/href</a></iframe><p>Final model architecture for prediction of tweet type using the extracted features from BERT pretrained model as input is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*W_PDo6JOUHFOQze986mgoA.png" /></figure><p>The performance of all models mentioned above on validation data set are tabulated below in descending order of ROC_AUC_score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*P5cSK2c_5gioRAwUv42LBA.png" /></figure><p>From the above table we select CNN+Bi-directional LSTM model with dot_scoring attention as our best model with highest ROC_AUC_score of 0.854 for deployment. Highest accuracy score is achieved by pretrained-BERT model 0.799 .</p><p>The app for prediction of Tweet type is built using Streamlit, below is the video showing demo of how the app works:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKhdxBtUo_MU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKhdxBtUo_MU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKhdxBtUo_MU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb61f8ba7793916f1f41789a7d57b08d/href">https://medium.com/media/cb61f8ba7793916f1f41789a7d57b08d/href</a></iframe><p>Here is the link to the app, which the readers can play with, to predict whether a tweet is related to disaster or not.</p><p><a href="https://share.streamlit.io/kunal51290/cs2_app_deployment/main/cs2_app.py">https://share.streamlit.io/kunal51290/cs2_app_deployment/main/cs2_app.py</a></p><p>The app deployment python file, saved best model along with the requirements.txt file, procfile and setup file are available in my github repo. Link: <a href="https://github.com/kunal51290/CS2_APP_DEPLOYMENT">https://github.com/kunal51290/CS2_APP_DEPLOYMENT</a></p><p>My linkedin profile : <a href="https://www.linkedin.com/in/kunal-dipakranjan-baidya-43b32b196/">https://www.linkedin.com/in/kunal-dipakranjan-baidya-43b32b196/</a></p><p><strong>References:</strong></p><ol><li>Applied AI course by Applied Roots.</li><li><a href="https://publish.tntech.edu/index.php/PSRCI/article/view/686/225">https://publish.tntech.edu/index.php/PSRCI/article/view/686/225</a> Real or Not? NLP with Disaster Tweets, Kristopher Flint and Zachary Kellerman.</li><li><a href="https://www.xajzkjdx.cn/gallery/1-may2021.pdf">https://www.xajzkjdx.cn/gallery/1-may2021.pdf</a> Natural Language Processing with Disaster tweets using Bidirectional LSTM. Aryan Karnati, Shashank Reddy Boyapally, Dr. Supreethi K.P</li><li><a href="https://machinelearningmastery.com/best-practices-document-classification-deeplearning/">https://machinelearningmastery.com/best-practices-document-classification-deeplearning/</a><br>Using word embedding with CNN for text classification.</li><li>Bi-LSTM Model to Increase Accuracy in Text Classification: Combining Word2vec CNN and Attention Mechanism” by Beakcheol Jang , Myeonghwi Kim, Gaspard Harerimana, Sang-ug Kang and Jong Wook Kim * Department of Computer Science, Sangmyung University, Seoul 03016, Korea; <a href="/service/mailto:bjang@smu.ac.kr">bjang@smu.ac.kr</a> (B.J.); <a href="/service/mailto:nopkgogo3@gmail.com">nopkgogo3@gmail.com</a> (M.K.); <a href="/service/mailto:gharelim@alumni.cmu.edu">gharelim@alumni.cmu.edu</a> (G.H.); <a href="/service/mailto:sukang@smu.ac.kr">sukang@smu.ac.kr</a> (S.-u.K.) Correspondence: <a href="/service/mailto:jkim@smu.ac.kr">jkim@smu.ac.kr</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff0a2100cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CASE-STUDY ON TAARIFA WATER-PUMP STATUS PREDICTION CHALLENGE]]></title>
            <link>https://kunalbaidya.medium.com/case-study-on-taarifa-water-pump-status-prediction-challenge-c4985b5014f3?source=rss-4f3416896fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4985b5014f3</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[ml-algorithm]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal D. Baidya]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 19:28:04 GMT</pubDate>
            <atom:updated>2022-02-04T12:39:13.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*cf0Ry7OALZlJhYSFtMuPyA.png" /><figcaption>CREDITS: <a href="https://medibang.com/picture/ox2001011923126550012116851/">https://medibang.com/picture/ox2001011923126550012116851/</a></figcaption></figure><p><strong>THE PROBLEM</strong></p><p>The challenge here is to be able to correctly predict the operational condition of the water pumps, whether these pumps are functional, non-functional or functional but needs repair. The data related to the water pumps are provided by TAARIFA and Tanzanian Ministry of Water. TAARIFA is an open-source platform for the crowd sourced reporting and triaging of infrastructure related issues. Accurate predictive models for the same can be very helpful to TAARIFA and Tanzanian Govt. to predict the waterpoint failures in advance so that the timely maintenance and repair is conducted, resulting in uninterrupted water supply to the people of Tanzania. Also, timely maintenance and repair of water points will be a financially cheaper option for the Govt. authorities rather than replacing a pump.</p><p><strong>ML APPROACH TOWARDS THE PROBLEM</strong></p><p>From ML point of view this is clearly a multiclass classification problem, where given a query point which in our case will be a water point (various features related to the water point), we have to predict whether it is functional, functional but needs repair or non-functional.</p><p><strong>THE DATA</strong></p><p>The data is provided by the Tanzanian Ministry of water and TAARIFA and is available for download on <a href="https://www.drivendata.org/competitions/7/pump-it-up-data-mining-the-water-table/data/">DRIVENDATA</a> website. The pump prediction problem has been hosted as a competition by <a href="https://www.drivendata.org/competitions/7/pump-it-up-data-mining-the-water-table/page/23/">DRIVENDATA.</a> For each water pump we have the following data available:</p><p>· <strong>‘id’: </strong>Identification number of the water point.</p><p>· <strong>‘amount_tsh’: </strong>The amount of total static head of the water point, TSH is a measure of water available to the water pump.</p><p>· <strong>‘date_recorded’: </strong>The date when the water pump data was recorded.</p><p>· <strong>‘funder’: </strong>By whom the fund for water pump was provided.</p><p>· <strong>‘gps_height’: </strong>The altitude at which the water pump is located.</p><p>· <strong>‘installer’: </strong>Name of the organization which installed the pump.</p><p>· <strong>‘longitude’ &amp; ‘latitude’: </strong>GPS coordinates which give the location of the water point.</p><p>· <strong>‘wpt_name’: </strong>Name of the water point.</p><p>· <strong>‘num_private’: </strong>No information related to this feature available.</p><p>· <strong>‘basin’: </strong>Name of the geographic water basin.</p><p>· <strong>‘subvillage’, ‘region’, ‘lga’, ’ward’: </strong>Name of area describing the geographic location of the water pump.</p><p>· <strong>‘region_code’ &amp; ‘district_code’:</strong> Numeric code describing the geographic location of the water point.</p><p>· <strong>‘population’:</strong> Population around the water point.</p><p>· <strong>‘public_meeting’: </strong>Boolean data whether public meeting for the water pump was conducted.</p><p>· <strong>‘recorded_by’:</strong> Name of agency which recorded the water pump data.</p><p>· <strong>‘scheme_management’ &amp; ’management’:</strong> Name of organization/authority which operates the water point</p><p>· <strong>‘scheme_name’:</strong> Name of scheme under which the water point was established.</p><p>· <strong>‘permit’:</strong> Boolean data describing whether the water point has permit available or not.</p><p>· <strong>‘construction_year’:</strong> Year in which the water point was constructed.</p><p>· <strong>‘extraction_type’, ‘extraction_type_group’, ‘extraction_type_class’: </strong>Description of the method of extraction by which the water point extracts water</p><p>· <strong>‘management_group’: </strong>Management class under which the management authority of the water point falls.</p><p>· <strong>‘payment’, ‘payment_type’: </strong>Describes how the payment for water point is done.</p><p>· <strong>‘water_quality’, ‘quality_group’: </strong>Describes the quality of water available at the water point.</p><p>· <strong>‘quantity’, ‘quantity_group’: </strong>Describes the quantity of water available at the water point.</p><p>· <strong>‘source’, ‘source_type’: </strong>Source of the water for the waterpoint.</p><p>· <strong>‘source_class’: </strong>Class of the source i.e. whether the source is groundwater or surface water.</p><p>· <strong>‘waterpoint_type’, ‘waterpoint_type_group’: </strong>Description of the kind of waterpoint</p><p>The training data set has 59400 data-points/records.</p><p><strong>EXISTING APPROACHES</strong></p><p>There are a few remarkable papers and solutions available for the problem all of which have mostly used Random Forest Classifier to achieve high accuracy. The main focus in each of them and where they mostly vary is data pre-processing and feature engineering. Some of them and their brief summary described below:</p><p><strong>1.</strong> <strong>Kremonic,Zlatan. “Predicting Status of Tanzanian Water Pumps.” Zlatan Kremonic — My</strong></p><p><strong>Mathematical Mind, 23 Jan.2017, </strong><a href="https://zlatankr.github.io/posts/2017/01/23/pump-it-up"><strong>https://zlatankr.github.io/posts/2017/01/23/pump-it-up</strong></a></p><p>The authors of this paper considered the following features useless or non-contributing : [“id”,”amount_tsh”,”num_private”,”scheme_name”] and thus these features were dropped.</p><p>For “Latitude”, “Longitude”, “gps_height” and “population” imputation has been</p><p>carried out by taking the mean of these features within “basin” or any other</p><p>region based feature rather than taking the mean of entire records.</p><p>“Population” feature is transformed by taking log of the values.</p><p>“date_recorded” feature is converted to ordinal form, so that the model has an easier time interpreting it.</p><p>Also 2 new features are created from the “date_recorded” feature, namely “month_recorded” &amp; “year_recorded”, and then these are converted to dummy variables.</p><p>The “construction_year” feature has 35% zero values which are imputed using the mean of all the years.</p><p>The boolean features namely “permit” and “public_meeting” imputed by equating the nulls to False.</p><p>A threshold of 20 was selected for categorical feature values having low frequency and all values having frequency below 20 were all put into a single category named “others”. This was done to reduce overfitting and computational costs. Although the authors suggest increasing the cut-off to 100.</p><p>The model selected by the authors for classification is “Random Forest Classifier” for which they carried out hyperparameter tuning using GridSearchCV, and thus derived the best “min_samples_split” and “n_estimators” as 6 and 1000 respectively. Using the above derived optimal hyperparameters they got an out-of-bag score of 0.8134 and when they do k-fold cross-validation with k=3, they get a score of 0.8071.</p><p><strong>1.</strong> <strong>Agrawal, Karishma, et al. Pump it Up Data Mining for Tanzanian Water Crisis. andrew.cmu.edu , 2015, pp. 1–12, Pump it Up Data Mining for Tanzanian Water Crisis.</strong></p><p>Unlike the previous paper approach where, missing values in “population” feature were imputed using mean of values within a region, here “population” values have been imputed with actual population data fetched from the “Tanzania National Bureau of Statistics”.</p><p>Unlike the previous paper approach where the “amount_tsh” feature was considered useless because most of its values are zero, this feature has been considered important by the authors of this paper. For highly correlated features a similar approach to that of the previous paper has been adopted.</p><p>The authors have clubbed the functional and non-functional class of “status_group” as one label and focused on classification of functional needs repair class from the rest. (This is also contrary to the previous paper approach where ternary classification has been conducted)</p><p>The final classification model consisted of raw data augmented with top 10 principal components obtained from funder and Random Forest made up of 50 trees each with depth of 10. This resulted in the final model performing with 23.45 true positive rate.</p><p><strong>1.</strong> <strong>Alex Pham, Ben Backus, Lauren Zhu. Pump it Up: Mining the Water Table. </strong><a href="https://cs230.stanford.edu/projects_spring_2018/reports/8291176.pdf"><strong>https://cs230.stanford.edu/projects_spring_2018/reports/8291176.pdf</strong></a></p><p>The authors of this paper have performed the classification task using deep learning unlike the above two approaches which use Random Forest.</p><p>Pre-processing carried out were more or less similar to the previous described approaches like one-hot-encoding the categorical data and selecting a threshold to group the less frequent categories in a feature to a single category “others”, for construction year median of years was selected for imputation, for population median of the values within a region(district_code) was calculated for imputation, for date feature day was removed and only month and year were used.</p><p>After trying out various architectures for the deep learning model the authors selected a fully connected network with 9 layer , where input layer has a shape of 432 as after preprocessing they got 432 features, the output layer used was a softmax layer with 3 neurons, the remaining 7 layers had no. of neurons</p><p>(4000,192,96,48,24,12,6,3) respectively, all with ReLu activation unit. Optimizer used was Adam. Loss function used was cross-entropy. The model was trained to 560 epochs with a decaying learning rate initialized to 10^-5 with a decaying rate of 0.99 with a step size of 2000. The train accuracy achieved was 0.785 and test accuracy achieved was 0.786.</p><p><strong>1.</strong> <strong>Addison, Joseph. “Pump it Up: Data Mining the Water Table”. Yet Another Compsci Guy, 12 Jul.2017, </strong><a href="https://jitpaul.blog/2017/07/12/pump-it-up/"><strong>https://jitpaul.blog/2017/07/12/pump-it-up/</strong></a><strong>.</strong></p><p>Like the previous approaches authors of this paper also removed all the redundant features during preprocessing of the data, example : waterpoint_type and waterpoint_type_group, quantity and quantity_group, feature pairs like these have similar observations so retaining one of them will suffice.</p><p>The authors created a new feature “age of the well” using the difference of date_recorded year and construction_year.</p><p>The rows that contained 0 or were missing data were omitted by the authors.</p><p>The authors concluded that Random Forest classifier works best for the classification task and using the same on test data they achieved an accuracy of 80.59%.</p><p><strong>IMPROVEMENT TO EXISTING APPROACHES</strong></p><p>From the above approaches we know that in interest of low computational requirements and for not having a black-box model we should avoid using neural network model for classification.</p><p>Random forest models with larger number of trees, XGBoost models, LGBM models, stacking classifier models and CATBOOST models have been tried to achieve better results than those in the existing approaches.</p><p>New feature apart from those mentioned in existing approaches has been created to combine existing latitude and longitude features into one feature named location.</p><p>Highest accuracy score achieved is 0.8120 and highest weighted F1-score achieved is 0.8040 on the cross validation set. Accuracy score achieved on test set provided by the DRIVENDATA website is 0.8160.</p><p><strong>EXPLORATORY DATA ANALYSIS</strong></p><p><strong>Count plot of total static head (amount_tsh) for each class:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejLItPxx7nSgX9eK_XO70w.png" /></figure><p><strong>Observation: </strong>We have most of the datapoints with amount_tsh = 0 and water points with higher amount_tsh have higher proportion of functional pumps.</p><p><strong>Scatter plot between total static head (amount_tsh) and class labels:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*hXTuSlt0DfPhmpK91pA2lg.png" /></figure><p><strong>Observation: </strong>From the scatter plot of total_static_head vs. class labels we can see that the pumps having tsh above approx.125000 are all functional (there are no non-functional or repair needing pumps with static head more than 125000. So we can say that higher the tsh more the probabilty of a pump being functional that is why tsh may be an important feature</p><p><strong>Count plot of ‘date_recorded’ for each class:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21ugS4Pmt0eH-YU04Hh3jA.png" /></figure><p><strong>Observations: </strong>Nothing much is deducible from the above plot as for most of the month-year the functional and non-functional pumps are equiprobable and for some years the count of non-functional pumps is less but there is no discernible pattern</p><p><strong>Count plot of ‘date_recorded’ for each class:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzXUz3rjFShknk51Z9Br7A.png" /></figure><p><strong>Observations: </strong>There are 266 categories (after pre-processing by grouping less frequent categories) due to which it is difficult to plot and visualize but it is clear from the plot that there are some funders for which the non-functional counts in very high and for some functional is very high, so “funder” feature can be important for prediction of pump status.</p><p><strong>gps_height, latitude &amp; longitude feature analysis:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*ZPAh95fwk27jqUlEy_utKA.png" /></figure><p><strong>Observation:</strong> For GPS heights above 2400 non-funtional and repair needing pumps are very few whereas functional pumps are abundant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYVwa0ncLIj3ofHRPoWd6g.png" /></figure><p><strong>Observation:</strong> As we can see from the above plot that certain regions have high density of functional pumps and certain regions have high density of non-functional pumps. So regional or location related features can be important for predicting the status of pump.</p><p><strong>KDE PLOT FOR POPULATION FEATURE:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUFGl46vbhWZu05Q6PC90Q.png" /></figure><p><strong>Observation:</strong> Highest number of water points are those with missing population data (0 population in dataset), also as population increases functional pumps dominate.</p><p><strong>COUNT PLOT FOR PERMIT &amp; PUBLIC_MEETING FEATURE (BOOLEAN TYPE):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*CIcemkTu4XGZ3J4PfwTdBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*YrpTTdNXir46Q03BEOGcfA.png" /></figure><p><strong>Observation: </strong>From the above plot we can see that for water points with public_meeting as FALSE the difference in proportion of functional pumps and non-functional pumps is not too much, whereas for water points for which public_meeting is TRUE the proportion of funtional pumps in higher than non-functional pumps. So this feature can play important role in predicting the functional status of the pumps.</p><p><strong>SCHEME_NAME FEATURE ANALYSIS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itwpMiDIBSuq40NOyZNkpg.png" /></figure><p><strong>COUNT PLOT FOR SCHEME_MANAGEMENT FEATURE:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*6VSkdjyVPGIAlPiFoSgxRA.png" /></figure><p><strong>Observation: </strong>scheme_management can be an important feature as some scheme_managements have equiprobable pump status whereas for some probability of functional pumps is higher than other two status groups. Also, scheme_management like SWC has higher proportion of non-functional pumps</p><p><strong>COUNT PLOT FOR CONSTRUCTION YEAR FEATURE:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrBy3J9jLw33Mw3zQ9UN7A.png" /></figure><p>35% of the data points do not have the construction year, which have to be imputed with synthetic values like median year or maximum occurring year of construction. Construction year can be useful to generate a new feature as the duration till recorded date of the pump.</p><p><strong>COUNT PLOT FOR WATERPOINT TYPE, WATER QUALITY AND WATER QUANTITY FEATURE:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Ia7eJMwDU_7-4rn7xRRRzA.png" /></figure><p><strong>Observation: </strong>We can see that for “communal standpipe”, “hand pump” and “improved spring” type of water point funtional pumps are higher than non-functional, whereas for “communal standpip multiple” and “other” type of water point non-functional points are higher than functional. Because of these proportions waterpoint_type can be an important feature for determining the status of well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*KUyIS-VMqm9k_AmzCHGe1w.png" /></figure><p><strong>Observation: </strong>As we can see when water is soft, there are more functional wells whereas for other types of water non-functional pumps are more or equiprobable, thus water type is a feature important for prediction of well status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*yHw81oHoDmrAldmYFi13Dw.png" /></figure><p><strong>Observation: </strong>As we can see when water is enough in quantity proportion of functional pumps is much more than non-functional pumps compared to when quantity is insufficient, when well is dry almost all of them are non-functional.</p><p><strong>COUNT PLOT OF PAYMENT TYPE, EXTRACTION TYPE AND SOURCE TYPE FEATURES:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*Jp4wF35nm3iL0lGehGeNrA.png" /></figure><p><strong>Observation: </strong>Payment type can be an important feature as some category have equiprobable pump status whereas for some probability of functional pumps is higher than other two status groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*4atk9v6R7R6fKzxi5itECQ.png" /></figure><p><strong>Observation: </strong>Extraction type can be an important feature as some category have almost equiprobable pump status whereas for some probability of functional pumps is higher than other two status groups and categories like “other” and “mono” have higher non-functional pump counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*b0Q6sh-DBmmtVx6e4ifAkA.png" /></figure><p><strong>Observation: </strong>Source type can be an important feature as some category have equiprobable pump status whereas for some probability of functional pumps is higher than other two status groups.</p><p><strong>CORRELATION BETWEEN NUMERICAL FEATURES:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*UuaawFLnxiK_1Ph9VWBUsw.png" /></figure><p><strong>Observation: </strong>region_code and district_code are highly correlated with a corr. coef of 0.68 as observed from the above correlation map, out of these two district_code is weakly correlated with the class label (0.066 corr. coef), so we can drop district_code and retain region_code. gps_height is not strongly correlated with the other two features so we can retain it.</p><p><strong>CLASS LABELS (status_group feature):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*uxBjIf9ITqKfV7uhbU6pbA.png" /></figure><p>Dataset is imbalanced as we have 32,259 functional pumps whereas non-functional are 22,824 i.e. 9435 less and functional but needs repair are very less only 4317</p><p>Since the data set is imbalanced w.r.t class labels, metric used will be “Weighted F1-score” as it gives weightage based on the number of instances in each class thus accounting for the imbalance. Also, confusion matrix will be plotted to check for the proportion of correctly predicted class.</p><p><strong>MULTIVARIATE ANALYSIS BETWEEN NUMERICAL FEATURES:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9mKew4xNVLH7MU5M4hAgg.png" /></figure><p><strong>Observation:</strong> From the above pair plots we cannot figure out any decision boundary for classification between the class labels. We can observe that in region with high values of gps_height population is less, also that above 1,25,000 tsh all pumps are functional which was already observed in univariate analysis of “amount_tsh” feature.</p><p><strong>IDENTIFYING SIMILAR FEATURES:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKifsTvedo60gX2fJ5tLcA.png" /></figure><p><strong>Observation: </strong>Out of 21 categories in region 18 are present in subvillage, so region feature can be dropped.</p><p>Subvillage and ward feature also have 844 common categories so we can drop ward feature also if we want.</p><p>Out of 125 categories in lga feature 59 are present in subvillage, so lga can be dropped if we want.</p><p>Basin feature do not have much in common with other features so it should be retained.</p><p><strong>Other features found similar are as follows:</strong></p><p>· 5 out of 7 categories in ‘source_type’ feature are also present in ‘source’ feature, so we can drop any one of them.</p><p>· 4 out of 6 categories in ‘quality_group’ feature are already present in ‘water_quality’ feature so we can drop the ‘quality_group’ feature.</p><p>· ‘quantity’ and ‘quantity_group’ features have the same categories so we can drop ‘quantity_group’ feature.</p><p>· 5 out of 7 categories from ‘extraction_type_class’ feature are present in ‘extraction_group_type’, 7 out of 13 categories from ‘extraction_type_group’ feature are present in ‘extraction_type’ feature. So, we can keep ‘extraction_type’ feature and drop other two.</p><p>· All categories of ‘waterpoint_type_group’ are present in ‘waterpoint_type’ feature so we can drop ‘waterpoint_type_group’ feature.</p><p>· We can keep ‘management’ feature and drop other two as ‘scheme_management’ has similar categories which couldn’t be detected in set intersection due to text style difference, also 3 out of 5 categories in ‘management_group’ feature are present in ‘management’ feature.</p><p>· ‘payment’ and ‘payment_type’ both features have same categories so we can drop one of them.</p><p><strong>DATA PRE-PROCESSING</strong></p><p><strong>1.</strong> <strong>DROPPING OFF NON-CONTRIBUTING FEATURES:</strong></p><p>Following similar features identified in EDA were removed:</p><p>[“source_type”,”quality_group”,”quantity_group”,”extraction_type_group”,”extraction_type_class”,</p><p>“waterpoint_type_group”,”payment_type”,”management_group”,”scheme_management”,”region”,</p><p>“district_code”]</p><p>Since name of water point &amp; id are not useful in the prediction, the ‘wpt_name’ &amp; ‘id’ feature are dropped.</p><p>All the instances of ‘recorded_by’ feature are same “GeoData Consultants Ltd” , so this feature is dropped.</p><p>98.72% of the instances in ‘num_private’ feature are 0 so we drop the feature.</p><p><strong>2.</strong> <strong>COMBINING FEATURES:</strong></p><p>‘latitude’ and ‘longtitude’ features are combined into a single feature ‘location’ by calculating the Euclidean distance from origin. Haversine distance can also be tried in place of Euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB00rS3YsNWXr0c88DIOGg.png" /></figure><p>‘construction_year’ and ‘date_recorded’ features have been combined to create a new feature age of pump by calculating the difference between these two features, for this the date_recorded feature has been converted to year and then construction_year subtracted from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRdvnJQKpI5cxXJIsTz3sQ.png" /></figure><p><strong>3.</strong> <strong>ENCODING THE CATEGORICAL FEATURES</strong></p><p>Following are the categorical features in the dataset:-</p><p>{ ‘funder’ , ‘installer’ , ‘basin’ , ‘subvillage’ ,’lga’, ‘ward’, ‘public_meeting’ ,’scheme_name’ ,’permit’ ,’extraction_type’, ‘management’ ,’payment’ ,’water_quality’ ,’quantity’ ,’source’ ,’source_class’ ,’waterpoint_type’ }</p><p>Of the above listed categorical features ‘permit’ and ‘public_meeting’ features are Boolean type so we convert them into 0’s and 1’s as well as imputing the null values with 0’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC_RNgWxc0TGAKNITY1KlA.png" /></figure><p>Since the quantity feature categories can be ordered it is encoded numerically in increasing order of quanity where in unknown is assigned 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnhQd0Di7EVyoGfWWDMIpw.png" /></figure><p>For rest of the categorical features first the categories having count/frequency less than 20 are grouped into a single category “other”. After this one hot encoding is performed on each of the feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McS-qRuAXwH1HBafVwDawg.png" /></figure><p><strong>EXPERIMENTING WITH VARIOUS ML MODELS</strong></p><p>FOLLOWING ARE THE VARIOUS MODELS WHICH WERE TRAINED ON 80% OF THE TRAINING DATA</p><ol><li><strong>SUPPORT VECTOR MACHINE CLASSIFIER WITH RBF KERNEL</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfOn4LEg_Mmasc0T9f7GLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*KcZM4xoVdJHTLbDWJ2qtLw.png" /></figure><p>SVC with RBF kernel performs mediocre with 0.755 f1-score and 0.775 accuracy score. As we can see from the confusion matrix the minority class “functional but needs repair” is the one which is misclassified the most.</p><p><strong>2.</strong> <strong>SUPPORT VECTOR MACHINE CLASSIFIER WITH POLYNOMIAL KERNEL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9_JYdD2IkbzBjiofV7nhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*EtSlUSZ5z1nIzBL5vvCUJQ.png" /></figure><p>As we can observe SVC with polynomial kernel of degree 4 performs almost similar to SVC with RBF kernel with marginal increase in the performance metric.</p><p>As observed from the confusion matrix only a 13.5% of minority class is correctly classified by both the SVM models thus we cannot use these models for accurate prediction.</p><p><strong>3.</strong> <strong>DECISION TREE MODEL</strong></p><p>Scikit-learn’s Decision Tree Model has been used for prediction of cross-validation set with hyper parameter tuning. Hyperparameters such as max-depth, min_samples_split, min_samples_leaf, splitting criterion have been tuned with RandomizedSearchCV of 5 folds to get the best model before fitting it to the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqhJH3PUZK-EdG4FUu_Exw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBI4Q_UVKQNnyHT2Vb2i7g.png" /></figure><p>Performance metrics of decision tree model is almost similar to SVM classifier but the misclassification of minority class is lesser, 25% of minority class are correctly classified compared to 13.5% in case of SVM.</p><p><strong>4.</strong> <strong>LIGHT GRADIENT BOOSTING MACHINE MODEL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igFZJPo5AOoHvLW-c3_e3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*l-9q3DPfUHyw-0kQ4QehyQ.png" /></figure><p>As we can observe that the accuracy score and f1-score of LGBM model is much better than SVM and decision trees at 0.8009 and 0.7909 respectively. Also, the minority class correctly classified instances are 27.69%, which is more than that of decision tree model.</p><p><strong>5.</strong> <strong>XGBOOST MODEL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gZUIGxA1nmg83SkWYuN-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAAlCRllUmemO9gaQWj6vA.png" /></figure><p>From the above we can observe that f1-score &amp; accuracy score for XGBOOST model has lower accuracy score than LGBM model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*bXzDxQRFxovsXEf25ltglg.png" /></figure><p>From the confusion matrix we can deduce that although accuracy score and f1-score are less, the model performs better on minority class with correctly classified instance of 31.6% compared to 27.69% of LGBM model.</p><p><strong>6.</strong> <strong>RANDOM FOREST MODEL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fk8tF-4a7SXtsid4kctW5w.png" /></figure><p>As compared to the existing solution paper where maximum number of trees used was 1000 for random forest, here we can observe that hyperparameter tuning using RandomizedSearchCV gives best number of trees = 1500.</p><p><strong>Performance of Random Forest Model:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wK7xW1LoJoKaIcswpg8bZQ.png" /></figure><p>As we can observe the random forest model performs poorly on minority class compared to XGBoost model, correctly classified points are 28.8% compared to 31.6% of XGBoost model, but the overall accuracy score and f1-score are higher 0.8120 and 0.8027 respectively.</p><p>Using all the above model’s various combinations 6 types of stacking classifiers were build and performance of all of them are tabulated in the next page. Also, code snippet for one of the stacking-classifier displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWgIgHtDq5b0unb-1NV_sQ.png" /></figure><p><strong>TABULATED PERFORMANCE OF ALL THE ABOVE-MENTIONED ML MODELS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*FEIJV-XHiqMjN6Nxo96eYg.png" /></figure><p><strong><em>Stacking Classifier-1: </em></strong><em>Using SVM, Decision tree model &amp; RFC stacked classifiers &amp; XGB as Meta_classifier</em></p><p><strong><em>Stacking classifier-2: </em></strong><em>Using SVM, Decision tree model &amp; XGB stacked classifiers Random Forest as Metaclassifier</em></p><p><strong><em>Stacking Classifier-3: </em></strong><em>Using XGBClassifier as Metaclassifier and removing the svm classifier</em></p><p><strong><em>Stacking Classifier-4: </em></strong><em>Using RandomForest as Metaclassifier and removing the svm classifier</em></p><p><strong><em>Stacking classifier 5: </em></strong><em>LGBM, SVM, Decision tree model &amp; RFC stacked classifiers and XGBoost as Metaclassifier</em></p><p><strong><em>Stacking classifier 6: </em></strong><em>LGBM, Decision tree model &amp; RFC stacked classifiers and XGBoost as Metaclassifier</em></p><p>· As observed in the table the Accuracy score and f1-score of top3 models are with 1000 trees with 1500 trees the results achieved are accuracy_score = 0.8120 and f1_score = 0.8027 for the top-3 models.</p><p>· Since RFC is more time efficient compared to the stacking classifiers with same accuracy, RFC has been used to further pump up the accuracy of model with the help of further model tuning and data pre-processing experiments.</p><p>· CATBOOST model was also tried with explicit one hot encoding and with its implicit feature of converting the categorical features by just giving the input of column index related to the categorical features. The model with explicit one hot encoding performed better but not better than RFC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*hbQmUjfxHm2x8nyOk1uBMA.png" /></figure><p><strong>EXPERIMENT WITH OVERSAMPLING:</strong></p><p>Since our data set is imbalanced with 32,259 functional pumps whereas non-functional are 22,824 i.e., 9435 less and functional but needs repair are very less only 4317, up sampling of the dataset with SMOTE method was tried.</p><p>SMOTE over sampling with k_neighbors value of 5 &amp; 20 was tried on RFC model of which k_neighbors = 20 gave better results than k_neigbors=5, so SMOTE over sampled data with k_neighbors = 20 was used to train and measure performance of the previously experimented top models.</p><p>Each of the top models trained on SMOTE over-sampled data achieved similar performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*3TDZOHQWWc7NiH9NDjcNHQ.png" /></figure><p>As observed accuracy score is not better than that of the RFC model achieved on original dataset.</p><p>Also, the SMOTE oversampled data with manually entered class size was tried with but this also didn’t achieve better results than that of models trained on original dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*finZD11489wyRoB4F5YT1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHC-sSiiBql9gJo9V_27_A.png" /></figure><p><strong>POST TRAINING ANALYSIS:</strong></p><p>In order to try and find out any pattern among the misclassified points, post training analysis was carried out on misclassified points.</p><p>1. VISUALIZING THE MISCLASSIFICATION ERRORS</p><p>Here misclassification error is calculated for each predicted instance in the cross validation set and plot a scatterplot of these errors to visualize the pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*k2Db86--qm2gk4U_H3NhGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2oOrOvkPxSY7Ko3OYhyjw.png" /></figure><p>2. TSNE VISUALIZATION OF MISCLASSIFIED AND CORRECTLY CLASSIFIED CROSS-VALIDATION DATA POINTS</p><p>Here we make two different dataset of misclassified and correctly classified instances and label the misclassified points as “0” and correctly classified as “1”. Then using TSNE we visualize the data in 2-D in order to discern if there are any separate clusters of the misclassified instances indicating they are different from the correctly classified ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAWM0VB9-uDAhWrjv9ukFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9IYzORNqdzriSG6Sx9DtA.png" /></figure><p>3. COMPARING THE FEATURE WISE DISTRIBUTION OF MISCLASSIFIED AND CORRECTLY CLASSIFIED DATA POINTS</p><p>On comparing various feature wise distribution of misclassified and correctly classified instances it is observed that for every feature the distribution of both types of points is similar except the fact that counts of features in misclassified points are lesser than that in correctly classified points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4Tt8NAJWl7nxLR3xYXuwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNCkoNp68W7nQnOagNl2qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJHesa1JYsymZEJ5X6ueIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BScPRV4MRlQRjiIHXtTa2w.png" /></figure><p><strong>PUMPING UP THE ACCURACY</strong></p><p>As mentioned earlier the case being studied here is also hosted as a competition in the DRIVENDATA website.</p><p>From the above read we can see that highest accuracy achieved is 0.8120, but with further experimentation I was able to achieve an accuracy of 0.8134 on cross-validation set. Applying this model on the test set provided by DRIVENDATA an accuracy score of 0.8189 was achieved on the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAUBxh19r7su-1taejAE8w.png" /></figure><p>This further boost in accuracy was achieved by changing the following:</p><p>· While imputing the “0” values in “population” feature instead of imputing it with median value of entire training set the mean value was calculated for same “basin” feature and imputed accordingly.</p><p>· “amount_tsh” feature was removed. (70% of “0” values may be is missing data)</p><p>· RFC with trees in range 800–2000 was tried and 900 trees gave the best results, also while hyper-parameter tuning GridSearchCV was used including other hyper-parameters like class_weight and max_samples.</p><p><strong>FUTURE WORKS</strong></p><p>In order to pump up the accuracy score and thus making the model even more useful for prediction further experiment with data preprocessing will be continued to try and match or surpass the top accuracy scores in the leaderboard of the competition. Some ideas to be tried are:</p><p>· Trying various values of frequencies for grouping of less frequent categorical features.</p><p>· Trying label encoding in place of one hot encoding for categorical features.</p><p>· Trying with construction year and date recorded features separately instead of combining them.</p><p>· Using one hot encoding for “water_quantity” feature instead of custom ordinal label encoding.</p><p><strong>MY LINKEDIN PROFILE: </strong><a href="https://www.linkedin.com/in/kunal-dipakranjan-baidya-43b32b196/">https://www.linkedin.com/in/kunal-dipakranjan-baidya-43b32b196/</a></p><p><strong>REFERENCES</strong></p><p>.Case-study performed under guidance of mentor from AppliedRoots team. <a href="https://www.appliedaicourse.com/course/11/Applied-Machine-learning-course">https://www.appliedaicourse.com/course/11/Applied-Machine-learning-course</a></p><p>· Kremonic,Zlatan. “Predicting Status of Tanzanian Water Pumps.” Zlatan Kremonic — My Mathematical Mind, 23 Jan.2017. <a href="https://zlatankr.github.io/posts/2017/01/23/pump-it-up">https://zlatankr.github.io/posts/2017/01/23/pump-it-up</a></p><p>· Agrawal, Karishma, et al. Pump it Up Data Mining for Tanzanian Water Crisis. andrew.cmu.edu , 2015, pp. 1–12, Pump it Up Data Mining for Tanzanian Water Crisis.</p><p>· Alex Pham, Ben Backus, Lauren Zhu. Pump it Up: Mining the Water Table. <a href="https://cs230.stanford.edu/projects_spring_2018/reports/8291176.pdf">https://cs230.stanford.edu/projects_spring_2018/reports/8291176.pdf</a></p><p>· Addison, Joseph. “Pump it Up: Data Mining the Water Table”. Yet Another Compsci Guy, 12 Jul.2017, <a href="https://jitpaul.blog/2017/07/12/pump-it-up/">https://jitpaul.blog/2017/07/12/pump-it-up/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4985b5014f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DECISION TREES : UNBOXING THE BLACK BOX]]></title>
            <link>https://kunalbaidya.medium.com/decision-trees-in-machine-learning-46a7cc730b59?source=rss-4f3416896fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a7cc730b59</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[applied-ai]]></category>
            <dc:creator><![CDATA[Kunal D. Baidya]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 15:34:14 GMT</pubDate>
            <atom:updated>2021-09-07T07:29:58.269Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>DECISION TREES : UNBOXING THE BLACK BOX</strong></p><p>Being a civil engineer myself and thus belonging from a non coding background I understand how difficult it is sometimes for those like me who are trying to learn the concepts of machine learning.</p><p>So here I will try to explain the concepts of decision trees which is a very simple but powerful model in machine learning so that everyone who reads this can understand the basic concepts and how to apply it.</p><ol><li><strong>A brief description of decision trees &amp; their use</strong></li></ol><p>In a very simple language decision trees can be described as a network of decisions where we make a decision at each step and that decision leads us to another until a final decision is reached or it can also be described as a set of nested if-else statements.</p><p>Don’t know what an if-else statement is?</p><p>Well some of you might be scared as to it is some very high level concept used by programmers and is beyond our level of understanding. Let me tell you that you are wrong my friend. It is as simple as making your daily decisions in a regular life. You are using the logic of if-else statements since a long time in your day to day life. For example when you decided that today I will not go to school but your mind started reasoning with if-else statements , if I won’t go to school then parents might scold me, the next day my teacher might punish me, but if I go(this is the else statement) I may get bored the whole day.</p><p>Jokes apart, we will put this logic to use in a real-world application with real data in the next section, before that lets know what do we use decision trees for.</p><p>Uses: Decision trees are used for classification of data sets based on some given features or characteristics. For example:</p><p>Given the length, width and height of a t-shirt classify it into a size like Small, Medium or Large.</p><p>They can also be used to predict real values for example given the age, weight and gender of a person predict his/her height.</p><p>Technically decision trees are supervised machine learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable or class of the data by learning simple decision rules based on the features of data set.</p><p><strong>2. Understanding the data set</strong></p><p>Here I will use a very simple and easy to understand data set created by me for the ease of computation and interpretation.</p><p>So the data set given below consists of 3 criteria (the first three columns) based on which a company decides whether to shortlist a candidate for interview or not.</p><p>If we create an automated model and provide it to the company they just have to feed the 3 criteria related data of the candidates into the model and it will classify which candidates to call for interview and which to reject.</p><p>Isn’t it fascinating? Of course it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*j6udM_ebf6IEDvz_YOcZGw.png" /><figcaption><strong>Figure-1</strong></figcaption></figure><p>As said above the data set here has 3 criteria(first 3 columns except the serial no.) which are ‘Matriculation in science’, ‘Graduate student’ and ‘Graduation CGPA ≥ 5’ and the last column is the decision based on these three criteria whether to call the candidate or not viz. ‘call for job interview’.</p><p>Still intimidated by the number of yes and no in the table? Let me explain with a few data points from the table.</p><p>Look at the data in sr. no. 1 of the data set, it says that the candidate has matriculation in science? : yes, is the candidate a graduate? : yes, is the graduation CGPA of candidate ≥ 5? : yes. since all three criteria are satisfied the candidate will be called for interview? : yes.</p><p>Now look at sr. no.4 the candidate is a graduate student? yes, graduation CGPA ≥ 5? : yes, but candidate has a matriculation in science? no, since this criteria is not satisfied the candidate will be called for interview? : no.</p><p>In sr.no.5 and sr.no.12 the other 2 criteria are not satisfied so candidate is not being called for interview.</p><p>So by studying the data set we can say that only when all three criteria are satisfied a candidate will be called for an interview.</p><p>The above decision making can be visualized using a branched out flow chart as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*ttnyyTnws1S00JA3d_rSLw.png" /><figcaption><strong>Figure-2</strong></figcaption></figure><p>Isn’t this even simpler to understand? This is what a decision tree is.</p><p>While the above decision tree is what we created using our logic and understanding of the data set, the machine/computer model does the same in a slightly different way. So now lets understand how the ML model builds a decision tree. It makes use of some thing called ENTROPY and INFORMATION GAIN. So let us first understand how to derive these two values.</p><p><strong>3. Entropy and information gain</strong></p><p>Entropy is the measure of dominance of a single class in data set.</p><p>The more is the dominance of single class in a data set the lesser is the entropy.</p><p>The lesser is the dominance of a single class in data set, i.e. the data set has equal proportion of all classes, the more is the entropy.</p><p>Lets consider our own data set, we have total 30 data points or samples and 2 classes yes or no(call for interview: yes, call for interview: no). Out of the 30 samples we have 12 samples of class ‘yes’ and 18 samples of class ‘no’.</p><p>Class ‘yes’ samples are only 6 less from class ‘no’ samples so dominance of a single class is not significant and hence entropy will be high.</p><p>Entropy is calculated using the below formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*XPvrT4XYMgWcuIiGf6x_Lw.png" /></figure><p>H(y) is entropy for given y classes</p><p>k is the number of classes (in our case 2 i.e. yes and no)</p><p>P(yi) is the probability of a class yi</p><p>lg is log to the base 2.</p><p>Derivation of this formula is beyond the scope of this article. So now lets calculate the entropy for our data set.</p><p>Probability of class yes p(yi =yes) = 12/30 i.e. out of total 30 samples 12 samples of yes class and p(yi = no) = 18/30.</p><p>H(y) = -(12/30)*lg(12/30)- (18/30)*lg(18/30) = 0.97</p><p>Entropy has the highest value 1 in case of 2 class data sets when both the classes are of equal proportion and lowest value of 0 when data set have data of only one class. So 0.97 is quite high entropy value.</p><p>Now lets branch out our data set as per our decision tree in Figure-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*deNDvMNe3hSJo3QaRE6t-A.png" /><figcaption><strong>Figure-3</strong></figcaption></figure><p>The first branch out is based on whether the candidate has matriculation in field of science or not. From above figure-3 if yes then we get a dataset say D1, if no we get another data set say D2.</p><p>Now for D1 &amp; D2 we get the entropy as 0.97 and 0.00 respectively</p><p>Now we calculated the weighted entropy of these 2 data sets and sum them up, weightage of D1 is no. of sample in D1/total no. of samples in entire data set i.e. 20/30 similarly for D2 weightage is 10/30.</p><p>Weighted entropy = (20/30)*0.97 + (10/30)*0 = 0.64</p><p>So lets summarize till now we calculated the entropy of entire dataset H(y) = 0.97 then we did the first branch out with whether the student has matriculated or not in field of science and got 2 branched out data sets , for which we calculated the weighted entropy = 0.64</p><p>Now the difference between the entropy of entire data set and the weighted entropy of branched out data sets is called the information gain IG.</p><p>In our case IG = 0.97- 0.64 = 0.33.</p><p><strong>4. How the ML model builds decision trees</strong></p><p>Now that we know how to calculate entropy and information gain let me tell you how the machine learning model uses these values to build a decision tree.</p><p>The ML model considers branching out from a criteria/feature based on the IG value, the feature/criteria which has the maximum IG value on branching out is considered as the parent node for branching out, also the next level branching out is done using the same concept in our data set the IG values using the three features as parent node are as follows:</p><p>IG(Matriculation in science) = 0.33 (calculated in previous section)</p><p>IG(Graduate student) = 0.28 (calculate this as an exercise)</p><p>IG(Graduation CGPA &gt;= 5) = 0.477 (calculate this as an exercise)</p><p>So we get the highest value of IG as 0.477 when we branch out using ‘Graduation CGPA ≥5’ as the parent node and that is what the ML model will do exactly and we will see that practically in next section. So unlike using our logic where our parent node for branching out was ‘Matriculation in science’ the ML model branches out using the feature where we get the highest IG value.</p><p>And we keep continuing this till we get the nodes with zero entropy and these final nodes are called leaf nodes and the number of time we have to branch out till reaching the leaf node from parent node is called the depth of the decision tree. The more the depth the more complicated our decision tree is and less the depth lesser complex is our decision tree.</p><p>This depth of decision tree is the hyper parameter in case of decision tree model which we have to tune using cross-validation in order to find the optimum or best depth.</p><p>Enough of theoretical chit-chat right? So lets get into action and write the code for classification of data using decision trees.</p><p>Here I assume a few pre-requisites that you are familiar with Jupyter notebooks, basic Sci-kit learn, basic pandas and basic python for ML.</p><p><strong>5. Code for building a classifier using decision trees</strong></p><p><strong>a) </strong>We read the csv file of our data set and save it as a data frame ‘df’ and visualize the first 10 rows of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*rT9Y0znRaXSt9X294Dt9-A.png" /></figure><p><strong>b)</strong> Lets get the information of all columns/features of our data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*U3t5iDwW4yDq4oRBHLsINA.png" /></figure><p><strong>c)</strong> As we can see that the 3rd column or the feature ‘Graduation CGPA ≥5’ has only 21 non-null values and 9 null values which are null for candidates who have not graduated, since they have no graduation they do not have any graduation CGPA. We can fill these null values with 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uo_yN-8Xe-zuFgctcs1lQ.png" /></figure><p><strong>d)</strong> The sci-kit learn decision tree model cannot classify based on categorical data i.e. our type of data which has 2 categories yes and no. We have to convert these categorical type data into numeric data so that the sklearn decision tree can interpret it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*ybgqyjIREkxco_I8vFHMAg.png" /></figure><p><strong>e)</strong> Now we separate the class labels/dependent variables from the independent variables/features as X and y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*MGdwIh6q1vydJrfPbjKwaw.png" /></figure><p><strong>f)</strong> Now we split the data into training set and test set with 80:20 proportion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*7cWtoKoQK7Z6bEjoq8E0xQ.png" /></figure><p><strong>g)</strong> Now we perform five fold cross-validation using random search cv on our training data set Xtrain &amp; ytrain in order to find the best hyperparameter i.e. depth of our decision tree. For this we pass a list of hyper-params [2,3,4,5,8,10] as we can see from below that cross-validation yields the best hyper-parameter max_depth(depth of decision tree) as 2. Also observe that we have selected the criterion = ‘entropy’ for decision tree so the tree will be built using entropy &amp; IG. It can also be built using another criterion i.e. gini impurity for which we have to pass the criterion = ‘gini’. For accuracy we have selected the F1-score performance metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*LEzDrp6HnRFRdOS2d_XMng.png" /></figure><p><strong>h)</strong> Now let us train the model using the optimum hyper-parameter derived in step g) and get the predictions for Xtrain and Xtest.</p><p>Using the F1_score metric we will also get the accuracy of test data predictions and train data predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*LgPGs5KQ2fmtJRz9CqYZPw.png" /></figure><p><strong>i) </strong>Now let us plot the decision tree for our Xtrain data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*-IO9T_sU3iVXw2PyAx2yig.png" /></figure><p>As we can see from the decision tree it has a depth 2 which was selected as optimum by cross-validation. Also as discussed in our theories the leaf nodes have an entropy of 0.</p><p>Observe another thing here that the decision tree has selected a threshold value for each feature here it is 0.5 if any feature has value &lt; 0.5 then for our case it means feature has value 0 or ‘no’ and if this condition is false means that feature has value 1 or ‘yes’.</p><p><strong>j)</strong> Now finally lets build the decision tree for entire data set using the optimum decision tree model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*RdDKcecijNO1f5P6r8d5Lg.png" /></figure><p>From the above decision tree we can now verify our entropy value we calculated as 0.97 is correct, also the parent node is with the feature ‘Graduation CGPA ≥5’ as we stated in section 4 that when branching out with this feature as parent node we get the highest IG value.</p><p><strong>References:</strong></p><p>1. sci-kit learn documentation</p><p>2. Lecture videos from Applied AI course of Applied Roots</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a7cc730b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>