<?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 Ashish Thomas Chempolil on Medium]]></title>
        <description><![CDATA[Stories by Ashish Thomas Chempolil on Medium]]></description>
        <link>https://medium.com/@ashishthomaschempolil?source=rss-9a080999c1f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t80ISXVwg5jNcUax-qN5sw.jpeg</url>
            <title>Stories by Ashish Thomas Chempolil on Medium</title>
            <link>https://medium.com/@ashishthomaschempolil?source=rss-9a080999c1f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:06:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashishthomaschempolil/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[Medical Image Captioning on Chest X-Rays]]></title>
            <link>https://medium.com/data-science/medical-image-captioning-on-chest-x-rays-a43561a6871d?source=rss-9a080999c1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43561a6871d</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[medical]]></category>
            <dc:creator><![CDATA[Ashish Thomas Chempolil]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 04:54:25 GMT</pubDate>
            <atom:updated>2021-02-09T23:22:17.723Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating an Image captioning deep learning model which can write automatic medical reports as part of self case study using Tensorflow and Keras</h4><figure><img alt="Image of two doctors operating" src="https://cdn-images-1.medium.com/max/1024/0*rFzqVek_VlpeJT3g" /><figcaption>Photo by <a href="https://unsplash.com/@designer4u?utm_source=medium&amp;utm_medium=referral">Olga Guryanova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Table of Contents</h3><ol><li>Business problem</li><li>Use of Machine learning to solve the business problem</li><li>Evaluation metric (BLEU score)</li><li>Dataset</li><li>Existing solutions</li><li>Exploratory data analysis</li><li>Data Preprocessing</li><li>Input Data Pipeline</li><li>Pre-requisites</li><li>My Experiments and Implementation details</li><li>Summary and Results</li><li>Conclusion</li><li>Future work</li><li>Link to my profile</li><li>References</li></ol><h3><strong>1. Business Problem</strong></h3><p>Medical imaging is the process of creating visual representations of the interior of a body for clinical analysis as well as visual representation of the function of some organs or tissues. They are widely used in hospitals and clinics to determine fractures and diseases. The medical images are read and interpreted by specialized medical professionals and their findings regarding each body of area examined are communicated via written Medical Reports. The process of writing medical reports usually takes around 5–10 minutes per report. In a day the doctors have to write medical reports that number in 100s which can take a lot of their time. The objective of this case study is to build a deep learning model that automatically write the impression part of medical report of chest X-rays and alleviate some of the burden of the medical professional. Here I will be taking a publicly available dataset from Indiana University which consists of chest X-ray images and reports (in XML format) which contain information regarding the findings and impression of the X-ray. The goal is to predict the impressions of the medical report attached to the images.</p><h3>2. Use of Machine learning to solve the business problem</h3><p>This problem is an image captioning task. For this dataset, we are given a couple of images of different patients and report which is in xml format. The information of the image names and also the patients are contained within the xml file. We will extract this data from xml file using regex and transform it into a dataframe. Then we can use pretrained models to get information from images and using this info we can generate caption using LSTMs or GRUs.</p><h3>3. Evaluation metric (BLEU score)</h3><p>BLEU score stands for Bilingual Evaluation Understudy. Here we will be using BLEU score as the metric. BLEU score compares each word in the predicted sentence and compare it to the reference sentence (It is also done in n-grams) and returns score based on how many words were predicted that were in the original sentence. BLEU score is not a good metric to compare the performance of translation since similar words that have the same meaning will be penalized. So we will not only use n-gram BLEU score but also take a sample of the predicted captions and compare it to the original reference caption manually. BLEU scores range from 0–1.</p><blockquote><strong>Predicted text:</strong> “The dog is jumping”</blockquote><blockquote><strong>Reference text:</strong> “The dog is jumping”</blockquote><p>Here for this case, we will have a BLEU score(n-grams) of 1. Here are very good articles for further reading on the topic.</p><ul><li><a href="https://towardsdatascience.com/bleu-bilingual-evaluation-understudy-2b4eab9bcfd1">BLEU — Bilingual Evaluation Understudy</a></li><li><a href="https://machinelearningmastery.com/calculate-bleu-score-for-text-python/">A Gentle Introduction to Calculating the BLEU Score for Text in Python - Machine Learning Mastery</a></li></ul><h3>4. Dataset</h3><p>Here I will be taking a publicly available dataset from Indiana University which consists of chest X-ray <a href="https://academictorrents.com/details/5a3a439df24931f410fac269b87b050203d9467d">images</a> and <a href="https://academictorrents.com/details/66450ba52ba3f83fbf82ef9c91f2bde0e845aba9">reports</a> (in XML format) which contain information regarding the comparison, indication, findings and impression of the X-ray. The goal of this case study is to predict the impressions of the medical report attached to the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*7-Eb8jc4qi9fnslblXAhxw.png" /><figcaption><a href="https://academictorrents.com/details/66450ba52ba3f83fbf82ef9c91f2bde0e845aba9">Sample report taken from data source</a></figcaption></figure><h3>5. Existing Solutions</h3><p><a href="https://towardsdatascience.com/image-captioning-with-keras-teaching-computers-to-describe-pictures-c88a46a311b8">Image Captioning with Keras | by Harshall Lamba</a>: Here he has used flicker 8k images as the dataset. For each image there are 5 captions and he has stored them in a dictionary. For data cleaning, he has applied lowercase to all words and removed special tokens and eliminated words with numbers (like ‘hey199’, etc.). After extracting unique words he removed all those words whose frequency was less than 10 in the entire corpus so that model can be robust to outliers. Now he added “startseq” and “endseq” to each captions. For preprocessing of the images he has used inception v3 model with Image net dataset weights. Images were sent to this model and the output of the second last layer was taken (2048 size vector, bottleneck features) and saved these vectors. For preprocessing of captions he has tokenized the captions and also found out the maximum length of the sentence in the captions (found to be 34) so that he can use it for padding. He has used pretrained Glove vectors for word embeddings (200 dimensions) and also set trainable = False for the embedding layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JIKLOO6YK_CMWMmd" /><figcaption><a href="https://towardsdatascience.com/image-captioning-with-keras-teaching-computers-to-describe-pictures-c88a46a311b8">Source</a></figcaption></figure><p>This is the model architecture he has used for training which is self explanatory. The output from the above model gives a probability value for which word has the highest probability to come next in the sentence. Here he is using greedy search method (gets the word which has the highest probability to come next in the sentence). The model was then trained for 30 epochs with the initial learning rate of 0.001 and 3 pictures per batch (batch size). However after 20 epochs, the learning rate was reduced to 0.0001. Loss used is categorical cross entropy while optimizer used was Adam.</p><p><a href="https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e">Image Captioning using Attention Mechanism | by Subham Sarkar | The Startup</a>: Here he has used attention mechanism for image captioning. The dataset used is flickr8k same as before. Here the train size was 6000 images, validation data size was 1000 images and test data size was 1000. For preprocessing he has removed punctuation, numeric values and single characters. Then he creates a dataframe with columns filename and captions. He has reshaped each image into 224*224*3 before feeding it to a pretrained on ImageNet VGG-16 model. Here he has only taken convolutional part (include_top=False). He has removed the last dense layer and has taken the output from the second last layer as backbone features.</p><p>For captions, he has tokenized and added &lt;unk&gt; as the token for recognizing those words which are not in the vocabulary. He has padded the tokenized sequence with that of the maximum length of sentence found in the corpus (=39).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*qVtSSDFJxhashobk" /><figcaption><a href="https://arxiv.org/pdf/1508.04025.pdf">source</a></figcaption></figure><p>For attention mechanism he has used both global attention and local attention and did not combine them but instead gave an option of choosing which attention to use, here in the code file he has used only local attention. Global attention looks at the image as a whole while local attention focus on specific parts of an image (in the context of image captioning). This is done by considering the hidden states to derive the context vector. The global attention considers all the hidden vectors while local attention considers a specific window of hidden vectors per target word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*qPSwBz1192Qgj2aF" /><figcaption><a href="https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e">Global attention</a></figcaption></figure><p>The encoder here is the VGG-16 model. The decoder is RNN. Here he is using GRU. He has used teacher forcing method here whereby he input the actual tokens as the next input instead of the predicted tokens for the decoder gru at different time steps during training. The different steps for global attention and local attention are explained below:</p><p>Attention Mechanism:</p><ol><li>The features that are considered as encoder hidden states are features from VGG-16 here.</li><li>The previous decoder hidden state and decoder output is passed through decoder gru to generate a new hidden state and prediction probability score.</li><li>Using all the hidden states from encoder and new decoder hidden state we will calculate the attention scores. These attention scores are then softmaxed to give probability scores (which all part should be given attention to)</li><li>Using this probability scores he calculated the context vector by multiplying each scores with encoder hidden states (here cnn features) then gives it to GRU.</li><li>This is repeated until it reaches the padded length.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*Aejenm0pBKV7i5Jf" /><figcaption><a href="https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e">Local Attention</a></figcaption></figure><p>Now for evaluating the captions he has used two methods beam search and greedy search. Here the number of predictions considered for beam search was b=3,7,10 (top b predictions). Beam prediction gets the caption with the most probability (i.e. here he sums up the probability values for each word and evaluates the final probability of that sentence/caption).</p><p>Here he has used the BLEU score as the metric to evaluate the prediction. He built a custom loss function which only penalizes based on the word that are in the caption. He has used an Adam optimizer.</p><p><a href="http://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">A good blog for further understanding of Attention mechanism.</a></p><h3>6. Exploratory Data Analysis</h3><h4>Images</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*xOUgrVK8Un03nd3brptPYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kA_3OKd6XtBYnBxfFy5KbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*3Yi-tvdR707jqSgaN6lKWA.png" /><figcaption>X-rays from the dataset</figcaption></figure><p>We can see 3 sample images of the dataset. These are chest X_rays which are taken in front and side view.</p><h4>Reports</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*7-Eb8jc4qi9fnslblXAhxw.png" /><figcaption><a href="https://academictorrents.com/details/66450ba52ba3f83fbf82ef9c91f2bde0e845aba9">Sample report taken from data source</a></figcaption></figure><p>This is a sample report. The report is stored in xml format. We will extract comparison, indication,findings and impression part of the report. This was done using regex. <a href="https://regex101.com/">Here is a very good website that I used to test my regex code which will be very helpful for you guys.</a></p><p>The number of the reports in the data are found to be 3955.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSd6rQAR9qNjvjwZK6y8ug.png" /><figcaption>In the xml file, report information is stored like this.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*oWh9UaRC1xSYqn9t0AYVIQ.png" /></figure><p>These are the two image files that are associated with this report. Now we will see what is the maximum and minimum possible value for number of images that are associated with a report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtFRrldaBGvqqRkftJD6xA.png" /></figure><p>We can see that the maximum number of images associated with a report can be 5 while the minimum is 0. We will extract all the information part ie comparison, indication, findings and impression part of the report and the corresponding 2 images (we will take 2 images as input as 2 images are highest frequency of being associated with a report) of the concerned report to a dataframe with xml report file name using regex and string manipulations. For images more than 2, we will create new datapoints with new image and same info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqnHGFMrNG3F-P3XwDu3JQ.png" /><figcaption>This is the sample dataframe we get after extracting the information from the xml report</figcaption></figure><p>It was found that there are missing values in the dataframe. All the datapoints which had their image_1 and impression value null were removed from the dataframe. Then for all the missing values found in image 2 were filled with the same data path of that of image 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRKV7_nkJzB7EmWDXRhdsg.png" /><figcaption>Distirubution of image_1 and image_2 heights</figcaption></figure><p>We can see from the above diagram that 420 is the most common image height for image1 while 624 is the most common image height. Width for both of the images have only 1 unique value for all datapoints and that is 512. Since pretrained models are modelled for square-sized images we can choose 224*224 (same as that of input to VGG16) as the specified size of the image. Hence we will resize all images into 224*224 shape.</p><h4>Sample Images along with Captions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auUFkmCC6dvgSWsW3vZKIA.png" /><figcaption>Images + Captions</figcaption></figure><p>We can see that findings are the observations from X-ray while impression is inference obtained. In this case study, I will try to predict the impression part of the medical report given the two images.</p><h4>Word-cloud of all the impression values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*ov-UNimn2iasvuInbTrG6g.png" /></figure><p>We can see from the word-cloud above that several words are higher in frequency i.e “acute cardiopulmonary” and “cardiopulmonary abnormality”. We will investigate this further by observing the value counts of the impression feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIYqsS5yi37GBws7tYBh4g.png" /><figcaption>Top 20 most frequently occurring value for impression column</figcaption></figure><p>From the above value counts we can see that top 20 most frequently occurring words had the same meaning thereby the same information suggesting one type of data is dominating for this data. We will apply a set of upsampling and downsampling to the data so that model doesn’t output the same value for entire dataset i.e to reduce over-fitting.</p><h3>7. Data Preprocessing</h3><p>Since from what we have seen from the most of the X-rays that were given, majority of the datapoints had captions with similar meaning that is “no disease” or “no acute cardiopulmonary abnormality”. So to reduce over-fitting, first I will remove all those duplicated data points (ie those which had more than 2 images associated with one caption) keeping only one and then split the dataset based on value counts of the impression into two where one with all the impression value counts greater than 5 (other1) and other being value_counts&lt;=5 (other2). Then split the other1 data with test_size=0.1. A sample of 0.05*other2.shape[0] will be then taken and will be added on to the test data that was split. The other data from the other2 will be appended to train.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c35cd6ad9a94187295c7381a5b428893/href">https://medium.com/media/c35cd6ad9a94187295c7381a5b428893/href</a></iframe><p>Now I will upsample and downsample the train dataset. For that I will further divide the dataset into 3, one with impression value counts greater than or equal to 100 (df_majority), 2nd one with value counts lesser than or equal to 5 (df_minority) and final one where the impression value counts between 100 and 5 (df_other). Then df_majority and df_other will be downsampled and df_minority will be upsampled. Finally the number of datapoints of the resulting concatenated dataframe is 4487.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d23567bf3a07864453e79010245f41ee/href">https://medium.com/media/d23567bf3a07864453e79010245f41ee/href</a></iframe><p>After sampling, the text will be added ‘&lt;start&gt;’ and ‘&lt;end&gt;’ towards the start and end of the impression column. Now after fitting the tokenizer, I have decided to use the 80th percentile value of length of caption to be taken as maximum padded value for each impression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJw8lrrDDNgvXUhWy3KV8Q.png" /></figure><h3>8. Input Data Pipeline</h3><p>First I will explain how I created my input data pipeline for this case study. First I will create a class named Dataset which contains __getitem__, __len__ method. __getitem__ method is called whenever the an object of Dataset classed is called with element index passed to it (i.e like a[i]). __len__ method must be there for every class which has __getitem__ which returns the number of items that class Dataset contains (here it will be the number of rows in df). Here I will apply random augmentation of Flip (both left,right and up,down). Also it was found that applying embossing and sharpening greatly reduced the model’s performance so it was discarded. The Dataset class will output two resized image feature vectors and padded tokenized true caption input(does not contain &lt;end&gt;) and true caption output(does not contain &lt;start&gt;).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80e9031e2f71b4a5e40a4d1a062dae49/href">https://medium.com/media/80e9031e2f71b4a5e40a4d1a062dae49/href</a></iframe><p>Next class I have created is called Dataloader which inherits from tf.keras.utils.Sequence class. Here the dataloader will output datapoints as batches, where the ith index will output as (image1,image2,input captions),output captions. It will return batch_size number of datapoints for the ith index.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d479a24f7733e2d40ec681d066fa8c0d/href">https://medium.com/media/d479a24f7733e2d40ec681d066fa8c0d/href</a></iframe><h3>9. <strong>Pre-requisites</strong></h3><p>These are the some of the topics that the reader has to familiarize to fully understand the modelling part:</p><ol><li><a href="https://keras.io/guides/transfer_learning/">Transfer Learning</a></li><li><a href="https://www.tensorflow.org/tutorials/text/image_captioning">Attention Mechanism</a></li><li><a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models">Model Sub-classing API</a></li><li><a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention">Encoder Decoder Models</a></li></ol><h3>10. My Experiments and Implementation details</h3><p>For the modelling part I have created 3 models. Each one will have a similar encoder but entirely different decoder architectures.</p><h4>Encoder</h4><p>Encoder part will take the two images and convert it into backbone features to provide to the decoder. Here for encoder part I will be using CheXNET model.</p><p><a href="https://arxiv.org/pdf/1711.05225.pdf">CheXNET Model</a> is a Denset121 layered model which is trained on millions of chest x-ray images for the classification of 14 diseases.We can load the weights of that model and pass the images through that model. The top layer will be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkSin18kOgTb-U7TrZrjmg.png" /><figcaption>Final layers of CheXNET</figcaption></figure><p>Now I will create an Image Encoder layer which contains chexnet model which is same as outlined as before. Here I will set the chexnet model trainable as false.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/624ed34807a701de456a57d243180cd7/href">https://medium.com/media/624ed34807a701de456a57d243180cd7/href</a></iframe><h4>Simple Encoder Decoder Model</h4><p>This model will be our baseline. Here I will built a simple implementation of an image captioning model. The architecture will be as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sn2x0PPRYFzckgR11OK3KA.png" /><figcaption>Simple Encoder Decoder Model</figcaption></figure><p>Here I will pass the two images through the Image_encoder layer and concatenate the two outputs and then pass it through the Dense layer. The padded tokenized captions will be passed through an embedding layer where we will be using pretrained Glove vectors (300 dimensions) as the initial weights for the layer. This will be set as trainable and then it is passed through LSTM where the initial state of the LSTM is taken from the output of Image_dense layer. These are then added and then passed through output_dense layer where the numbe of output will be the vocabulary size with softmax activation applied on top.</p><p>For training, I have chosen “adam” optimizer and created a loss function based on Sparse categorical loss where I have only considered the losses of the words in the true captions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472133df6b5c8d1974dabe619d8200e3/href">https://medium.com/media/472133df6b5c8d1974dabe619d8200e3/href</a></iframe><h4>Attention Model</h4><p>Here for this model I will be using Global Attention and using the concat equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*qPSwBz1192Qgj2aF" /><figcaption><a href="https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e">Global Attention</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe5c116b83dbe43fbd524d4c327d52d/href">https://medium.com/media/3fe5c116b83dbe43fbd524d4c327d52d/href</a></iframe><p>For the decoder, I have created a one_step_decoder layer which takes in decoder_input, the encoder_output and state value. The decoder_input will be any character token number. This will be passed through the embedding layer and then embedding output and the encoder_output will be passed through the attention layer which will produce the context vector. The context vector will then be passed through the RNN (here GRU will be used) with initial state being that of previous decoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebfb833c4e2021752e04ea36337cdcfb/href">https://medium.com/media/ebfb833c4e2021752e04ea36337cdcfb/href</a></iframe><p>The decoder model will store all the outputs in an tf.TensorArray and return it. Here I will be using teacher forcing method to train the RNN where instead of passing the output of the last rnn’s output I will pass the next original token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db7bea5d8b4aa74229eaa590efff8c46/href">https://medium.com/media/db7bea5d8b4aa74229eaa590efff8c46/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgHU_36CA3CkOqojmmXn8w.png" /><figcaption>RNN decoder (Image by the author)</figcaption></figure><p>s1 will be the zeros here. All i’s will be the original token after passing it through attention layer along with encoder output.</p><h4>Final Custom Model</h4><p>Here I will be using a custom encoder along with decoder which is same as that of the Attention Model.</p><p>For the encoder part for this model I will be extracting the backbone features from the chexnet model specifically 3rd last layer’s output. This will be the output from the Image_encoder layer. Then I will pass it through global flow and context flow which is actually inspired from another model which was used for image segmentation purposes. This will be explained below.</p><p><strong>Global Flow and Context Flow: </strong>This architecture implementation is taken from <a href="https://arxiv.org/abs/2002.12041v3">Attention guided chained context aggregation for image segmentation</a> (Specifically <strong>Chained Context Aggregation Module (CAM)</strong>) which was used for image segmentation but I will use it to extract image information. Here what I will do is that the outputs from Image encoder (ie chexnet) will be sent to global flow. Then outputs from both the chexnet and global flow will be concatenated and sent to context flow. Here only one context flow will be used since our dataset is small and can lead to underfitting if a more complicated architecture is used. <strong>Here</strong> <strong>global flow extracts the</strong> <strong>global information of image while context flow will get the local features of the images</strong>. Then the output from the global flow and context flow will be summed and then sent to decoder after reshaping, and applying batch norm and dropout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KcC14Tsjf0HB-Ie61tjEA.png" /><figcaption><a href="https://arxiv.org/abs/2002.12041v3">Attention guided chained context aggregation for image segmentation</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*3bt307f7ste6qcmXTHSzcA.png" /><figcaption>Global Flow</figcaption></figure><p><strong>Global Flow</strong></p><ol><li>Here Global flow will take the information from Image encoder layer and then I will apply global average pooling which will result in (batch_size,1,1,no. of filters).</li><li>Then we will apply batch normalization, relu, 1*1 Convolution and upsample to the same shape as the input.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07961ee010e852a944a3e1e2c6b73984/href">https://medium.com/media/07961ee010e852a944a3e1e2c6b73984/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t5B0As6PVk0JVKnzuAPxQ.png" /><figcaption>Context flow</figcaption></figure><p><strong>Context Flow</strong></p><ol><li>We will get the data from both global flow and the image encoder layer and concat it on the last axis.</li><li>This is then applied average pooling which reduces the size of feature map by N* times.</li><li>Then a 3*3 single convolutions will be applied twice. (No CShuffle will be applied)</li><li>After that we will apply 1*1 convolutions, followed by relu activation, then again 1*1 convolutions followed by sigmoid activation. This is multipled with output from context fusion module and then added to output from the context refinement model which will then be upsampled with the same size as the input (here conv2d transpose will be used to get the same number of filters as of that of the input).</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/429849ad4fa66df766b7ec1f58591724/href">https://medium.com/media/429849ad4fa66df766b7ec1f58591724/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lazWDWBw1RcGdvnLew4f7w.png" /><figcaption>Custom Final model</figcaption></figure><p>The summed output of both context flow and global flow will be concatenated (here add_1 and add_2 are results of image_1 and image_2 respectively) then will be sent to Dense layer which converts the no. of filters to 512 which after a series of reshaping, batch normalization and dropout will be sent to decoder. The decoder architecture is the same as that of the Attention model.</p><h3>11. Summary and results</h3><p>Beam search and greedy search methods were used to analyse the predictions. Greedy search just outputs the most probable word in each time-step while beam search shows the most probable sentence by multiplying probability of each word at each time-step and getting the sentence which has the highest probability. Greedy search is much more faster compared to beam search while beam search is found to produce correct sentences. Further readings on the topic:</p><ul><li><a href="https://machinelearningmastery.com/beam-search-decoder-natural-language-processing/">How to Implement a Beam Search Decoder for Natural Language Processing - Machine Learning Mastery</a></li><li><a href="https://towardsdatascience.com/an-intuitive-explanation-of-beam-search-9b1d744e7a0f">An intuitive explanation of Beam search</a></li></ul><h4>Simple Encoder Decoder model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*VXzua5LE5eZGp_52DVC64A.png" /><figcaption>BLEU score for simple encoder decoder model</figcaption></figure><p>The bleu scores of both greedy search and beam search (top_k = 3) is found to be similar so we can say that the best model will be based on greedy search for the simple encoder decoder model since it is the fastest. Finding bleu score for top_k = 5 was found to be very slow so it was discarded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebK-OlcVgHWZliNFCpz3wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjvIA261nNEIvzzLb-8o5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1HWmZ3atq4Es93ngp6brg.png" /><figcaption>Results on sample test data</figcaption></figure><p>We can see from above that model has predicted the same caption for all images. It was found that model predicted the same caption for all images when taking the value counts as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDH4r-1Zr1xchVcok9uM2Q.png" /><figcaption>Value counts of predicted captions</figcaption></figure><p>From the above results, we can see that for every datapoint the model is predicting “no acute cardiopulmonary abnormality” suggesting the model has overfitted. Since this is a baseline model we can check on the other models predictions and compare their performance to this.</p><h4>Attention Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*J1Dc35Frqtmq0JXdZogqUg.png" /><figcaption>BLEU score for Attention Model</figcaption></figure><p>Based on the bleu score, this model performed similar to that of simple baseline model. Beam search (top_k = 3) was found to be slow in predicting one caption so the approach was discarded. Now we will observe some random predictions to see how well the model is doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kixXRwi0M3q_KNiBPljF6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tn8I79UrmiRtbwKvuxKitA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twpJFj7cvwC-m6KrylYG5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYn74IwKTmFbGw_ShGaPSA.png" /><figcaption>Here also some of the words are predicted correctly</figcaption></figure><p>This model performed better than simple baseline model since it produced captions which had higher variability and also remained linguistically similar. From the value counts of the predictions, it was seen that model has predicted sentences with more variability than the baseline model.</p><h4>Final Custom Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*yBafO0A7O5IRJlR71g1VOw.png" /><figcaption>Bleu Scores for Final Custom Model</figcaption></figure><p>This model also produced similar bleu compared to other two. Looking at the value counts of the predictions we can see that there is a little variability better than that of the baseline model but not as good as that of the 2nd model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNxDekj4lbgoaFwbf1YayA.png" /><figcaption>Value counts % of predictions for final custom model</figcaption></figure><p>Here also same as the case of Attention model, beam search (top_k = 3) was found to be slow in predicting one caption so the approach was discarded.</p><p>Some random predictions on test data are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_j5FESjeiOnPuNyoC_pthw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3ECwJdcL40dHV6pmkxnKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmWjUVQl5CVS94me0HiLhg.png" /></figure><p>We can observe from the above that the model is predicting only those images which have no disease correctly but for others it is not. We can conclude that Attention model is the best performing model out of the three.</p><h3>12. Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d1rbxdqWxKNuil4qxGdjQ.png" /><figcaption>Best Models of each approach arranged in descending order of cumulative BLEU-4 score</figcaption></figure><p>These are the best models of each approach in terms of bleu score. Here the list is sorted based on <strong>cumulative BLEU-4</strong> score. The best model we obtained was Attention Model(greedy search). This model performed far better than other two models since it was able to output names of diseases and some observation more correctly than others. Other models only outputted the caption assuming all the datapoints shown were of “no disease category”. The simple encoder decoder model was only able to output one caption for the entire dataset suggesting overfitting. More data with much more variability specifically X-rays with diseases can be much more helpful for the models to understand better and can help reduce bias towards “no disease category”.</p><h3>13. Future work</h3><ol><li>We can use BERT to get caption embeddings instead of using embedding layers with glove vector weights and use it as inputs to the decoder.</li><li>Instead of using Attention decoder in the final custom model, we can try using simple decoder.</li><li>We can also use Visual BERT. Or try using GPT-2 or GPT-3 in the decoder to generate captions.</li><li>Get more X-ray images with diseases since most of the data that is available on this dataset were of “no disease” category.</li></ol><h3>14. Link to my profile — Github code and LinkedIN</h3><p>You can find the complete code for this case study on this <a href="https://github.com/ashishthomaschempolil/Medical-Image-Captioning-on-Chest-X-rays"><strong>github link</strong></a>. You can connect me on <a href="https://www.linkedin.com/in/ashishthomas7/"><strong>Linkedin</strong></a> or at <strong>ashishthomas7@gmail.com</strong>. I have also created a <strong>Web App using Streamlit</strong>. You can view the app <a href="https://share.streamlit.io/ashishthomaschempolil/medical-image-captioning-on-chest-x-rays/main/final.py"><strong>here</strong></a>.</p><h3>15. References</h3><ol><li>Q. Tang, F. Liu, T. Zhang, J. Jiang, Y. Zhang, <a href="https://arxiv.org/abs/2002.12041v3">Attention-guided Chained Context Aggregation for Semantic Segmentation (2020)</a></li><li><a href="https://www.appliedaicourse.com/">Applied AI Course</a></li><li><a href="https://towardsdatascience.com/image-captioning-with-keras-teaching-computers-to-describe-pictures-c88a46a311b8">https://towardsdatascience.com/image-captioning-with-keras-teaching-computers-to-describe-pictures-c88a46a311b8</a></li><li><a href="https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e">https://medium.com/swlh/image-captioning-using-attention-mechanism-f3d7fc96eb0e</a></li><li><a href="https://machinelearningmastery.com/beam-search-decoder-natural-language-processing/">https://medium.com/r/?url=https%3A%2F%2Fmachinelearningmastery.com%2Fbeam-search-decoder-natural-language-processing%2F</a></li><li><a href="https://towardsdatascience.com/an-intuitive-explanation-of-beam-search-9b1d744e7a0f">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Fan-intuitive-explanation-of-beam-search-9b1d744e7a0f</a></li><li><a href="https://towardsdatascience.com/bleu-bilingual-evaluation-understudy-2b4eab9bcfd1">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Fbleu-bilingual-evaluation-understudy-2b4eab9bcfd1</a></li><li><a href="https://machinelearningmastery.com/calculate-bleu-score-for-text-python/">https://medium.com/r/?url=https%3A%2F%2Fmachinelearningmastery.com%2Fcalculate-bleu-score-for-text-python%2F</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43561a6871d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/medical-image-captioning-on-chest-x-rays-a43561a6871d">Medical Image Captioning on Chest X-Rays</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Santander Customer Satisfaction — A Self Case Study using Python]]></title>
            <link>https://medium.com/data-science/santander-customer-satisfaction-a-self-case-study-using-python-5776d3f8b060?source=rss-9a080999c1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5776d3f8b060</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[customer-satisfaction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ashish Thomas Chempolil]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 11:30:32 GMT</pubDate>
            <atom:updated>2021-06-06T21:42:28.593Z</atom:updated>
            <content:encoded><![CDATA[<h3>Santander Customer Satisfaction — A Self Case Study using Python</h3><h4><em>Classification modeling on the Santander Customer Satisfaction dataset in Kaggle as part of self case study using Python (</em><a href="https://github.com/ashishthomaschempolil/Santander-Customer-Satisfaction">github link</a> and <a href="https://www.linkedin.com/in/ashishthomas7/"><strong>Linkedin</strong></a><strong>)</strong></h4><h3><strong>Table of Contents</strong></h3><ol><li>Business problem</li><li>Use of Machine learning to solve the business problem</li><li>Evaluation metric (Area Under the Curve)</li><li>Exploratory data analysis</li><li>Feature engineering</li><li>Existing solutions</li><li>My Experiments with models</li><li>Summary, results and conclusions</li><li>Future work</li><li>Link to my profile — Github code and Linkedin</li><li>References</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wa0XrjVPkRdCoS9z" /><figcaption>Photo by <a href="https://unsplash.com/@garrettpsystems?utm_source=medium&amp;utm_medium=referral">garrett parker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Business Problem</h3><p>This case study is based on <a href="https://www.kaggle.com/c/santander-customer-satisfaction">Kaggle competition</a> conducted in the year 2016. Customer satisfaction is one of the most important key performance indicators in every company today and is seen as a key element of a company’s success. Unhappy customers don’t stick around. What’s more, unhappy customers rarely voice their dissatisfaction before leaving. Santander is a Spanish multinational corporation bank and financial based company which operates in Europe, North and South America, and also Asia. In this Kaggle competition that is conducted by Santander we need to predict whether a customer is dissatisfied with their services early on based on the features provided by the company. This will help them to take proactive steps to improve the customer satisfaction before the customer leaves.</p><h3>2. Use of Machine learning to solve the business problem</h3><p>This problem is a classification modelling task to determine whether a customer (datapoint) is dissatisfied or not.</p><p>We are given two files :a test.csv and train.csv which contains around 370 features which are anonymized and 1 dependent feature that is TARGET. Each datapoint represents a customer and the value in TARGET will be 1 if a customer is dissatisfied with the company’s service and 0 if he is satisfied and also the dataset is heavily imbalanced.</p><h3>3. Evaluation Metric (Area Under the Curve)</h3><p>The metric used here is the <strong>area under the ROC</strong> (receiver operating characteristic) curve which is the <strong>area under the plot between True Positive Rate (Sensitivity or Recall)(TPR) and False Positive Rate(FPR) at different thresholds</strong>. AUC helps in determining whether a model is good at distinguishing between classes. Higher the AUC, better the model is at predicting 0s as 0s and 1s as 1s. AUC of 0.5 means the model is making random guesses(random model) while AUC of 0 means that the model is predicting 0s as 1s and 1s as 0s whereas AUC of 1 is that of a perfect classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*aTjmvEn58RmgtuSa.png" /><figcaption><a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">Source</a> — AUC is the area under the curve of ROC</figcaption></figure><p>Here is a very good article on AUC.</p><p><a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">Understanding AUC - ROC Curve</a></p><h3>4. Exploratory data analysis</h3><p>We will first delve deep into the dataset and observe all the features through visualizations which will aid us in getting conclusions as well as ideas for feature engineering. There are 370 features in total which are all anonymized (not including the ‘TARGET’ feature). We were able to get what information an anonymized feature convey from literature review and also by observing distribution of the values.</p><p>Since there were many features, we will check for features having <strong>zero variance</strong> (does not hold any information ie only 1 unique values present) and will remove them if found.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d973047e88f4867dd06d9ec59f14f4/href">https://medium.com/media/f4d973047e88f4867dd06d9ec59f14f4/href</a></iframe><p>34 features were found to have zero variance and these were all removed.</p><p>We will now check for <strong>features that were duplicated</strong> (ie they shared same values across datapoints need not be the same feature name).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aab614bc6d8926cf7ca3b4a89c9510b/href">https://medium.com/media/7aab614bc6d8926cf7ca3b4a89c9510b/href</a></iframe><p>12 features were found to be duplicated and of this 6 were removed.</p><p>We will now remove all <strong>sparse features</strong> (features that have little information). A condition is set such that if feature has 99 percentile value to be 0 then it is considered as a sparse feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dc648964500bb5144b223375b47cd09/href">https://medium.com/media/9dc648964500bb5144b223375b47cd09/href</a></iframe><p>No missing values were also found.</p><p>The final number of features after removing unnecessary features are 142.</p><p>Now we will explore each feature.</p><h4>4.1 TARGET</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*L5d-Xfr_LvNLiAidLXvjLw.png" /></figure><p>We can see that the dataset is highly imbalanced with only 3.96% being of unsatisfied customers and 96.04% being satisfied customers.</p><h4>4.2 var3 (Region)</h4><p>From looking at other literature and also at the number of unique values present (=208) this feature may be holding the information of the region where the customer is from. There is also an outlier in this feature which is -999999 which may be missing value. The values ranged from 0 to 208 except for the outlier. The most common unique value is found to be 2 (around 97% for both train and test data). Firstly we will convert all -999999 to -1 values and explore the value counts considering only values which does not include ‘2’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*EV6w3gDPpCZTfO2EWo7Qog.png" /><figcaption>Value counts of ‘var3’ excluding most common value ‘2’</figcaption></figure><p>Since looking at the value counts we can see that -1 represent only a small fraction of the entire dataset (even after excluding 2). So we will replace the missing values with most frequent value for this feature which is ‘2’.</p><h4>4.3 var15 (Age)</h4><p>The minimum value of var15 is found to be 5 and maximum value is 105 in train data. Since the value of var15 is from 5–105, it is safe to assume that this feature implies age of the customer. This is also evidenced in literature review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88BAZgKOh7XEjRvVQmfb2A.png" /></figure><p>Both the train and test data had similar distribution, both consisted of younger customers the most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*6UDJil9fqMHUvaU5PTbH4Q.png" /></figure><p>The minimum age of unsatisfied customers was found to be 23. It seems that every young customer (below the age of 23) are satisfied always. So we can create a new feature during feature engineering which essentially tells whether a customer is below the age of 23 or not.</p><h4>4.4 var38 (mortgage values)</h4><p>From the various literature in kaggle it was inferred that var38 might be the mortgage values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*GyLH_R3_3j8_gnn49H3ikg.png" /><figcaption>Value Counts of var38</figcaption></figure><p>Here we are not able to get any information as one value is having very high frequency. We will print out each percentile values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*_Vog7bn41XZMcSQRvvqICw.png" /><figcaption>var38 values in percentile</figcaption></figure><p>We can see that there is a huge difference between 0 percentile value and 10 percentile value. This is the same case for 90 percentile value and 100 percentile value. Now we will check the distribution plot of var38 for all values that are below 97.5 percentile (above 97.5 percentile value 1 value is dominating, cannot extract usable information)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*gvSTqqU7qGGMTC8heG6_hA.png" /></figure><p>We can see that the above plot is right skewed with a outlandish peak between 100,000 and 150,000. We can apply log transformation and check the resulting distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*lYUZ8DdMPMXYMGTILz-vBg.png" /><figcaption>After applying log transformation</figcaption></figure><p>We can see that it looks similar to a normal distribution. Since machine learning models work better on normal distribution, we can create new datasets with log transformation and without log transformation for this feature and compare the performances during feature engineering phase.</p><h4>4.4 Features with keywords</h4><p>There were several features which had specific keywords in them which were: ‘imp’, ‘ind’, ‘num’, ‘saldo’ . These keywords were found to be short-forms for some spanish words which were obtained from several literature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*LkmrzFnBYR6t0rzNRrgODA.png" /></figure><p>‘num’ features had the highest representation in the dataset.</p><p>Now what we will do is explore each keyword feature 1 by 1 by randomly selecting 2 features for each keyword and we will draw conclusions.</p><h4><strong>4.4.1 ‘imp’ feature</strong></h4><p>‘imp’ likey is shortened word for importe which is Spanish for amount(inferred from literature review). The total number of features with ‘imp’ keyword are 14. By looking at the value counts of the two randomly selected feature that had ‘imp’ keyword in them, we can see that the most common occurring value is 0 for both of them. 0 accounted for more than 87% for both of these features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhIlwXz5Lsu-dmtmlIzyiQ.png" /><figcaption>Frequency plot of a randomly selected ‘imp’ feature train and test data respectively</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLdPGmSLmzBziZA-I1ljfw.png" /><figcaption>Distribution of a randomly selected ‘imp’ feature not including 0 after log transformation</figcaption></figure><p>Here also after log transformation, the distribution(excluding 0) becomes a lot like guassian. So we can put down a strategy for all ‘imp’ features.</p><p><strong>Strategy for ‘imp’ features:</strong></p><ol><li>We can create a new dataset with log transformed (excluding 0) imp features.</li><li>We can also create another dataset with no transformations applied (leaving as it is).</li></ol><h4>4.4.1 ‘saldo’ feature</h4><p>The number of features with saldo keyword are 26. Now we will approach the data similar to how we approached ‘imp’ feature. By looking at the value counts for the 2 features we can see 0 is the most frequent value here also (around 95% of the entire train dataset).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLqqdMsUKfUYxrrsKffKag.png" /><figcaption>Frequency plot of train and test data respectively</figcaption></figure><p>All ‘saldo’ features were found to be continuous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlxcdUq2FqGIm57wE2PC_w.png" /><figcaption>Random ‘saldo’ faeture after log transformation(excluding zero)</figcaption></figure><p>Here also (as similiar to ‘imp’ feature), we can create new datasets with log transformation applied to saldo features except for 0 values which will be kept as it is.</p><p><strong>Strategy for ‘saldo’ features:</strong></p><ol><li>We can create a new dataset with log transformed (excluding 0) saldo features.</li><li>We can also create another dataset with no transformations applied (leaving as it is).</li></ol><h4>4.4.3 ‘num’ features</h4><p>‘num’ may be short form for numerical. Exploring the value counts of all the ‘num’ features we can say that every feature with ‘num’ keyword are categorical in nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ssBOK0vhRTFmkLQB2zGedw.png" /><figcaption>Some of the features with ‘num’ keyword with their corresponding number of unique values</figcaption></figure><p>The maximum number of unique values found for a feature with ‘num’ keyword is 172(total datapoints is around 70k) and minimum was 2. We will employ a strategy for ‘num’ feature:</p><p><strong>Strategy for ‘num’ features</strong></p><ol><li>We will put a threshold on what is the maximum number of unique values that is allowed so that a feature can be defined as categorical. We will set the threshold as 10.</li><li>We can create new datasets with response encoding, one hot encoding and leaving the features as it is for ‘num’ features.(This only applies to categorical features that are defined based on the rule above)</li></ol><h4>4.4.3 ‘ind’ features</h4><p>‘ind’ feature may refer to indicator. After looking at the value counts all the features with ‘ind’ feature had only 2 unique values.</p><p><strong>Strategy for ‘ind’ features</strong></p><p>We are leaving these features as it is.</p><h3>5. Feature Engineering</h3><p>From literature review it was understood that the number of occurrences of zeros across different features for a particular datapoint is an important feature for recognizing whether a customer is unsatisfied or not. So we will create features to the preprocessed data as shown below:</p><p><strong>no_zeros: </strong>number of zero values present across different features for a datapoint</p><p><strong>no_nonzeros:</strong> number of non-zero values present across different features for a datapoint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d19f85eec700d6b91676476fa6f91ff/href">https://medium.com/media/5d19f85eec700d6b91676476fa6f91ff/href</a></iframe><p>Now we will add a feature which calculates <strong>number of zeros and non-zeros across different keyword features (‘saldo’ , ‘ind’, ‘num’, ‘imp’)</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d91af7bea24781e5dedc6509abbeb5a/href">https://medium.com/media/9d91af7bea24781e5dedc6509abbeb5a/href</a></iframe><p>Now we will take <strong>average values for all ‘saldo’ and ‘imp’ features</strong> for each unique values of all features that have between 50(exclusive) and 210(inclusive) unique values and add it as feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84da06d0d4db786b42820871b1d6b2ad/href">https://medium.com/media/84da06d0d4db786b42820871b1d6b2ad/href</a></iframe><p><strong>K-means Clustering: </strong>We will add K-means cluster values for k = 2,4,6,8,10 as features after applying standardization for this particular step. Note: The features that we obtain after this step is not standardized since we need to apply log transformation. We are applying standardization for getting K-means clustering features only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eee7a61ea2bba8364196bb2858e3cc7e/href">https://medium.com/media/eee7a61ea2bba8364196bb2858e3cc7e/href</a></iframe><p><strong>Removing highly correlated features and low correlated features with TARGET: </strong>We will remove all features that are highly correlated with one another keeping one. We will remove all features that have low correlation with “TARGET” feature. For removing high correlated features, the threshold is kept as any feature above 0.95 correlation value while for removing low correlation values with “TARGET” the threshold is any feature below 10**-3 correlation value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/286cd6d86c744e91399447a49d9716dd/href">https://medium.com/media/286cd6d86c744e91399447a49d9716dd/href</a></iframe><p><strong>Creating new datasets:</strong></p><p>Now we will create new datasets with log transformations. We will apply log transformation to features ‘var38’, all ‘saldo’ and ‘imp’ features except for zero values which will be kept as it is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b188e9533b5ae77288882738be6c777/href">https://medium.com/media/5b188e9533b5ae77288882738be6c777/href</a></iframe><p>Now we have two datasets one is log transformed and the other is normal dataset (without any log transformation). Now we will apply <strong>one hot encoding</strong> and <strong>response encoding</strong> to these and create new datasets. Here the encoding is applied to those features where the number of unique values is between 3 and 10 (both inclusive). Here is a good article on how <a href="https://medium.com/@thewingedwolf.winterfell/response-coding-for-categorical-data-7bb8916c6dc1"><strong>response encoding</strong></a> is computed. For response encoding I have used laplace smoothing to smoothen the data ( suppose a category value is there in the test data which has not been seen in train data, we do not want the probability of that unique value to go zero so we apply smoothing). The best alpha was found by manually checking the response encoded values of a randomly selected feature from a set of alphas by how varied the resultant encoded values were.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_77DdkKImiMBi0p76X1icw.png" /></figure><p>Finally 6 datasets are created which are :</p><ol><li><strong>Normal</strong></li><li><strong>Normal with One Hot Encoding</strong></li><li><strong>Normal with Response Encoding</strong></li><li><strong>Log Transformed</strong></li><li><strong>Log Transformed with Response encoding</strong></li><li><strong>Log Transformed with One Hot Encoding</strong></li></ol><p>Now we will <strong>standardize</strong> all the datasets. After standardizing we will apply <strong>principal component analysis</strong> (here n=2) and add it as features to every dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8199a3da124d4b6d267aac660d2bd3ce/href">https://medium.com/media/8199a3da124d4b6d267aac660d2bd3ce/href</a></iframe><p>Initially we had only 142 features for train and test data. Now we have created 6 datasets and the final number of features is as follows:</p><ol><li><strong>Normal: 359 features</strong></li><li><strong>Normal with One Hot Encoding: 446 features</strong></li><li><strong>Normal with Response Encoding: 374 features</strong></li><li><strong>Log Transformed: 359 features</strong></li><li><strong>Log Transformed with Response encoding: 374 features</strong></li><li><strong>Log Transformed with One Hot Encoding: 446 features</strong></li></ol><h3>6. Existing Solutions</h3><ol><li><a href="https://beta.vu.nl/nl/Images/werkstuk-elsen_tcm235-865964.pdf"><strong>Derek van den Elsen. (2017). Santander Customer Satisfaction</strong></a><strong> :</strong> For preprocessing, he removed features that had zero variance, sparse features and also duplicated columns bar one. Now after normalization he removed all first pairs of correlated features that had a high correlation value of 0.99 or higher. <strong>Feature Engineering:</strong> A new feature was created from var3 (Nationality) feature which essentially carried the information whether the client was from the most common nation or had the most common value. This is also done for var15(Age), var36 and var38 (mortgage value), And for var15 there were values of -999999 which likely means missing value. Another feature was created which tells whether the datapoint had a value of -999999. After the creation of this feature all the -999999 values in var3 were replaced with the most common value. The same was done for var36 since it had a value of 99 which was far from the other unique values which included 0,1,2 and 3. Var36 was one hot encoded since the values suggested that it was categorical. Another feature was created which calculated the number of 0s in a datapoint (dmi3kno, 2015). Also a number of 1s for a datapoint feature was also created. The author has created 3 models: <strong>Logistic Regression, Random Forest and XGBoost</strong> with 10 fold stratified cross-validation with hyperparameter tuning. The metric AUC is found to be best for XGBoost.</li><li><a href="https://github.com/kweonwooj/kaggle_santander_customer_satisfaction/tree/master/34_wpppj"><strong>kweonwooj’s re-implementation of pjpan’s 34th place solution(in R code) in Python</strong></a><strong>:</strong> In this re-implementation, the user has removed all features that have constants (only 1 unique value), removed all duplicate features and kept one. Converted all the extreme values such as 9999999999 and -99999 to -1. Removed sparse features where the condition was that if the feature had 99 percentile value to be 0 then it was declared as sparse. For these set of columns ‘num_meses_var8_ult3’, ‘num_meses_var13_largo_ult3’, ‘num_op_var40_comer_ult1’, all meses columns from this set of columns, values were changed to int type. While all the other features from the set the values were divided by 3 (these features had multiples of 3 as their unique values). The data was trained on XGBoost with 10 stratified k folds. The test value predicted was the average of all these models test predictions that were fitted on 10 stratified k folds.</li></ol><p>For my approach, I have created 6 datasets which is thoroughly explained in Feature Engineering part and will model on these 6 different datasets.</p><h3>7. My experiments with modelling</h3><p>I have 6 datasets, so what I am going to do is for each dataset I will model on <strong>Logistic Regression, Decision Trees, Random Forest, XGBoost and LightGBM</strong>. First the dataset was split randomly with stratification for ‘TARGET’ (ensures same proportion of unique ‘TARGET’ values in both train and test) with 85:15 split. After modelling on the dataset, I selected <strong>top features based on the random forest model and then created new dataset with top 250 features </strong>for each dataset. Then <strong>Random Forest, XGBoost and LightGBM models</strong> were created based on the <strong>dataset with top 250 features</strong>. The best hyper-parameters is found by using <strong>Random Search CV for Logistic Regression, Decision Trees and Random Forest.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzfiT79IyPo8e-jx1QXTlA.png" /><figcaption>Different hyper-parameters that were used for random search cv</figcaption></figure><p>Here class_weight = ‘balanced’ takes care of class imbalance. For <strong>Decision trees </strong>and<strong> Random Forest</strong>, after fitting on the model with best hyper-parameters, calibrated classifier is fitted on top of these models (to get probability values).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/762820152726e23295a8b5b35b01fe4e/href">https://medium.com/media/762820152726e23295a8b5b35b01fe4e/href</a></iframe><p>Here model is either <strong>Decision Tree Classifier</strong> or <strong>Random Forest Classifier</strong>.</p><p>For <strong>XGBoost</strong> and <strong>LightGBM, </strong>I manually changed each parameters and found the best one based on the below article. Using RandomSearchCV for these two models consumed a lot of time.</p><p><a href="https://towardsdatascience.com/fine-tuning-xgboost-in-python-like-a-boss-b4543ed8b1e">Fine-tuning XGBoost in Python like a boss</a></p><p>Below is the code for <strong>XGBoost</strong>, similar is done for <strong>LightGBM</strong> (except for objective where in <strong>LightGBM</strong> it becomes ‘binary’).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48af8cccbbfab8a331b4bffe6b657c5d/href">https://medium.com/media/48af8cccbbfab8a331b4bffe6b657c5d/href</a></iframe><p>Combined AUC plots for different datasets are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neP5joZ_0PhxuO4eaBTIOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GqeIPUjzPOxqxTfc1jOyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7BxAfUuR9Y6ILopcjTHPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqkgAwY5Mdrdww8WFP_g9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cpy_P4MndwONtW5YG5mmqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYNyXyC_ZhJcJFpx94gQxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCVbwyiET5i-1eEq2eyJmg.png" /><figcaption>AUC scores(sorted) for <strong>Log</strong> Datasets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7x94oqSkHwg_fHRLrC95SQ.png" /><figcaption>AUC scores(sorted) for <strong>Normal</strong> Datasets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*OG3dCbiN9pJhjsMCoByY9g.png" /><figcaption>Best models from each dataset based on validation AUC</figcaption></figure><p>We then select the best model from each dataset based on validation AUC for <strong>ensembling</strong> and <strong>stacking</strong>. We do not take the best models out of all models because for stacking and ensembling larger the difference between the models (this ensures that we take models from different datasets otherwise models trained on same dataset will appear), the better will be the performance of the final ensemble/stacking classifier(each model will be an expert on different topics ie for eg: if we built a dog classifier model we can built a classifier such that one model will detect tail, another model will detect face etc, so combining these models will give a better performance,this is what I mean by different models). So larger the difference between the datasets, larger the difference between the models.</p><p>The best models obtained are then trained on the entire train dataset provided(we split the data before) and then are used to predict the test “TARGET” probability values. The 6 “TARGET” obtained is then used as features for creating a new dataframe. A classifier is trained on top of this dataframe (stacking). Here the classifier used is <strong>Logistic Regression </strong>(hyperparameters found through <strong>RandomSearch CV</strong>) and the test probability values of “TARGET” is submitted in Kaggle. The 6 test probability values obtained from the 6 best models are also submitted and their public AUC scores are recorded. Then based on the public AUC score obtained best 2 models (here it was ‘log re(top 250) xgb’ and ’normal re(top 250)) are selected and then simple average ensembling is done on the probability values. The values obtained are then submitted on Kaggle and the public AUC score is recorded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e6fdb57400854a0d694a9cbddc81464/href">https://medium.com/media/3e6fdb57400854a0d694a9cbddc81464/href</a></iframe><h3>8. Summary, results and conclusions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Df_FgiAIz5jxyJD5p5C8tA.png" /><figcaption>Models with their kaggle public AUC score</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*N9tsfdVejyOqNF3tWE_fvw.png" /></figure><p>We can see from the result dataframe above that XGB model fitted on Log transformed Response Encoded (top 250 features) dataset and XGB model fitted on Normal response encoded (top 250 features) performed very well. The simple average ensembling of these 2 models were able to achieve a kaggle public AUC score of 0.82746 which was just around 2% below the top score in public leaderboard (0.84532). The xgb model trained on Log transformed (all features) performed poorly as it had the worst public score. Response encoding the categorical features improved the models a lot since models trained on other dataset models did not produce great results compared to models trained on the response encoded datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BYWiDJCklRqoAFtuLZHY9w.png" /><figcaption>log response encoding (top 250 features) xgboost model (top 20 features)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*A6YUGGbKUX59WxWM8kf6ag.png" /><figcaption>normal response encoding (top 250 features) xgboost model (top 20 features)</figcaption></figure><p>And also from the feature importance plot of the two models of the ensemble used, we can see that in both the models, the common feature which had highest importance was ‘var15’(represents ‘age’ inferred from literature review) which implies that age is an important factor that determines whether a customer is satisfied or not.</p><h3>9. Future work</h3><ol><li>We can use <strong>Bayesian optimization</strong> to find the best hyper-parameters for each of the model.</li><li>We can also try implementing <strong>deep learning models</strong> to the problem.</li></ol><h3>10. Link to my profile — Github code and Linkedin</h3><p>You can find the complete code for this case study on this <a href="https://github.com/ashishthomaschempolil/Santander-Customer-Satisfaction"><strong>github link</strong></a>. You can connect me on <a href="https://www.linkedin.com/in/ashishthomas7/"><strong>Linkedin</strong></a> or at <strong>ashishthomas7@gmail.com</strong>.</p><h3>11. References</h3><ol><li><a href="https://www.appliedaicourse.com/course/11/Applied-Machine-learning-course">https://www.appliedaicourse.com/course/11/Applied-Machine-learning-course</a></li><li><a href="https://beta.vu.nl/nl/Images/werkstuk-elsen_tcm235-865964.pdf">Derek van den Elsen, Santander Customer Satisfaction(2017)</a></li><li><a href="https://github.com/kweonwooj/kaggle_santander_customer_satisfaction/tree/master/34_wpppj">kweonwooj’s re-implementation of pjpan’s 34th place solution(in R code) in Python</a></li><li><a href="https://towardsdatascience.com/fine-tuning-xgboost-in-python-like-a-boss-b4543ed8b1e">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Ffine-tuning-xgboost-in-python-like-a-boss-b4543ed8b1e</a></li><li><a href="https://towardsdatascience.com/mercari-price-recommendation-for-online-retail-sellers-979c4d07f45c?gi=5873f2d314af">https://towardsdatascience.com/mercari-price-recommendation-for-online-retail-sellers-979c4d07f45c?gi=5873f2d314af</a></li><li><a href="https://medium.com/@thewingedwolf.winterfell/response-coding-for-categorical-data-7bb8916c6dc1">https://medium.com/@thewingedwolf.winterfell/response-coding-for-categorical-data-7bb8916c6dc1</a></li><li><a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5776d3f8b060" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/santander-customer-satisfaction-a-self-case-study-using-python-5776d3f8b060">Santander Customer Satisfaction — A Self Case Study using Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>