<?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 Bernardo Garcia del Rio on Medium]]></title>
        <description><![CDATA[Stories by Bernardo Garcia del Rio on Medium]]></description>
        <link>https://medium.com/@bernardogarciadelrio?source=rss-9b5db1c122af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IN6taIjP4YIUfRHIge5doA.jpeg</url>
            <title>Stories by Bernardo Garcia del Rio on Medium</title>
            <link>https://medium.com/@bernardogarciadelrio?source=rss-9b5db1c122af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:53:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bernardogarciadelrio/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[Learning how GPT-3 instruct models were (most likely) trained]]></title>
            <link>https://medium.com/data-science/learning-how-gpt-3-instruct-models-were-most-likely-trained-3eb61e0f4169?source=rss-9b5db1c122af------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb61e0f4169</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bernardo Garcia del Rio]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 13:44:19 GMT</pubDate>
            <atom:updated>2022-10-27T13:29:01.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSqEL9JQXPVdqoyELHzViQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@seffen99?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sven Brandsma</a> on <a href="https://unsplash.com/s/photos/word?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>[UPDATE</strong>: Open AI published a paper called <em>Aligning Language Models to Follow Instructions</em> on Jan 27, 2022 where they explained the methodology that they really employed to train InstructGPT. You can find the paper <a href="https://openai.com/blog/instruction-following/">here</a>.]</p><p>A few months ago, OpenAI released the beta version of their GPT-based instruct models. Open AI claimed that Instruct models could understand your instructions in a similar way that humans do and that they still had the same capabilities that the other GPT-3 base models.</p><p>This advancement brought the possibility of design and engineer even more innovative prompts. You can just tell the model what is your task and the outcome you want to get and, the model will try to understand your instructions and fulfill them to the best of its ability.</p><p>At <a href="https://www.flowrite.com/">Flowrite</a>, we work with GPT-3 models on a daily basis so we didn’t wait for a second and started to test these instruct models extensively.</p><p><a href="https://www.flowrite.com/">Flowrite - Supercharge your daily communication</a></p><p>We developed a solid intuition of how these instruct models work but Open AI never published a paper or an article on how instruct models are trained so this question remained unknown. Fortunately, the Google Research Team publish a <a href="https://arxiv.org/pdf/2109.01652.pdf">paper</a> on the same topic in December 2021, which shed some light on how transformer-based models are fine-tuned to understand instructions.</p><p>Let’s take a look at the most important aspects of the paper that will help us understand how to fine-tuned large language models so they are able to deal with instruct prompts.</p><h3>Finetuned models are zero-shot learners</h3><p>As you may have already figured out, this paper revolves around the ability of large language models to perform zero-shot tasks and how instruction tuning can improve the zero-shot capabilities of these models.</p><blockquote>Zero-shot learning (ZSL) is <strong>a problem setup in machine learning</strong>, where at test time, a learner observes samples from classes that were not observed during training, and needs to predict the class they belong to. — <a href="https://en.wikipedia.org/wiki/Zero-shot_learning">Wikipedia</a></blockquote><p>Language models at scale, like GPT-3, have tremendous few-shot learning capabilities but fall shorter in zero-shot learning. GPT-3 zero-shot performance is much worse than few-shot performance on several tasks (reading comprehension, QA, and NGI). In a zero-shot setting, prompts don’t have few-shot / in-context examples and models might struggle to perform well, probably because they can’t find similarities with the pre-training data.</p><p><strong>Instruction tuning</strong> is described as the task of fine-tuning a pre-trained language model (LM) to improve its ability to respond to natural language instructions. The idea is that by using supervision to teach an LM to perform tasks described via instructions, it will learn to follow instructions and do so even for unseen tasks.</p><p>The authors instruction fine-tuned a 137B parameter pre-trained language model over 60 NLP datasets expressed via natural language instruction templates. The resulting fine-tuned model was called FLAN and, as we are going to see, it was evaluated on unseen task types showing performance improvements in many tasks with respect to other language models in other machine learning settings (few-shot learning for example).</p><h4>Datasets</h4><p>For instruction fine-tuning, the Google Research team had to transform a mixture of more than 60 NLP datasets into instructional format. These datasets were publicly available in <a href="https://www.tensorflow.org/datasets?hl=es-419">TensorFlow Datasets</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*ulfmLMFc6nj8Sp5jvUAdRw.png" /><figcaption>Publicly available datasets used for instruction fine-tuning. The datasets were transformed into instructional format and aggregated in clusters by task.— Figure from <a href="https://arxiv.org/pdf/2109.01652.pdf">Finetuned models are zero-shot learners</a> by <a href="https://research.google/research-areas/natural-language-processing/">The Google Research Team</a></figcaption></figure><p>The authors aggregated the dataset in clusters by task: commonsense, natural language inference (NLI), sentiment, etc. Then for each dataset, they created 10 unique instruct prompt templates that described the task. To increase diversity in the data, up to 3 out of 10 templates instructed the model to turn the task around. e.g. Sentiment classification → generate a movie review with positive sentiment.</p><p>Finally, each of these datasets was formatted via a random selection of instruct prompt templates specific to each dataset.</p><p>In the following figure, the authors illustrate how the instruct prompts were created to build the datasets for instruction fine-tuning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*_3AlBQexVofo_O8M3DCCgQ.png" /><figcaption>Multiple instruction templates describing a natural language inference task — Figure from <a href="https://arxiv.org/pdf/2109.01652.pdf">Finetuned models are zero-shot learners</a> by <a href="https://research.google/research-areas/natural-language-processing/">The Google Research Team</a></figcaption></figure><h4>Evaluation</h4><p>The authors were interested in evaluating how FLAN performs on tasks that hadn’t been seen during instruction tuning so it was necessary to clearly define what counts as an unseen task.</p><p>They defined an unseen dataset <em>D</em> at evaluation time if no datasets from any task clusters that <em>D</em> belongs to were seen during instruction tuning. For example, let’s assume that <em>D</em> is an entailment task, then the entailment cluster was ignored for instruction tuning and only all other clusters were used.</p><p>The authors grouped the datasets into task clusters and hold out the evaluation cluster while instruct tuning on all remaining clusters. This way they made sure that FLAN was evaluated on unseen tasks.</p><h4>Classification with Options</h4><p>FLAN is a version of a decoder-only language model (like GPT) instruction-tuned on different tasks, and therefore, it returns completions to the input text.</p><p>The output space for a classification task is one of the several unique classes specific to the problem at hand. For example, if we are performing binary classification (”Yes” or “No) with a decoder-only language model, we need to keep in mind that the model is still generating text and that a large number of different ways of responding “Yes” may lower the probability mass assigned to the token “Yes”.</p><p>As the authors state, a probability mass for answers that have an undesired distribution among alternatives of expressing the same answers makes some approaches like <em>rank classification </em>(2 outputs are considered and the most probable between the 2 is the prediction)<em> </em>imperfect.</p><p>In order to address this potential problem in classification tasks, the authors came up with the <strong>Options suffix</strong>. The Options suffix is a token attached to the end of a classification task along with a list of the unique output classes so the model is constrained to respond with only one of the classes.</p><h4>Training</h4><p>The model architecture was a dense left-to-right, decoder-only transformer language model of 137B parameters. This model was pre-trained on web documents, dialog data, etc. The text was tokenized into 2.49T BPE tokens with a 32k vocabulary using the <a href="https://github.com/google/sentencepiece">SentencePiece</a> library. Also, the authors included around 10% of non-English text in the pre-training dataset.</p><p>The resulting pre-trained model is referred as to Base LM so FLAN is the instruction-tuned version of Base LM.</p><p>For instruction fine-tuning, the authors built pipelines to mix all datasets and randomly sample from each of them.</p><h4>Results</h4><p>FLAN was evaluated on natural language inference, reading comprehension, closed-book QA, translation, commonsense reasoning, coreference resolution, and struct-to-text.</p><p>Below is a brief summary of the results. More details can be found in the <a href="https://arxiv.org/pdf/2109.01652.pdf">original paper</a>.</p><ul><li>Zero-shot FLAN outperforms zero-shot GPT-3 on 20 out of 25 tasks and even surpasses GPT-3’s few-shot performance on 10 tasks</li><li>Instruction tuning significantly improves Base LM on most tasks.</li></ul><p>The authors stated that overall, instruction tuning is more effective on tasks that are naturally verbalized by humans as instructions (NLI, QA, translation, struct-to-text) whereas the model is less effective on tasks that can be directly formulated as language modeling (commonsense reasoning and coreference resolution tasks that are formatted as finishing an incomplete sentence or paragraph). The intuition behind this is that, in the latter, instructions could be considered redundant, and therefore, they don’t add much information.</p><h4>Ablation study — Instructions with few-shot examples</h4><p>The authors of the paper presented a few ablation studies. One of the most interesting explored the capabilities of instruction tuning with few-shot examples available at inference time in the prompt.</p><p>They built a prompt for few-shot learning on top of the zero-shot prompts as follows:</p><p>For input <em>x</em> and output <em>y, </em>let<em> instruct(x) </em>denote the zero-shot instructions. Given <em>k</em> few-shot examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*JmO3q2-t_AVi6LHlZ0irpQ.png" /></figure><p>and a new input <em>x</em>, the instruction format for the few-shot prompt is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*uFfdQQ_Abq6pRDP17ELumw.png" /></figure><p>where instructions are filled with the input and concatenated with the output with a delimiter token in between.</p><p>The maximum number of examples provided in the prompt was limited to 16 and these were randomly drawn from the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7UmtKk1SDQZ8CgEEkXQPA.png" /><figcaption>Zero-shot FLAN vs. Few-shot FLAN. Orange bars indicate standard deviation among templates, averaged at the dataset level for each cluster — Figure from <a href="https://arxiv.org/pdf/2109.01652.pdf">Finetuned models are zero-shot learners</a> by <a href="https://research.google/research-areas/natural-language-processing/">The Google Research Team</a></figcaption></figure><p>It was seen that adding few-shot examples in the prompt improves the performance of FLAN on all the tasks, compared to a zero-shot setting. These improvements are larger in complex tasks such as struct to text or QA. This actually makes sense since the output space of these tasks is larger and in-context examples help the model understand the output format better and therefore, perform better than FLAN in a zero-shot setting.</p><h3>Summary</h3><p>In this article, I tried to summarise the most important concepts in the paper <a href="https://arxiv.org/pdf/2109.01652.pdf">Finetuned models are zero-shot learners</a> by the <a href="https://research.google/research-areas/natural-language-processing/">Google Research Team</a>.</p><p>If you had heard of GPT-3 instruct models but didn’t know how these were trained, I hope this summary along with the paper gives you a good intuition behind instruction tuning and its benefits.</p><p>As Open AI hasn’t published a paper on instruct models, we can’t affirm with total confidence that GPT-3 instruct models were trained following the exact same procedure that was presented here, but it’s very likely that they employed very similar techniques.</p><p><a href="https://www.linkedin.com/in/bernardo-garc%C3%ADa-del-r%C3%ADo-b4a98873/"><strong>If you want to connect with me on LinkedIn, just send me a note! :)</strong></a></p><h3>References</h3><ol><li>Finetuned Language Models Are Zero-Shot Learners — <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Wei%2C+J">Jason Wei</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Bosma%2C+M">Maarten Bosma</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Zhao%2C+V+Y">Vincent Y. Zhao</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Guu%2C+K">Kelvin Guu</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Yu%2C+A+W">Adams Wei Yu</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Lester%2C+B">Brian Lester</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Du%2C+N">Nan Du</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Dai%2C+A+M">Andrew M. Dai</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Le%2C+Q+V">Quoc V. Le</a></li><li>Open AI API Documentation — <a href="https://beta.openai.com/docs/engines/instruct-series-beta">https://beta.openai.com/docs/engines/instruct-series-beta</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb61e0f4169" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learning-how-gpt-3-instruct-models-were-most-likely-trained-3eb61e0f4169">Learning how GPT-3 instruct models were (most likely) trained</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[ID3 Decision Tree Classifier from scratch in Python]]></title>
            <link>https://medium.com/data-science/id3-decision-tree-classifier-from-scratch-in-python-b38ef145fd90?source=rss-9b5db1c122af------2</link>
            <guid isPermaLink="false">https://medium.com/p/b38ef145fd90</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[id3-algorithm]]></category>
            <category><![CDATA[decision-tree-classifier]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Bernardo Garcia del Rio]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 14:39:44 GMT</pubDate>
            <atom:updated>2020-12-13T14:39:44.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>Coding the ID3 algorithm to build a Decision Tree Classifier from scratch.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWmJupQPgE2Ob8oaQwgZIA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fabulu75?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fabrice Villard</a> on <a href="https://unsplash.com/s/photos/tree?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In my last article, I showed how you could have some fun<strong> growing a Random Forest using Sklearn’s DecisionTreeClassifier</strong>. You can check it out below:</p><p><a href="https://bernardogarciadelrio.medium.com/growing-a-random-forest-using-sklearns-decisiontreeclassifier-24e048e8bd84">Growing a Random Forest using Sklearn’s DecisionTreeClassifier</a></p><p>If you are new to Machine Learning (ML) or are in the process of becoming a Data Scientist or ML practitioner like me, you will probably get something out of it. In my case, preparing the material for the article helped me gain a good understanding of how Random Forests and Decision Trees work under the hood without getting into complex code.</p><p>In that article, I mentioned that there are many algorithms that can be used to build a Decision Tree. One of them is <strong>ID3 (Iterative Dichotomiser 3)</strong> and we are going to see how to code it from scratch using ONLY Python to build a Decision Tree Classifier.</p><p>All the code can be found in a public repository that I have attached below:</p><p><a href="https://github.com/bergr7/ID3_From_Scratch">bergr7/ID3_From_Scratch</a></p><h3>Modelling the nodes of the tree</h3><p>A Decision Tree is formed by nodes: root node, internal nodes and leaf nodes. We can create a Python class that will contain all the information of all the nodes of the Decision Tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f8d6a55f9c0a385bf8c1f8d7f6b3df/href">https://medium.com/media/a7f8d6a55f9c0a385bf8c1f8d7f6b3df/href</a></iframe><p>The class Node will contain the following information:</p><ul><li><em>value</em>: Feature to make the split and branches.</li><li><em>next</em>: Next node</li><li><em>childs</em>: Branches coming off the decision nodes</li></ul><h3>Decision Tree Classifier Class</h3><p>We create now our main class called DecisionTreeClassifier and use the __init__ constructor to initialise the attributes of the class and some important variables that are going to be needed.</p><p>Note that I have provided many annotations in the code snippets that help understand the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0631965e62961e873a671474126bed92/href">https://medium.com/media/0631965e62961e873a671474126bed92/href</a></iframe><p>In order to calculate the entropy note we are using the private function _get_entropy( ). The code for this function is provided below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93a5568a2f3ef57530b7ed14980f87bc/href">https://medium.com/media/93a5568a2f3ef57530b7ed14980f87bc/href</a></iframe><p>We pass the instances id’s or indexes to this function. For doing this, we need to generate an unique number for each instance. <a href="https://www.w3schools.com/python/python_lists_comprehension.asp">Python’s lists comprehensions</a> come in very handy for this task as you can see.</p><p>We are going to code an ID3 algorithm that uses the <strong>information gain</strong> to find the feature that maximises it and make a split based on that feature. The information gain is based on entropy.</p><p>As this article is about coding the ID3 algorithm, I am not going to go into the details but <strong>entropy</strong> is a measure of uncertainty about a random variable. If we minimise the entropy, then we increase the certainty about the variable. In other words, if the random variable can take only one value the entropy reaches its minimum whereas if all the values are equiprobable the entropy is maximum.</p><blockquote>The algorithm will try to minimise the entropy or, equivalently, maximising the information gain.</blockquote><p>We can compute the entropy with the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*voRgqFZhfko4ZfG3odSK_Q.png" /><figcaption>Entropy formula (Caption by Author)</figcaption></figure><p>where <em>pi</em> is the proportion of each category i=1,…,N.</p><p>We said that we would compute the information gain to choose the feature that maximises it and then make the split based on that feature. The information gain is a concept based on entropy. It is defined as the total entropy minus the entropy if we chose a particular feature j.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*_uzMwgApeQPXEylcwOc3WQ.png" /><figcaption>Information gain (Caption by Author)</figcaption></figure><p>So we create another private function that computes the information gain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4942963845ad6bb0d13a3268daa94c31/href">https://medium.com/media/4942963845ad6bb0d13a3268daa94c31/href</a></iframe><p>_get_information_gain( ) takes the instances ids and the feature id of the selected featured to be evaluated. Then it calculates the total entropy, the entropy if we selected the feature specified in feature_id and finally the information gain.</p><p>This ID3 algorithm chooses the feature that maximise the information gain at each split. That is if the amount information in the feature is large, the entropy will be small, and therefore the second term of the information gain formula will be also small, increasing the information gain.</p><p>_get_information_gain( ) only calculates the information gain for a given set and feature but, at each split, we need to figure out which is the <strong>feature</strong> that maximises the information gain. We need to create another function to find the feature that maximises the information gain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd42441176100e3fd8c7cb45146672c4/href">https://medium.com/media/dd42441176100e3fd8c7cb45146672c4/href</a></iframe><p>Ok..so we have a private function (<strong>_get_feature_max_information_gain( )</strong>) that find the feature that maximises the information gain, that uses another private function (<strong>_get_information_gain( )</strong>) that calculates the information gain, that uses another private function (<strong>_get_entropy()</strong>) that computes the entropy. We are all set! We can start coding the ID3 algorithm that will create our ID3 Decision Tree for classification problems.</p><p>We create a function that initialises the algorithm and then uses a private function to call the algorithm recursively to build our tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2963a2d8f0d40b293743c07b64ed5677/href">https://medium.com/media/2963a2d8f0d40b293743c07b64ed5677/href</a></iframe><p>Note how we call <strong>_id3_recv( )</strong> function in <em>self.node</em>. This function returns an instance of the class Node with information of all the nodes (decisions) in the Decision Tree.</p><p>_id3_recv_( ) is the trickiest function to code so let’s spend some time understanding what is does.</p><h3>Let’s generate some data</h3><p>I have generated a small toy dataset so we can work on a small example and actually visualise the resulting tree. This will help us understand the algorithm as well.</p><p>Let’s imagine that we love surfing waves and would like to have a model to predict if there will be good waves in our favourite spot.</p><p>Our features are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*pHjAdaaTzMvk0t6Uw_HzRw.png" /><figcaption>Features (Caption by Author)</figcaption></figure><p>And our target is simply a binary categorial variable that tells us if there were/will be good waves based on the information provided in our features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*HbaZyDXx5_tBR5NxbjO3ig.png" /><figcaption>Target (Caption by Author)</figcaption></figure><p>Let’s generate some synthetic data using random sampling:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31eb5ad92a31df0ee8a7d161c8aa5d85/href">https://medium.com/media/31eb5ad92a31df0ee8a7d161c8aa5d85/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*BpQX-vLGBoNLBBz-A8hi3A.png" /><figcaption>First 5 rows of our toy dataset (Caption by Author)</figcaption></figure><h3>_id3_recv( ) function</h3><p>Now that we have some data to work with it will be easier to understand _id3_recv ( ) function. Below is the code with some annotations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9d4de24766fdf8f698091fde1c74787/href">https://medium.com/media/d9d4de24766fdf8f698091fde1c74787/href</a></iframe><p>The function takes two lists containing instances ids and feature ids and an instance of the class Node. Firstly, it checks if the node attribute is <em>None</em> and if it is, it initialises an instance of the class Node.</p><p>Then, at each split the algorithm checks if some of the following conditions are met:</p><ul><li><strong>Are all the instances of the same category?</strong> If so, it assigns the category to the node value and returns the variable node. The following chunk of code does this task in the function:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48c12292c6a8c20cbce8f88f2ab7ed58/href">https://medium.com/media/48c12292c6a8c20cbce8f88f2ab7ed58/href</a></iframe><ul><li><strong>Are there more features to compute the information gain?</strong> If there are not, it assigns the most probably category to the node value (it computes the mode) and returns the variable node. Code doing this is below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d770e76223aec773072042cac6553f/href">https://medium.com/media/13d770e76223aec773072042cac6553f/href</a></iframe><p>If none of the above conditions are met, it chooses the feature that maximises the information gain and stores it in the node value. In this case, the node value is the <strong>feature</strong> with which it is making the split.</p><p>The ID3 algorithm creates a branch for each value of the selected feature and finds the instances in the training set that takes that branch. Note each branch is represented with a new instance of the class node that also contains the the next node.</p><p>For the next node, it computes the information gain for the remaining features and instances and chooses the one that maximises it to make another split until all the instances have the same class or there not more features to compute, returning the most probable category in this case. All of this is done in the last part of the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7877ad2b219c3fb52d8188a6f4c6208c/href">https://medium.com/media/7877ad2b219c3fb52d8188a6f4c6208c/href</a></iframe><h3>Resulting Decision Tree</h3><p>And here we have the Decision Tree Classifier that the ID3 algorithm has built using our synthetic data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*--Eqg6l0NhE3z7ZnPzgBDg.png" /><figcaption>Resulting Decision Tree (Caption by Author)</figcaption></figure><p>It seems that our “synthetic” beach only works well when the wind blows from the South. If there is a large swell, it is likely that there will be good waves regardless of the tide but if the swell is medium, we will usually find better surfing conditions during low tide.</p><p><em>I would like to give credit to the Professors of the MSc in Machine Learning, Deep Learning and AI by Big Data International Campus for providing a version of the source code, that inspired me to write this article.</em></p><h3>References</h3><ol><li><em>Text notes of MSc in Machine Learning, Deep Learning and AI by Big Data<br>International Campus and UCAM</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b38ef145fd90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/id3-decision-tree-classifier-from-scratch-in-python-b38ef145fd90">ID3 Decision Tree Classifier from scratch in 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>
        <item>
            <title><![CDATA[Growing a Random Forest using Sklearn’s DecisionTreeClassifier]]></title>
            <link>https://medium.com/data-science/growing-a-random-forest-using-sklearns-decisiontreeclassifier-24e048e8bd84?source=rss-9b5db1c122af------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e048e8bd84</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[decision-tree-classifier]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest-classifiers]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Bernardo Garcia del Rio]]></dc:creator>
            <pubDate>Sat, 05 Dec 2020 10:08:15 GMT</pubDate>
            <atom:updated>2020-12-11T17:26:45.478Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Decision Trees and Random Forests with a hands-on example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsxwS9qFOqn7n3Rvl8FxlQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@skamenar?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Steven Kamenar</a> on <a href="https://unsplash.com/s/photos/forest?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Random Forest</strong> is one of the most widely used machine learning algorithm based on ensemble learning methods.</p><p>The principal ensemble learning methods are<strong> boosting</strong> and <strong>bagging</strong>. Random Forest is a bagging algorithm.</p><p>In simple words, bagging algorithms create different smaller copies of the training set or subsets, train a model on each of these subsets and then combine the results of all the models to make predictions.</p><p>These models trained on small subsets are called <strong>“weak learners”</strong> because are usually models that cannot fit complex data. The “weak models” that Random Forest uses are <strong>Decision Trees</strong>.</p><p>Let’s understand the basics of Decision Trees with an example using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">Sklearn’s DecisionTreeClassifier</a> before jumping into how to grow a forest.</p><h3>Decision Trees</h3><p>Decision Tree is a <strong>hierarchical graph representation</strong> of a dataset that can be used to make decisions.</p><p>It is a <strong>non-parametric method</strong> as it does not assume any parameter or pre-defined shape of the tree that can be used either for classification and regression.</p><p>Let’s generate some synthetic data and build a Decision Tree to understand how it works.</p><p>For this example, I have generated 10,000 data points and added Gaussian noise with a standard deviation of 0.4. The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html?highlight=make_moons#sklearn.datasets.make_moons">Sklearn’s make_moons</a> dataset is a toy dataset that comes handy to visualise classification algorithms. I have also imported all the libraries and classes that I will use later in this post.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/510ba9d736342293003f4318b7c6b3d3/href">https://medium.com/media/510ba9d736342293003f4318b7c6b3d3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*puOJpLpdBT87nBCFrOlBYw.png" /><figcaption>2d binary classification synthetic data generated by Sklearn’s make_moons class</figcaption></figure><p>By plotting the data, we can see how make_moons class generates two interleaving half circles. This is 2D binary data so our classes are {0, 1}. Typical binary classification problems are fraud detection or spam detection.</p><p>The corresponding Decision Tree for the training set is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMKMqo0ydl8ERZgsyq0cCQ.png" /><figcaption>Decision Tree trained on 8000 instances of the generated dataset, plotted using Graphviz library</figcaption></figure><p>The first node, the one at the top, is called <strong>Root Node</strong>. In this node we give the algorithm all the training data available, in our example 8000 instances because we have put apart 2000 instances of the dataset to evaluate performance on data the model has never seen before. This is the most simple technique of <a href="https://scikit-learn.org/stable/modules/cross_validation.html">cross-validation</a>.</p><blockquote><strong>Cross-validation </strong>is any of various similar <a href="https://en.wikipedia.org/wiki/Model_validation">model validation</a> techniques for assessing how the results of a <a href="https://en.wikipedia.org/wiki/Statistics">statistical</a> analysis will <a href="https://en.wikipedia.org/wiki/Generalization_error">generalize</a> to an independent data set.</blockquote><p>The algorithm finds the feature-threshold pair that maximizes the <strong>gain information</strong> and makes a split by evaluating if the value of the selected feature is less than / equal to or greater than the threshold. The threshold is the selected value in the feature that maximises the information gain.</p><p><strong>So what do we mean by information gain? </strong>First, we need to define <strong>entropy</strong>. Entropy is a measure of the uncertainty about a random variable. If all values of a random variable have the same probability, then we have the maximum entropy. If the random variable can take only one value, then the entropy takes its minimum value.</p><p>For example, in a <strong>pure node</strong>, which is leaf node where all the instances were predicted the same class, the entropy would be 0.</p><p>Information gain is a measure based on <strong>entropy. </strong>It measures the reduction in entropy when we split a subset according to the selected feature-threshold pair. When the algorithm chooses a feature-threshold pair that maximises the information gain, it is minimising the entropy.</p><p>So going back to our Decision Tree, the selected feature is X1 and the threshold is 0.29. After the first split, we have two new nodes. 4252 instances have taken the left <strong>branch </strong>(True)<strong> </strong>and 3748 instances have taken the right branch (False).</p><p>These two new nodes are leaf nodes until another split is made<strong>.</strong> <strong>Leaf nodes</strong> are nodes of a Decision Tree that do not have additional nodes coming off them so a decision about the class of the instances is made.</p><p>In our example, if we look at the (blue) node that received the 4252 instances that took the left branch, the algorithm has found another feature-threshold pair that maximises the information gain and made another split. The selected feature is X0 and the threshold -0.466.</p><p>The algorithm does the exercise of finding feature-threshold pairs that maximises information gain recursively until a certain <strong>tree depth</strong> is reached or the <strong>improvement in information gain</strong> is less than a given parameter (we will see in hyper-parameters fine-tuning).</p><blockquote>The maximum depth of the tree can be limited using the hyperparameter <strong>max_depth</strong> of Sklearn’s DecisionTreeClassifier. We can also set the maximum leaf nodes (<strong>max_leaf_nodes</strong>), the minimum number of samples required to split an internal node (<strong>min_samples_split</strong>), etc.</blockquote><p>It could be possible to train a Decision Tree until there are not more feature-threshold pairs that could be evaluated. However, it is likely that we would end up <strong>overfitting model</strong>.</p><p>After fine-tuning the hyperparameters using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html?highlight=gridsearch#sklearn.model_selection.GridSearchCV">Sklearn’s GridSearchCV</a>, our tree has 18 leaves or leaf nodes because maximum number of leaf nodes was limited to this value. Fine-tuning the hyperparameters of a Decision Tree is like setting out constraints to the tree growth.</p><p>If we look at the leaf at the bottom right corner, the class predicted for the 324 instances in this node is 0. The feature X0 takes a value greater than 0.511.</p><p>We have been ignoring the term “Gini” that appears in each node of the tree. “Gini” stands for <strong>Gini impurity</strong> and it is a measure of the goodness of the split in each decision node.</p><blockquote><strong>Decision nodes </strong>are nodes that are split by using If/Else conditions. They are also known as <strong>internal nodes or split nodes</strong>.</blockquote><p>By default, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">Sklearn’s DecisionTreeClassifier</a> uses the Gini impurity as a function to measure the quality of a split. Gini Impurity is the frequency with which a randomly chosen element in the dataset is incorrectly classified if it were randomly labeled according to the class distribution in the dataset.</p><p>We can think Gini impurity as the equivalent of the information gain. I have used the information gain in the explanation as it seems more intuitive to me. Indeed, we can set the criterion to <strong><em>“entropy”</em></strong><em> </em>and<em> </em><a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">Sklearn’s DecisionTreeClassifier</a> will compute the information gain to measure the goodness of the split.</p><p>In practice, there is not real difference between using the Gini impurity or the information gain for 99% of the problems.</p><p>Let’s go through the code to build a Decision Tree using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">Sklearn’s DecisionTreeClassifier</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7efad6f9c60afb220016dced89e8a0/href">https://medium.com/media/ca7efad6f9c60afb220016dced89e8a0/href</a></iframe><p>First of all, we split the dataset into training and test set using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html?highlight=train%20test#sklearn.model_selection.train_test_split">Sklearn’s train_test_split</a>.</p><p>Then we need to choose some hyperparameters to run GridSearchCV. This is a bit of an iterative process and experience is also an important factor here.</p><p>I chose some of them and run GridSearchCV several times, adjusting the parameters each time until I found an optimal combination. For example, if I started with max_leaf_nodes: [20 , 30, 40] and max_leaf_nodes was 20 in the best estimator, I would go back, set max_leaf_nodes = [15, 20, 25] and run GridSearchCV again.</p><p>We have now an optimal Decision Tree so let’s test it on data that the model has never seen before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd935f9d6a426ea21fea7adcd6e2407/href">https://medium.com/media/3dd935f9d6a426ea21fea7adcd6e2407/href</a></iframe><p>The<strong> accuracy </strong>on the test set is <strong>86.10%</strong>, slightly higher that the accuracy on the training set (85.97%). <strong>This is uncommon</strong>. Most of the time you will find that the performance on the training set is higher than on the test set. This finding might be just due to coincidence and it is probably due to the train-test split. If we repeated the process many times, we would usually see training accuracy higher than testing accuracy in the majority of the tests.</p><p>Finally, it is worth mentioning that there are many algorithms that can build a Decision Tree, some more powerful than others. Sklearn uses an optimised version of the <strong>CART (Classification and Regression Trees) algorithm</strong>. You can learn more about CART <a href="https://en.wikipedia.org/wiki/Predictive_analytics#Classification_and_regression_trees_(CART)">here</a>.</p><p>Ok so now that we have grasped the essence of Decision Tree let’s see how Random Forest leverages this hierarchical graph representation of a dataset to make better predictions.</p><h3>Random Forests</h3><p>As mentioned at the beginning of the post, Random Forest uses ensemble learning methods to learn from data.</p><p>It is a bagging algorithm that combines the predictions of many “weak models” trained on small subsets to make the final predictions.</p><p>In simple words, the basic idea behind a Random Forest is that if a Decision Tree is good, many Decision Trees together should be better.</p><p>A key factor is that “weak learners” trained on small subsets, Decision Trees in the case of Random Forests, <strong>must be slightly different and slightly better than a random guessing.</strong></p><p>We said that each “weak learner” is trained on a small subset of data. To create these subsets we use <strong>random sampling with replacement</strong>. Note we are introducing the first layer of randomness here.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.ShuffleSplit.html?highlight=shuffle%20split#sklearn.model_selection.ShuffleSplit">Sklearn’s ShuffleSplit</a> comes handy for this task. For our Random Forest, we are going to generate 1,000 subsets containing 100 instances of the training set. The code to carry out this task is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4803fca2b68aef92f0615c0840593f03/href">https://medium.com/media/4803fca2b68aef92f0615c0840593f03/href</a></iframe><p>Now, we train 1,000 Decision Trees, one for each subsets. We are growing our Forest. As these trees are trained on very small sets, we would expect them to be quite shallow and not too accurate.</p><p>Note we are going to use best estimator obtained for the Decision Tree above so we can compare performance.</p><p>We can check this by computing the average accuracy as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/155c6a113e622c80ab6d7ac908ee896d/href">https://medium.com/media/155c6a113e622c80ab6d7ac908ee896d/href</a></iframe><p>The average accuracy of the “weak Decision Trees” is 81.39%, lower than 86.10% that was the accuracy of the Decision Tree trained on the 8000 samples.</p><p>Let’s grow our Forest and evaluate its performance.</p><p>The <strong>process</strong> is the following:</p><ul><li>Loop through all the instances in the test set</li><li>Generate 1,000 predictions for each instance, one for each Decision Tree trained on a subset</li><li>Run and majority-vote to determine the class of the instance</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2724782cbb34c3daf54809ef9fa6b488/href">https://medium.com/media/2724782cbb34c3daf54809ef9fa6b488/href</a></iframe><p><strong>The testing accuracy achieved by the Random Forest is 86.85%, </strong>slightly higher than 86.10% of the Decision Tree.</p><p>Ok we have slightly improved our predictions but not by much so..does that mean that Random Forests are not much better than a single Decision Tree?</p><p>Well the truth is that this is a simplified example. Random Forests usually add a <strong>second layer of randomness</strong> by randomly limiting the features available at each split in the learning process. This avoids correlation between trees and results in better performance.</p><p>You could train a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html?highlight=randomforestclassifier#sklearn.ensemble.RandomForestClassifier">Sklearn’s RandomForestClassifier </a>on this dataset and see if it outbeats our simple Random Forest. Please share your results!!</p><p>As final note, Random Forests implicitly address the problem of overfitting because it reduces the final variance of the model by using multiple samples of the dataset.</p><p>Hope you enjoyed this post and found it interesting. Please share your feedback for future articles.</p><p><em>I would like to thank Aurélien Géron for suggesting this exercise in his book “Hands-On Machine Learning with Scikit-Learn, Keras and Tensorflow 2nd Edition”. I cannot recommend more this book for people who wants to learn data science or need to brush up some basic concepts.</em></p><h3>References</h3><ol><li><em>“Hands-On Machine Learning with Scikit-Learn, Keras and Tensorflow 2nd Edition” — Aurélien Géron</em></li><li><em>“The Hundred-Page Machine Learning Book” — Andriy Burkov</em></li><li><em>Module 2: Text Notes. MSc in Machine Learning, Deep Learning and AI— Big Data International Campus and UCAM</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e048e8bd84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/growing-a-random-forest-using-sklearns-decisiontreeclassifier-24e048e8bd84">Growing a Random Forest using Sklearn’s DecisionTreeClassifier</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[Customer Segmentation: Bertelsmann / Arvato Capstone Project]]></title>
            <link>https://bernardogarciadelrio.medium.com/customer-segmentation-bertelsmann-arvato-capstone-project-f66360186392?source=rss-9b5db1c122af------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66360186392</guid>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[xgbclassifier]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <dc:creator><![CDATA[Bernardo Garcia del Rio]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 12:45:01 GMT</pubDate>
            <atom:updated>2020-12-11T06:23:23.928Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>This is a blog post for a technical audience summarising my work on the final capstone project of the Udacity’s Data Scientist Nanodegree.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vs_RFpJWO97IG9FIs3hITw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">William Iven</a> on <a href="https://unsplash.com/s/photos/marketing-strategy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>I have structured this blog post in 8 sections make the reader’s life easier. The first section is just a brief introduction to the project.</em></p><p><em>The second section describes the standard process model that I have utilised along this project, the well-known CRISP-DM methodology.</em></p><p><em>Sections 2 to 6 correspond to each step defined in CRISP-DM and here I explain the business problem, how I tried to understand all the data available and how I preprocessed it, the algorithms that I used and why, etc.</em></p><p><em>Section 7 talks about the experience in the Kaggle competition amongst the Udacity’s students for this project.</em></p><p><em>In the last section, I put together some personal take-aways from this project that will be definitely useful for future projects.</em></p><p><em>All the code and information can be found in the GitHub repository below:</em></p><p><a href="https://github.com/bergr7/Bertelsmann_Arvato_Project">https://github.com/bergr7/Bertelsmann_Arvato_Project</a></p><h3>1. Introduction to the project</h3><p>In this capstone project, I was asked to analyse demographics data for customers of a mail-order sales company in Germany and compare it against demographics information for the general population.</p><p>The datasets used were provided by Bertelsmann Arvato Analytics, and the project represents a real-life data science task. This data has been strictly used for this project only and will be removed from my laptop after completion of the project in accordance with Bertelsmann Arvato terms and conditions.</p><p>The project is divied in <strong>3 parts:</strong></p><p><strong>Part 1: Customer Segmentation Report</strong></p><p>In this part, I used unsupervised learning techniques to analyse features of established customers and the general population in order to create customer segments with the aim of targeting them in marketing campaigns.</p><p><strong>Part 2: Supervised Learning Model</strong></p><p>Next step was to build a supervised learning machine learning model that predicted whether or not each individual will respond to the campaign.</p><p><strong>Part 3: Kaggle Competition</strong></p><p>Finally, after spot-checking several models, choosing the most promising one and fine-tuning its hyperparemeters, I used the model to make predictions on the campaign data as part of a Kaggle Competition.</p><h3>2. CRISP-DM Methodology</h3><p>Cross-industry standard process for data mining (CRISP-DM) is the most widely-used model in data science projects. CRISP-DM allowed me to keep track of all the necessary steps in this project.</p><p>For those not familiar with this methodology, CRISP-DM sets out the following steps for an end-to-end data science project:</p><ol><li>Business Understanding</li><li>Data Understanding</li><li>Data Preparation</li><li>Modeling</li><li>Evaluation</li><li>Deployment (Not applicable to this project)</li></ol><p>Almost 100% of the times, it is necessary to iterate over different steps during the lifecycle of the project.</p><p>You can find the <strong>CRISP-DM document</strong> that I created in <a href="https://www.notion.so/">Notion</a> for this project in the GitHub repository.</p><h3>3. Business Understanding</h3><p>I identified the following business objectives for this project:</p><ul><li><strong>Customer Segmentation:</strong> Identify the parts of the population that best describe the core customer base of the company.</li><li><strong>Improve marketing campaigns efficiency:</strong> Using the different features that define customer groups (from the Customer Segmentation report), get to know individuals that are most likely to becoming into customers for the company in order to target them in the marketing campaign and then prepare a supervised ML model to predict if an individual is likely to become a customer.</li></ul><p>As important as idenfitying and understanding the business objectives of the project is to idenfity the project derivables. These project had three main derivables:</p><ul><li><strong>Customer Segmentation Report:</strong> A Jupyter Notebook with markdown notes and visualisations. Note I needed to create a couple of supportive files to explore the data and preprocess it.</li><li><strong>Supervised Learning Model:</strong> I built a supervised learning model that used demographics data to classify people into potential customers or non-potential customer.</li><li><strong>Blog post for a technical audience:</strong> You are reading it! :)</li></ul><p>Dividing the project into derivables allows you to keep track of your project progress and increases the chances of delivering the project on time.</p><h3>4. Data Understanding</h3><p>Bertelsmann Arvato Analytics provided demographics data for the general population of Germany, for customers of a mail-order company and for individuals who were targets of a marketing campaign.</p><p>Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood.</p><p>Bertelsmann Arvato Analytics also provided a top-level list of attributes and descriptions, organised by informational category and a detailed mapping of data values for each feature in alphabetical order.</p><p>My business domain knowledge was very limited so these Excel files helped me understand some of the features.</p><p>The majority of the features were categorical, with a mix of ordinal and nominal data. All these features had already been encoded with the exception of CAMEO_DEU_2015 feature, that needed to be label encoded in the data preprocessing stage.</p><p>There were also a few numerical variables in the datasets.</p><p>During the <strong>exploratory data analysis (EDA)</strong>, I found two potential issues in the data:</p><ul><li>Some features in the .csv files provided did not have a description in the Excel files. That means that I did not know the meaning of some of the features.</li><li>In the categorical features, there was a category called ‘unknown’ that had been mapped to 0, -1, ‘X’ or ‘XX’.</li></ul><p>I went through the Excel files and the .csv files provided and manually created the following new .csv file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*Cs6FSz8enxTmQUDluarBlQ.png" /><figcaption>Note only 5 rows shown.</figcaption></figure><p>There were 54 features that had not been described/included in the Excel files.</p><p>Going through all the features (+350) gave me a better understanding of the data that I had in hand. I was also able to identified a couple of variables with outliers.</p><p>For example, the feature ANZ_HAUSHALTE_AKTIV represents the number of households in the building and is numeric. The information provided in the Excel files stated that this variable is typical encoded from 1–10 but I spotted much larger values so I plotted a histogram of the variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*D15SEjwvDAJeBkYNBEoh0w.png" /><figcaption>Histogram showing ANZ_HAUSHALTE_AKTIV feature distribution.</figcaption></figure><p>As we can see in the histogram above, there are some rare values that are likely to be errors in the data (Maximum value was 595.0) and also outliers.</p><h3>5. Data Preparation</h3><p>Once I had understood the data meaning and the data types with the particularities for each feature, I started to prepared a python script with functions that preprocessed the data for clustering analysis.</p><p>The preprocessing steps were the following:</p><p><strong>Step 1: Map unknown values to NaN’s</strong></p><p>As mentioned in the previous section, there were unknown values mapped to a category so I created a function to mapped them to NaN’s. Note the feature had already some NaN’s or missing values. The function used for this is below:</p><pre>def map_unknowns(attributes, df):<br>    <em>&quot;&quot;&quot;It maps unknown values identified during data exploration to NaN&#39;s.<br>    Parameters<br>    __________<br>    </em><strong><em>:param</em></strong><em> attributes: Attributes pandas DataFrame.<br>    </em><strong><em>:param</em></strong><em> df: df: AZDIAS or CUSTOMERS Pandas DataFrame<br>    __________<br>    </em><strong><em>:return</em></strong><em>: mapped_df: AZDIAS or CUSTOMERS Pandas DataFrame with unknown values mapped to NaN&#39;s<br>    &quot;&quot;&quot;<br>    </em># create a dict with original dtypes for each column<br>    original_dtypes = dict()<br>    for col in df.columns:<br>        original_dtypes[col] = str(df[col].dtype)<br><br>    # convert all columns to object type<br>    df.astype(dtype=&#39;str&#39;)<br>    # loop through all attributes<br>    for attribute in attributes.index:<br>        # for each attribute, retrieve a list with unknown values<br>        unknowns_list = attributes[&#39;Unknown&#39;].loc[attribute].strip(&#39;][&#39;).split(&#39;, &#39;)[0].split(&#39;,&#39;)<br>        # if there are unknown values, map them to NaN&#39;s<br>        if unknowns_list != [&#39;&#39;]:<br>            if attribute in [&#39;CAMEO_DEUG_2015&#39;, &#39;CAMEO_DEU_2015&#39;, &#39;CAMEO_INTL_2015&#39;]:<br>                df.loc[df[attribute].isin([&#39;X&#39;,&#39;XX&#39;, &#39;-1&#39;]), attribute] = np.nan<br>            else:<br>                df.loc[df[attribute].isin(unknowns_list), attribute] = np.nan<br><br>    # transform columns to original dtypes<br>    df.astype(original_dtypes, errors=&#39;ignore&#39;)<br><br>    mapped_df = df<br><br>    return mapped_df</pre><p>Note all the data is converted to string to map the unknown values and then converted back to the original data types.</p><p><strong>Step 2: Clean the data</strong></p><p>I created a function to clean the datasets. This function does the following:</p><ul><li>It drops features that were not useful for analysis due to its nature, for example an ID column, or due to the amount of missing values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*KZ_uXKYyaOTur12EHGVv_w.png" /><figcaption>Distribution of missing values per column in the training set.</figcaption></figure><p>The majority of the features had less than 200000 missed values, which is about 22% of missing values per attribute.</p><p>I decided to drop features with more than 60% of missing values. Features with less than 60% of missing values were <strong>imputed with the mode or most frequent value</strong>. To do this, Scikit-Learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html">SimpleImputer</a> class came very handy.</p><ul><li>It drops rows with high proportion of missing values from the training set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*TwF4yRCZ6y5sCA2XXZpQ_w.png" /><figcaption>Distribution of missing values per row in the training set.</figcaption></figure><p>The majority of the rows have less than 100 features missed. This is about 27% of missing values per row. I decided to drop rows with more than 150 features missed only from the training set. The chunk of code that does this in the function is shown below:</p><pre># drop individuals with more than 150 missed values<br>rows_toDrop = list(azdias_df.isnull().sum(axis=1).loc[azdias_df.isnull().sum(axis=1) &gt; 150].index)<br>azdias_df = azdias_df.drop(rows_toDrop, axis=0)</pre><ul><li>It drops outliers found in ANZ_HAUSHALTE_AKTIV and ANZ_PERSONEN features.</li></ul><pre>azdias_df = azdias_df.loc[azdias_df[&#39;ANZ_HAUSHALTE_AKTIV&#39;] &lt; 10, :]<br>azdias_df = azdias_df.loc[azdias_df[&#39;ANZ_PERSONEN&#39;] &lt; 3, :]</pre><p>The criteria to drop outliers was based on the <a href="https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/box-whisker-plots/a/identifying-outliers-iqr-rule">1.5*Interquantile Range (IQR) method</a> for outlier detection and the information provided in the Excel files.</p><p><strong>Step 3: Impute missing values</strong></p><p>Once the data was cleaned, I created another function to impute the missing values.</p><p>As the majority of the data is categorical, the strategy to impute the missing value was the mode or most frequent value using Scikit-Learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html">SimpleImputer</a> class. See created function below:</p><pre>def impute_mv(df, strategy):<br>    <em>&quot;&quot;&quot;It performs imputation of missing values using skelarn SimpleImputer.<br>    Parameters<br>    __________<br>    </em><strong><em>:param</em></strong><em> df: AZDIAS or CUSTOMERS Pandas DataFrame<br>    </em><strong><em>:param</em></strong><em> strategy: string. The imputation strategy for SimpleImputer<br>    __________<br>    </em><strong><em>:return</em></strong><em>: AZDIAS or CUSTOMERS df with imputed values<br>    &quot;&quot;&quot;<br>    </em># instantiate SimpleImputer<br>    imputer = SimpleImputer(strategy=strategy)<br><br>    # impute missing values<br>    data_with_no_mv = imputer.fit_transform(df)<br><br>    # put back column names from df as fit_transform returns an array of shape (n_samples, n_features_new)<br>    imputed_df = pd.DataFrame(data_with_no_mv, columns=df.columns)<br><br>    return imputed_df</pre><p><strong>Step 4: Label Encode categorical variables</strong></p><p>During the EDA, I identified a categorical feature (CAMEO_DEU_2015) that had not been encoded.</p><p>This is a nomical categorical variable so I label encoded it. Again, Scikit-Learn came very handy here with its <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">LabelEncoder</a> class. See function below:</p><pre>def label_encode_cameo(df):<br>    <em>&quot;&quot;&quot;It performs label encoding on &#39;CAMEO_DEU_2015&#39; feature using sklearn LabelEncoder.<br>    Parameters<br>    __________<br>    </em><strong><em>:param</em></strong><em> df: AZDIAS or CUSTOMERS Pandas DataFrame<br>    __________<br>    </em><strong><em>:return</em></strong><em>: AZDIAS or CUSTOMERS Pandas DataFrame with encoded &#39;CAMEO_DEU_2015&#39;.<br>    &quot;&quot;&quot;<br>    </em># instantiate LabelEncoder<br>    lab_encoder = LabelEncoder()<br><br>    # pull out list of unique classes<br>    classes = list(df[&#39;CAMEO_DEU_2015&#39;].unique())<br><br>    # fit encoder<br>    lab_encoder.fit(classes)<br><br>    # label encode &#39;CAMEO_DEU_2015&#39;<br>    df[&#39;CAMEO_DEU_2015&#39;] = lab_encoder.transform(df[&#39;CAMEO_DEU_2015&#39;])<br><br>    encoded_df = df<br><br>    return encoded_df</pre><p><strong>Step 5: Save DataFrame as a pickle file</strong></p><p>Running the preprocessing steps of the dataset took some time due to the dimensionality of the data. For example, the dataset with the demographics data for the general population of Germany has 891221 rows and 367 columns.</p><p>For that reason, I saved the preprocessed dataframes as pickle files that would be loaded in later for Clustering Analysis.</p><p><strong>Dataset for individuals who were targets of a marketing campaign</strong></p><p>All the preprocessing steps above are applicable either to the datasets for Part 1: Customer Segmentation and Part 2: Supervised Learning model. I just needed to make a couple of minor modifications to the script that run the preprocessing steps on the dataset for individuals who were targets of a marketing campaign.</p><h3>6. Modeling and Evaluation</h3><p><strong>6.1. Customer Segmentation Report</strong></p><p>I used unsupervised learning techniques to describe the relationship between the demographics of the company’s existing customers and the general population of Germany.</p><p>There were mainly two difficulties in the clustering analysis:</p><ol><li><strong>The dimensionality of the data:</strong> There were +350 features to be considered. This makes the investigation of the clusters quite difficult. Furthermore, it might be computationally expensive running a simple clustering algorithm such as K-Means.</li><li><strong>The lack of description for some of the features:</strong> Here I could drop the 54 features without a description or include them in the analysis and try to understand the cluster hopefully with other features. I opted for the latter.</li></ol><p>Due to the large number of columns, I use <strong>Principal Component Analysis (PCA)</strong> to reduce the dimensionality of the data and eliminate noise as well.</p><p>Note that as the aim is to describe the relationship between the demographics of the company’s existing customers and the general population of Germany, the model is trained on general population data and the customers dataset is transform with this model so that I could compare the results later.</p><p>I selected the first principal components that explained the 80% of the variability of the data. To do this, I plotted a scree plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUhFvfB00k7RaX72MulnUQ.png" /><figcaption>Scree plot shown PCs (General Population dataset).</figcaption></figure><p>The first 92 PCs captured the 80% of the variability in the data so the cardinality was reduced from 293 columns to 92 columns.</p><p>Having transformed the General Population data and the Customers data, I was ready to carry out the clustering analysis. I decided to use one of the most simple but also popular algorithm, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html?highlight=means#sklearn.cluster.KMeans"><strong>K-Means clustering</strong></a>.</p><p>K-Means algorithm requires a predefined number of clusters. In order to find an optimal number of cluster, I used the Elbow method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*OYifJz9J-Rlo0n32NQTM3g.png" /><figcaption>Elbow plot: Sum of square errors (SSE) vs. number of clusters (K). General population.</figcaption></figure><p>By the look of the Elbow plot, an optimal number of cluster was 9.</p><p>I fitted K-Means on the Principal Components from the General Populations data and predicted the labels for each individual. Then, I predicted the labels for the Customers using the same model.</p><p>Thus, I could compare which clusters were over-represented in the Customers base and which ones were under-represented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*pEWa6InPoqa16pGS6xbbzQ.png" /><figcaption>Bar chart showing comparison of proportion of individuals in each cluster.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*qORpWu0cYzcaXxCDwF3PzA.png" /><figcaption>Bar chart showing Representation Ratio (Customers / General Population of Germany).</figcaption></figure><p>As we can see in the bar charts above, the over-represented clusters are clusters number 2, 6, 7 and 9 and the under-represented clusters are clusters number 1, 4, 5 and 8. Cluster number 3 is pretty much balanced.</p><p>It is sensible to believe that an individual of the general population of Germany in the over-represented clusters are more likely to become a customer and that individuals in the under-represented clusters are less so.</p><p>By targeting people in the over-represented groups, the company could improve the efficiency of the marketing campaigns.</p><p>Now I needed to investigate the clusters to know the individual characteristic of each cluster. This was a bit tricky due to the number of features and because I used a dimensionality reduction technique before running K-Means.</p><p>A <strong>principal component (PC)</strong> is a unit vector that points in the direction of highest variance of the data points projected in a new subspace, after accounting for the variance captured by the earlier PC. If I could map each feature weight to its corresponding feature and sort them by weight in order to find out which features are more important for each PC, I would be able to find the most interesting features which are the ones at the beginning and the ends of the sorted weights. The reasons are explained below:</p><ul><li>The larger the feature weight (in absoulte values), the more the PC is in the direction of the feature.</li><li>If two features have large weights of the same sign (both positive or both negative), then an increase in one feature will yield an increase in the other. They show a <strong>positive correlation</strong>.</li><li>Similarly, two features with weights of different signs will be expected to show a <strong>negative correlation</strong>.</li></ul><p>So I inverse-transformed the cluster centres using the PCA model previously trained, obtained the feature weights and plotted them for each cluster. I created the following functions:</p><pre>def get_feature_weights_cluster(pca_model, clustering_model, cluster):<br> “””It inversely transforms the cluster centers using a PCA model to find feature weights.<br> Parameters<br> — — — — — <br> pca_model: PCA model trained on general population data<br> clustering_model: KMeans model trained on PCA transformed general population<br> cluster: int. Cluster number<br> <br> Returns<br> — — — — — <br> weights_by_feature: Series. Sorted weights by feature<br> “””<br> feature_weigths = pca_model.inverse_transform(clustering_model.cluster_centers_[cluster — 1])<br> # convert to series<br> weigths_by_feature = pd.Series(feature_weigths, index=azdias_df.columns).sort_values()<br> <br> return weigths_by_feature<br></pre><pre>def plot_feature_weights(weights):<br> “””It plots a bar chart showing the weights by feature.<br> <br> Parameters<br> — — — — — <br> weights: Series. Weights by feature.<br> <br> Returns<br> — — — — — <br> None<br> “””<br> <br> # plot bar chart with all weights by feature<br> plt.figure(figsize=(15,7))<br> plt.bar([i for i in range(1, len(weights.index.tolist())+1)], weights.values.tolist(), color=’lightcoral’)<br> plt.title(“Weight by feature”)<br> plt.xlabel(“Feature #”)<br> plt.ylabel(“Feature Weight”)<br> plt.show();<br> <br> # plot bar chart with only the first 3 weights and the last 3 weights<br> plt.figure(figsize=(15,7))<br> plt.bar(weights.iloc[[0, 1, 2, -3, -2, -1]].index.tolist(), <br> weights.iloc[[0, 1, 2, -3, -2, -1]].values.tolist(), color=’lightcoral’)<br> plt.title(“Weight by feature”)<br> plt.xlabel(“Feature name”)<br> plt.ylabel(“Feature Weight”)<br> plt.show();</pre><p>As an example, the plots for over-represented cluster 6 are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*cwpVq7W8HE9vPo3L36nxTQ.png" /><figcaption>Weight by feature for Cluster 6</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*cy28oBZVlNFq3Gp5htSmdA.png" /><figcaption>Weight by feature (only first 3 and last 3 in sorted weights) for Cluster 6</figcaption></figure><p>Features KBA13_HERST_BMW_BENZ, KBA13_KW_121 and KAB13_KMH_211 show positive correlation whereas KBA13_KMH_140_210, KBA13_HERST_FORD_OPELand KBA13_KMH_180 show negative correlation.</p><p>According to the features information, KBA13_HERST_BMW_BENZ represents share of BMW &amp; Mercedes, KBA13_KW_121 represents share of cars with an engine power of more than 121KW and KAB13_KMH_211 represents share of cars with a greater max speed than 210 km/h.</p><p>In contrast, KBA13_KMH_140_210, KBA13_HERST_FORD_OPELand KBA13_KMH_180 represent less powerful and less luxurious cars.</p><p>This cluster corresponds to people that own <strong>luxurious and very powerful cars.</strong></p><p>I did the same exercise for all the over-represnted and under-represented clusters.</p><p>Due to the lack of meaning for some of the features utilised in the analysis, it is hard to describe some of the clusters. I would probably drop features without feature meaning if I had to carry out the cluster analysis again or I would come back to people with business domain knowledge if possible.</p><p>However, I have been able to identify the following <strong>groups of potential customers:</strong></p><ul><li>Individuals that own luxurious and powerful cars and, therefore, these are likely to be in a good financial position and have high incomes.</li><li>Individuals that live in good neighborhood areas and municipalities. Also there is more than one car in their household.</li><li>Relatively young individuals with great interest in environmental sustainability, that are somewhat dissapointed with their current social status and interested in low interest rates financial services.</li></ul><p>If the company were to launch a marketing campaign for the current services, it would be sensible to target these groups of people.</p><p>I have also identified some <strong>groups of the German population that are under-represented in the customers base:</strong></p><ul><li>Young people with average cars and income.</li><li>Money savers with low interest in financial services.</li><li>Young people with low-midclass cars and low income.</li></ul><p>If the company were looking to reach a larger part of the German population, it might be worth designing some type of financial service that aligns with the needs of these groups and target them with a different marketing campaign. The company would need to consider the profitability of these services though before launching them as it is probably that customers of these profile will not tend to spend a lot of money often.</p><p><strong>6.2. Supervised Learning Model</strong></p><p>I In the second part of the project, I built a <strong>supervised ML model that uses demographics information from each individual</strong> and decides whether or not it will be worth it to include a person in the marketing campaign.</p><p>I had train and test sets avaiable for individuals who were targets of a marketing campaign. The test set would be used to make predictions and submit the to the Kaggle Competition (See section 7).</p><p>I randomly split the train set into train and validation sets using Scikit-Learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html?highlight=train_test_split#sklearn.model_selection.train_test_split">train_test_split class</a>.</p><p>The dataset set was <strong>highly imbalance</strong> with a 1:68 ratio as the majority of the individuals who received the promotion did not response to it. This is a common issue in classification problems.</p><p>There are several ways of handling imbalance datasets. <strong>Oversampling the minority class using systhetic samples combined with undersampling of the majority class has been proved an effective way.</strong></p><p><a href="https://imbalanced-learn.readthedocs.io/en/stable/index.html"><strong>Imbalanced-learn</strong></a> library is very useful for this type of problems. It provides similar functionality to Scikit-Learn’s but specifically for problems with imbalance datasets.</p><p>In this case, I used <strong>Synthetic Minority Oversampling Technique (SMOTE) </strong>to oversmaple the minority class by 40% and randomly undersampled the majority class by 60%. How I got to this proportions is a bit trial and error.</p><p>I started with defining a pipeline and spot-checking some algorithms: RandomForestClassifier, BalancedRandomForestClassifier, XGBClassifier and ADABoostClassifier with BalancedRandomForestClassifier.</p><p>In this pipeline for spot-checking algorithms, I set the SMOTE proportion to 10% and the undersampling proportion to 50%.</p><p>Scikit-Learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RepeatedStratifiedKFold.html?highlight=repeated#sklearn.model_selection.RepeatedStratifiedKFold">RepeatedStratifiedKFold</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html?highlight=cross_val_score#sklearn.model_selection.cross_val_score">cross_val_score</a> classes are very useful to quickly spot-check algorithms using the whole training set. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RepeatedStratifiedKFold.html?highlight=repeated#sklearn.model_selection.RepeatedStratifiedKFold">RepeatedStratifiedKFold</a> was used as opposed to <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RepeatedKFold.html?highlight=repeated#sklearn.model_selection.RepeatedKFold">RepeatedKFold</a> due to the imbalance in the dataset.</p><p>The most promising algorithm was XGBClassifier:</p><pre># define pipeline steps<br>scaler = StandardScaler()<br>over = SMOTE(sampling_strategy=0.1) # oversampling minority class by 10%<br>under = RandomUnderSampler(sampling_strategy=0.5) # undersample majority class by 50%<br>clf = XGBClassifier(random_state=42)</pre><pre>steps = [<br> (‘scaler’, scaler),<br> (‘over’, over),<br> (‘under’, under),<br> (‘clf’, clf)<br>]</pre><pre>pipeline = Pipeline(steps=steps)</pre><pre># evaluate pipeline<br>cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=5, random_state=42)<br>scores = cross_val_score(pipeline, X, y, scoring=’roc_auc’, cv=cv, n_jobs=-1)<br>print(‘Mean roc auc:’, scores.mean())</pre><pre>Mean roc auc: 0.7190005023445788</pre><p>Note that the evaluation metric was the <a href="https://developers.google.com/machine-learning/crash-course/classification/roc-and-auc">Area Under the ROC Curve (AUC)</a> as this would be the metric used in the Kaggle competition.</p><p>I selected the XGBClassifier model and run GridSearchCV over the following parameters:</p><pre># define parameters for GridSearchCV<br>parameters = {<br> ‘over__sampling_strategy’: [0.2, 0.4, 0.7],<br> ‘under__sampling_strategy’: [0.4, 0.6, 0.8],<br> ‘clf__n_estimators’: [50, 100, 150, 300],<br> ‘clf__max_depth’: [50, 150, 300],<br> ‘clf__learning_rate’: [0.001, 0.01, 0.1],<br> ‘clf__booster’: (‘gbtree’, ‘gblinear’, ‘dart’), <br>}</pre><p>This was particularly computationally demanding for my laptop and took +4 hours to run. These were the best parameters:</p><pre>{&#39;clf__booster&#39;: &#39;gbtree&#39;,<br> &#39;clf__learning_rate&#39;: 0.1,<br> &#39;clf__max_depth&#39;: 150,<br> &#39;clf__n_estimators&#39;: 100,<br> &#39;over__sampling_strategy&#39;: 0.4,<br> &#39;under__sampling_strategy&#39;: 0.4}</pre><p>I could have spent more time on fine-tuning the hyperparameters but I decided to stick to these ones and extend the lifespan of my macbook!</p><p>With this parameters, I trained the model on the training set and made predictions for the validation set.</p><pre># define XGBClassifier pipeline and tweak sampling parameters manually<br>scaler = StandardScaler()<br>over = SMOTE(sampling_strategy=0.4) # oversampling minority class by 40%<br>under = RandomUnderSampler(sampling_strategy=0.6) # undersample majority class by 60%<br>clf = XGBClassifier(booster=’gbtree’, learning_rate=0.1, n_estimators=100, random_state=42)</pre><pre>steps = [<br> (‘scaler’, scaler),<br> (‘over’, over),<br> (‘under’, under),<br> (‘clf’, clf)<br>]</pre><pre>pipeline = Pipeline(steps=steps)</pre><pre># fit pipeline on train set<br>pipeline.fit(X_train, y_train)</pre><pre># make predictions<br>y_preds = pipeline.predict_proba(X_val)</pre><pre># score<br>score = roc_auc_score(y_val, y_preds[:, 1])<br>print(“Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction score is {}”.format(score))</pre><pre>Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction score is 0.7246471020853598</pre><p>Note I manually tweaked the oversampling and undersampling proportions.</p><p>Both train and validation sets are highly skewed towards the majority class.</p><pre># summarise class distribution<br>counter = Counter(y_train)<br>print(counter)<br>“1:{} ratio”.format(int(round((counter[0] / counter[1]),0)))</pre><pre>Counter({0: 13869, 1: 194})<br>&#39;1:71 ratio&#39;</pre><pre>counter = Counter(y_val)<br>print(counter)<br>“1:{} ratio”.format(int(round((counter[0] / counter[1]),0)))</pre><pre>Counter({0: 3455, 1: 61})<br>&#39;1:57 ratio&#39;</pre><p>I tried to handle this imbalance by applying oversampling and undersampling techniques. I could have further fine-tuned the hyperparameters but it is computationally expensive for my personal laptop so I proceed to test my model performance on the test set.</p><h3>7. Kaggle competition</h3><p>The Kaggle competition page can be found at the link below:</p><p><a href="https://www.kaggle.com/c/udacity-arvato-identify-customers/leaderboard#score">https://www.kaggle.com/c/udacity-arvato-identify-customers/leaderboard#score</a></p><p>For this competition, I needed to provide a .csv file with 2 columns:</p><ul><li><strong>‘LNR’:</strong> which acts as an ID number for each individual in the “TEST” partition.</li><li><strong>‘RESPONSE’:</strong> should be some measure of how likely each individual became a customer. Predicting individual classes and using accuracy does not seem to be an appropriate performance evaluation method due to high imbalance so I predicted probabilities for each invididual.</li></ul><p>The preparation code is attached below:</p><pre># define XGBClassifier pipeline and tweak sampling parameters manually<br>scaler = StandardScaler()<br>over = SMOTE(sampling_strategy=0.4) # oversampling minority class by 40%<br>under = RandomUnderSampler(sampling_strategy=0.6) # undersample majority class by 60%<br>clf = XGBClassifier(booster=’gbtree’, learning_rate=0.1, n_estimators=100, random_state=42)</pre><pre>steps = [<br> (‘scaler’, scaler),<br> (‘over’, over),<br> (‘under’, under),<br> (‘clf’, clf)<br>]</pre><pre>pipeline = Pipeline(steps=steps)</pre><pre># fit pipeline on full train set<br>pipeline.fit(X, y)</pre><pre># make predictions<br>y_preds = pipeline.predict_proba(preprocessed_mailout_test.drop(‘LNR’, axis=1))</pre><pre># put preds together with LNR<br>predictions = pd.DataFrame(columns=[&#39;LNR&#39;,&#39;RESPONSE&#39;])<br>predictions[&#39;LNR&#39;] = LNR_col<br>predictions[&#39;RESPONSE&#39;] = y_preds[:, 1]<br>predictions.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*_woS_RW8kLqIZTywXI77vA.png" /></figure><pre># convert to .csv file<br>predictions.to_csv(‘kaggle_bg.csv’, index=False)</pre><p>My position in the Kaggle leaderboard was 198 with a ROC AUC score of 0.73226. Not very impressive but expected due to small amount of time that i spent tuning the hyperparameters. This is acceptable for the purpose of learning though.</p><h3>8. Take-aways</h3><p>The Udacity’s Nanodegree Capstone Project was challenging for me. I had never had to deal with a dataset of +350 columns in a Customer Segmentation problem so finding a way to reduce the dimensionality and investigate the clusters was tricky and exciting at the same time.</p><p>The popular saying “A Data Scientist spends 80% of their time cleaning and understanding the data.” was proven in this project to me.</p><p>Eye to the detail is important. For example, to find unexpected values in the feature like the unknown values that had been mapped to a category.</p><p>From my experience in previous projects, dealing with a highly imbalanced dataset in a classification problem is not a walk in the park and this project was not an exception.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66360186392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fancy a trip to Menorca?]]></title>
            <link>https://bernardogarciadelrio.medium.com/fancy-a-trip-to-menorca-a7e6e12056ba?source=rss-9b5db1c122af------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7e6e12056ba</guid>
            <category><![CDATA[udacity-nanodegree]]></category>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bernardo Garcia del Rio]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 16:04:38 GMT</pubDate>
            <atom:updated>2020-12-11T06:19:40.892Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you are planning a holiday trip to Menorca, I recommend you read this post about AirBnB accommodations prices in Menorca for 2020–2021.</h4><p><em>(Bonus — You will learn something about Data Science and Machine Learning along the way)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wks3L73o6TTdGQTErQXQsg.jpeg" /><figcaption>Cala Galdana in Menorca (Image by Author)</figcaption></figure><p>Balearic Islands are well-known for being one of the most expensive holiday destinations in Spain, particularly during Summer season.</p><p><strong>In the first two parts of this post</strong>, I used publicly available data from AirBnB, data wrangling and descriptive statistics to answer the following questions:</p><ol><li>What is on average the <strong>summer price increase</strong> of AirBnB accommodations in Menorca?</li><li><strong>Can I overnight in Menorca for less than 35.00 USD?</strong> If so, where and in which type of accommodation?</li></ol><p><strong>In the third part</strong>, I take you through a theoretical business case where I was asked to develop a <strong>Machine Learning (ML) model for predicting mean accommodations prices.</strong></p><p>The datasets and code related to this post can be found in my GitHub repository (Link at the end of the post).</p><h3>What is on average the summer price increase of AirBnB accommodations in Menorca?</h3><p>In my country, Spain, everyone knows that people who live and work in Balearic Islands and do not own a property do struggle with rent increases during summer season.</p><p>Therefore, it is sensible to assume that AirBnB accommodations prices in Menorca will be more expensive in summer but…How much expensive?</p><p>In order to answer this question, I used a time-series with all the prices of all the AirBnB accommodations listed in Menorca from May 2020 to May 2021.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*nC5JPyd5HSErYjwMp2I-IQ.png" /></figure><p>The Line chart above shows the price mean values of all the AirBnB accommodations in Menorca over 1 year time. The red hatch around the line indicates the 95% confidence interval around the mean values.</p><p><strong>Are on average AirBnB accommodations more expensive in summer?</strong> Yes, we can easily spot a peak in the curve in the summer season. Mean price starts to go up in May 2020 and reaches a peak in August, when the curve flattens. Mean price sharply declines at the end of August when the summer season ends.</p><p>We can make some easy calculations and conclude that, on average, <strong>AirBnB accommodations prices in Menorca are increased by 23.22% in 2021 summer when comparing them to 2020/2021 winter prices.</strong></p><p>An interesting finding that we can also extract from the chart is that <strong>AirBnB accommodations in May 2021 are on average more expensive that in May 2020.</strong></p><p>We could have expected higher prices in May 2021. However, something unexpected to me was that the <strong>14.82% of the AirBnB accommodations in Menorca are actually cheaper in 2021 summer season, with higher prices in 2020/2021 winter season. </strong>(I found out this when calculating the average summer price increase.)</p><p>There might be two reasons behind this unexpected, at least to me, finding:</p><ul><li><strong>COVID-19</strong>: The pandemic is hitting hard on the Economy, specially on tourism businesses. Some AirBnB hosts might be reducing their prices as a mitigation measure.</li><li><strong>Combination of unknown reasons</strong>: It might be that for several unknown reasons, some accommodations offer a lower price in summer. e.g. a new listed accommodation that overestimated its market value.</li></ul><p>We can only speculate about this as there is not data available to get to a conclusion so…<strong>what are your thoughts?</strong></p><h3>Can I overnight in Menorca for less than 35.00 USD/night? If so, where and in which type of accommodation?</h3><p>Given the fact that Balearic Islands climate is soft and temperatures are warm throughout the year, I was curious to see if it is possible to stay in an AirBnB accommodation in Menorca for less than 35.00 USD/night, regardless of the season.</p><p>I grouped the data by type of accommodation and plotted some bar charts showing lowest prices over the year.</p><p>Let’s imagine you are 20 and your gang wants to rent <strong>an entire home or apartment for a budget trip</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNLA1uYGLWFqn9gmW7b2fw.png" /></figure><p>Wow! It seems there are quite a few choices such as <strong>Alaior, Ciutadella de Menorca and Es Mercadal </strong>so we could definitely rent an AirBnB entire home in Menorca for less than 35.00 USD a night.</p><p>Obviously, we would need to look deeper into the data to determine when these prices are available, condition of accommodation, etc..but it is possible!! After all, you don’t tend to think much about these things when you are 20!</p><p>What if you are thinking about a romantic weekend with your partner? <strong>A</strong> <strong>hotel seems a better choice</strong>..Can we find a budget hotel in Menorca?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_Dv9UXxtOXekVMVg_d2wA.png" /></figure><p>Mmm..It is not gonna be that easy. We could find something in <strong>Ciutadella de Menorca </strong>but I am not sure it would be a good choice for a romantic weekend…</p><p>Finally, let’s take a look at the options if we are looking for a <strong>shared accommodation with private room</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1M9Cf82gGR2jyoJyCjoTA.png" /></figure><p>We have many choices. <strong>We could find an accommodation for less than 35.00 USD/night pretty much everywhere in the island</strong> with only the exceptions of Alaior and Es Migjorn Gran areas.</p><p>To conclude, <strong>it is absolutely possible to find an AirBnB place for less than 35.00 USD a night</strong>, particularly if you are looking for an entire home/apartment or a shared accommodation with private room.</p><p>Let’s jump now into a theoretical business case where we could use ML.</p><h3>Business Case — Can we use a ML model to determine the launch price of an accommodation on AirBnB?</h3><p><em>(Note. In this part of the post, I am going to assume that the reader has a very high-level understanding of how ML and data can help businesses.)</em></p><p>Imagine that a friend of mine owns a property in Menorca and plans to list it on AirBnB next year to make an extra income.</p><p>He knows that I have a technical background and have been learning Data Science and ML, so he asks me to develop a model that can predict the mean accommodations prices during the period of 1 year.</p><p>Before giving him an answer, I want to make sure that <strong>this is actually feasible with the data available.</strong> (Public AirBnB datasets)</p><p>For non-technical people, ML models learn from data and then try to predict values when you pass them new data by using what they have learnt. (e.g. If I have a house in Ciutadella de Menorca with 5 bedrooms, 2 bathrooms and swimming pool, what is the AirBnB market price?)</p><p>Without going into much detail, these are the steps that I took in order to assess the feasibility of the project and select a promising model:</p><ol><li><strong>First glance at the data</strong>: Here is where you try to get a general understanding of your data. It is a high-level exploration. You start to think about good predictors of price (the target variable), if they will be available for your case (e.g. If I want to predict the launch price, I cannot use data about customer reviews), etc.</li><li><strong>Splitting the dataset</strong>: In ML models, it is necessary to split the dataset into a training set and a test set (also known as validation set) in order to measure model performance on new data. If you train your model with all your data and you measure the model performance on the same data, it is highly likely that the model will not perform well on data that it has never seen before.</li><li><strong>Exploratory Data Analysis (EDA)</strong>: This step is similar to step 1 but you go deeper into the data. You check for outliers (abnormal observations, e.g. that luxurious AirBnB apartment with sea views and jacuzzi) that can make difficult for ML models identifying patterns in the data, correlations with the target variable, etc. Here is when you decide the data your are going to use to train your model.</li><li><strong>Data Preparation:</strong> Preprocessing the data is very important in ML models. Here is when you impute or remove observations with missing values, encode categorical variables (transform categorical or text data into numerical data) and scale the data to have numerical data in the same order of magnitude.</li><li><strong>Select a promising model</strong>: You choose some ML models and measure their quality using different techniques. This is done on training data. Based on the results, you select the most promising model and move on to the next step.</li><li><strong>Evaluate model performance on test data</strong>: Finally, you trained the model and pass new data to the model in order to make predictions. You compared the predictions with the target values in the test set to determine the error.</li></ol><p>So after going through these steps…<strong>Can we use a ML model to determine the launch price of an accommodation on AirBnB?</strong> Yes, we can. A <strong>Random Forest Regressor </strong>seems to be a promising model compared to a Decision Tree Regressor and a Gradient Boosting Model.</p><p>However, the model needs to be refined before being useful for my friend. The <strong>Root Mean Square Error</strong> (<strong>RMSE</strong>), a metric used to measure model’s performance, was 162.59 USD, which is not acceptable for most prices ranging from 75.00 USD to 210.00 USD.</p><p>The next steps to refine this model might be:</p><ul><li>Get more training data, if possible.</li><li>Spend more time on feature selection. Try to combined attributes that could result in a better predictor of price.</li><li>Try different imputation methods.</li><li>Scale numerical variables using a different method.</li><li>Fine tune hyperparameters.</li></ul><h3>Datasets and Code</h3><p>The datasets and code related to this post can be found in my GitHub repository at the link below:</p><p><a href="https://github.com/bergr7/Project_1_AirBnB_Menorca">https://github.com/bergr7/Project_1_AirBnB_Menorca</a></p><p><em>Note this project was part of the Udacity Nano-degree program in which I am enrolled to. Any feedback that could help me improve is well received and appreciated. Thanks for reading!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7e6e12056ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>