<?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 Sushrut Shendre on Medium]]></title>
        <description><![CDATA[Stories by Sushrut Shendre on Medium]]></description>
        <link>https://medium.com/@sushrutshendre71?source=rss-209e2c291e24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SAjB1U6ogiUVkX8CrOqNqw@2x.jpeg</url>
            <title>Stories by Sushrut Shendre on Medium</title>
            <link>https://medium.com/@sushrutshendre71?source=rss-209e2c291e24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:02:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushrutshendre71/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[Sports Article Generation with HuggingFace]]></title>
            <link>https://medium.com/data-science/sports-article-generation-with-huggingface-157314eadd9e?source=rss-209e2c291e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/157314eadd9e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Sushrut Shendre]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 05:15:52 GMT</pubDate>
            <atom:updated>2020-07-23T20:52:55.511Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Sports Article Generation with HuggingFace’s GPT-2 module</strong></h3><p>Natural Language Processing (NLP) has extended the applications of Machine Learning to an entirely new dimension. Who would have thought that statistical models could be applied to the text we see daily, in order to generate business insights and predictions? More than ever, the past 2 years have seen a resurgence that NLP has not witnessed ever before.</p><p>Among the advanced methodologies that have come in NLP, there has been a tremendous interest in language generation models. The auto-regressive features in Open AI’s GPT-2 model have enabled the generation of new sequences of text that very closely represent what a human mind would think, say and write. These transformer-based neural network models show promise in coming up with long pieces of text that are convincingly human.</p><p>In this article, we look at how HuggingFace’s GPT-2 language generation models can be used to generate sports articles. To cater to this computationally intensive task, we will use the GPU instance from the <a href="https://spell.ml/">Spell.ml</a> MLOps platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3SkF9i5B_0XPYrBC" /><figcaption>Photo by <a href="https://unsplash.com/@tyleranderson_?utm_source=medium&amp;utm_medium=referral">Tyler Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Getting started with Spell</strong></p><p>As discussed above, language generation models can get computationally expensive and it becomes impossible for normal machines with CPUs to handle them. To tackle this, we make use of Spell’s GPU backed Jupyter notebooks. Spell is a powerful MLOps platform for machine learning and deep learning. It takes care of the infrastructure, thus enabling developers and enterprises to focus solely on the easy, fast, and organized execution of their machine learning models.</p><p>Getting setup with Spell is super-easy. Just visit <a href="https://spell.ml/">https://spell.ml/</a> and create a new account. Every new user at Spell gets $10 of free usage credit.</p><p>In this exercise, we will be using the Sports Article dataset from UCI’s Machine Learning Repository. This contains 1000 text files, each having a sports article written in them. In order to upload the text files, log in to Spell in your terminal or command prompt window and navigate to the parent folder of where you unzipped the files and type:</p><pre>spell upload ‘Raw data’</pre><p>This will upload the required text files into the Resources section of Spell. <a href="https://spell.ml/docs/resources/#uploading-resources">Learn more about uploading files to the Spell Resources here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N18d-Xo4hargKMgd" /></figure><p>To open a Jupyter notebook, login into the Spell web console and click on Workspaces &gt; Create Workspace.</p><p>Give the new workspace a name of your choice, and click on Continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*Ma40OezXNaCZ2hAE" /></figure><p>In the next screen, Spell gives you multiple options to define the environment you want to run your code in. For example, under Machine Type, you can choose from a variety of CPU and GPU options according to your use and budget. Further, you can choose the framework, the environment variables, and the libraries to install before your Jupyter is set up.</p><p>For the purpose of this project, we choose ‘V100’ under Machine Type; and Notebooks’ under Jupyter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*8wTDdLbNH5DNURQI" /></figure><p>In the next screen, let’s click on ‘Start Server’ to get started. Once that is done, we find a Jupyter infrastructure similar to what we have in our local machines. Click on New &gt; Python3.</p><p><strong>Overview of language generation algorithms</strong></p><p>Let’s install ‘transformers’ from HuggingFace and load the ‘GPT-2’ model.</p><pre>!pip install -q git+https://github.com/huggingface/transformers.git</pre><pre>!pip install -q tensorflow==2.1</pre><pre>import tensorflow as tf<br>from transformers import TFGPT2LMHeadModel, GPT2Tokenizer<br><br><br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br><br># add the EOS token as PAD token to avoid warnings<br>model = TFGPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;, pad_token_id=tokenizer.eos_token_id)</pre><p>These two objects let you use the pre-trained GPT-2 as is. The way we utilize GPT-2 or transformers in general, is to specify an input string/phrase that would essentially be the beginning of your article. The algorithms then predict the next set of words such that they are coherent with the initial string given.</p><p>Let’s try to understand the different types of algorithms and how GPT-2 is able to come up with the most human-like text passages.</p><p>Let’s start with the greedy search algorithm, which is one of the simplistic methods of word prediction. Based on the initial string, this algorithm greedily searches for the most probable next word. Using this new string, which is basically the initial string plus the predicted word, the next word is predicted. This process repeats itself until we have the desired number of words. The drawback of this method is that the words start repeating after a few lines/words of text. This happens because it misses the high probability words hidden behind low probability words.</p><p>Beam search mitigates this by keeping a predefined number of hypotheses each time, and eventually choosing the hypothesis that has the overall highest probability. But after several experiments, it was found that it still suffers from the problem of repeatability.</p><p>One of the best algorithms for language generation is that of sampling. Language generation using sampling is not deterministic since it randomly picks the next word according to its conditional probability distribution. But, it was observed that given the random nature, sampling sometimes produced passages of text that do not sound like a human.</p><p>A trick used to solve this problem was to sharpen the distribution of the prediction of the next word given previous <em>i</em> words. While sharpening, we still are drawing random samples; but in addition, we increase the likelihood of high probability words getting picked up, and decrease the likelihood of low probability words getting picked up.</p><p>Another transformation was the introduction of Top-K Sampling where the K most likely next words are filtered and the probability mass is redistributed among those K next words. This simple yet powerful concept was incorporated in the GPT-2 model and is one of the major reasons for its success. Yet another addition to the GPT-2 model was nucleus sampling. Instead of sampling only from the most likely K words, this model chose from the smallest possible set of words whose cumulative probability exceeds a predefined probability <em>p</em>. The incorporation of this feature made sure that the size of the set of words could dynamically increase and decrease according to the next word’s probability distribution.</p><p><strong>Example of sports text generation using the GPT-2 model</strong></p><p>Having understood its internal working at a high level, let’s dive into the working and performance of the GPT-2 model. Note that, at this point, we are using the GPT-2 model as is, and not using the sports data we had downloaded earlier. We’ll look more into how to use this data when we fine-tune the model in the next section.</p><p>The code below demonstrates the sampling technique incorporated by GPT-2. The ‘input_ids’ refers to the initial string given to the model. By specifying ‘do_sample’ to True, we are telling the model to use the sampling technique. ‘max_length’ corresponds to the desired length of the article. ‘top_k’ and ‘top_p’ correspond to K words and the nucleus probability p respectively. Finally, we specify an argument called ‘num_return_sequences’ to 2. This generates 2 different passages using the same initial string, and gives us an option to choose the output we like better.</p><pre>#initial string<br>input_ids = tokenizer.encode(&#39;Manchester City agree deal to sell Leroy Sane&#39;, return_tensors=&#39;tf&#39;)<br><br># set seed to reproduce results. Feel free to change the seed though to get different results<br>tf.random.set_seed(0)<br><br># set top_k = 50 and set top_p = 0.95 and num_return_sequences = 3<br>sample_outputs = model.generate(<br>    input_ids,<br>    do_sample=True, <br>    max_length=100, <br>    top_k=50, <br>    top_p=0.45, <br>    num_return_sequences=3 )<br><br>print(&quot;Output:\n&quot; + 100 * &#39;-&#39;)<br>for i, sample_output in enumerate(sample_outputs):<br>  print(&quot;{}: {}&quot;.format(i, tokenizer.decode(sample_output, skip_special_tokens=True)))</pre><p>Here’s the output:</p><pre>0: Manchester City agree deal to sell Leroy Sane<br><br>The Gunners are ready to sign Leroy Sane, who has been on loan at Tottenham for the past three seasons, from Chelsea.<br><br>The 21-year-old, who is in his first season at the club, has scored five goals in 14 games for the Blues this season.<br><br>The former Arsenal and Chelsea striker has been a target for Chelsea since he joined from Southampton in January 2013.<br><br>The deal is<br><br><br>1: Manchester City agree deal to sell Leroy Sane<br><br>Manchester City have agreed a £30million deal to sell Leroy Sane to Manchester United for £30million.<br><br>The move was confirmed by City sources.<br><br>Sane, 24, has scored nine goals in 20 Premier League appearances for the club since joining from Manchester United in January 2014.<br><br>He has scored seven goals in 16 Premier League appearances for United since joining from Manchester United in January 2014.</pre><p><strong>Custom GPT-2 : Fine-Tuning for sports articles data</strong></p><p>Having looked at the output, we can say that GPT-2 has been able to put together a cohesive piece of text. However, the factual statements it generates lack accuracy. Also, the passage as a whole does not give us a very sporty feeling. To address these issues, we try to train and finetune GPT-2 specifically on sports articles instead of using it as is. We will use the Sports Dataset which we had uploaded earlier.</p><p>Our first job is to collate the articles into a single text file. In order to do that, we initiate a new Jupyter notebook. Click on the ‘Files’ tab and then click on ‘Add mount’. Go to uploads and select the ‘Raw data’ folder you had just uploaded.</p><p>Come back to the notebook and execute the code below to read the text files and collate them.</p><pre>mypath = &#39;Raw data/&#39;<br>import os<br>from os import listdir<br>from os.path import isfile, join<br>onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]</pre><pre>article_list = &#39;&#39;<br>for i in range(len(onlyfiles)):<br>  if onlyfiles[i][-3:] == &#39;txt&#39;:<br>    try:<br>      with open(&#39;Raw data/&#39; + onlyfiles[i], &#39;r&#39;) as file:<br>        data = file.read()<br>      article_list = article_list + &#39;\n&#39; + data<br>    except:<br>      pass</pre><p>Once this is done, we need to use the ‘printable’ function in the string package to filter out all the characters that don’t belong to ASCII.</p><pre>import string<br>article_list_str = &#39;&#39;.join(filter(lambda x: x in string.printable, article_list))</pre><p>Once the data is in the desired format, let’s move on towards building the model. We install the ‘transformers’ package and import the required packages.</p><pre>!pip install transformers</pre><pre>import logging<br>import os<br>import pickle<br>import random<br>import torch<br>import torch.nn as nn<br>import transformers<br>from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler<br>from transformers import (<br>    GPT2Config,<br>    GPT2LMHeadModel,<br>    GPT2PreTrainedModel,<br>    GPT2Tokenizer,<br>    PreTrainedModel,<br>    PreTrainedTokenizer,<br>)<br><br>MODEL_CLASSES = {&quot;gpt2&quot;: (GPT2Config, GPT2LMHeadModel, GPT2Tokenizer)}<br><br>logger = logging.getLogger(__name__)</pre><p>Next, we define a class, ‘SportsData’ to finetune the sports dataset and get the tokens within it.</p><pre>class SportsData(Dataset):<br>    def __init__(<br>        self,<br>        tokenizer: PreTrainedTokenizer,<br>        #file_path: str,<br>        block_size=512,<br>        overwrite_cache=False,<br>    ):<br>        #assert os.path.isfile(file_path)<br><br>        block_size = block_size - (<br>            tokenizer.max_len - tokenizer.max_len_single_sentence<br>        )<br><br>        # change if args are added at later point<br>        cached_features_file = os.path.join(<br>           &quot;gpt2&quot; + &quot;_&quot; + str(block_size) + &quot;_file.txt&quot; <br>        )<br><br>        if os.path.exists(cached_features_file) and not overwrite_cache:<br>            logger.info(<br>                f&quot;Loading features from your cached file {cached_features_file}&quot;<br>            )<br>            with open(cached_features_file, &quot;rb&quot;) as cache:<br>                self.examples = pickle.load(cache)<br>                logger.debug(&quot;Loaded examples from cache&quot;)<br>        else:<br>            logger.info(f&quot;Creating features from file&quot;)<br><br>            self.examples = []<br><br>            text = article_list_str<br>            tokenized_text = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))<br><br>            for i in range(0, len(tokenized_text) - block_size + 1, block_size):<br>                self.examples.append(<br>                    tokenizer.build_inputs_with_special_tokens(<br>                        tokenized_text[i : i + block_size]<br>                    )<br>                )<br><br>            logger.info(f&quot;Saving features into cached file {cached_features_file}&quot;)<br>            with open(cached_features_file, &quot;wb&quot;) as cache:<br>                <br>                pickle.dump(self.examples, cache, protocol=pickle.HIGHEST_PROTOCOL)<br><br>    def __len__(self):<br>        return len(self.examples)<br><br>    def __getitem__(self, item):<br>        return torch.tensor(self.examples[item], dtype=torch.long)</pre><p>Finally, we initiate the training of the custom model and save the model.</p><pre>device = &#39;cpu&#39;<br>if torch.cuda.is_available():<br>    device = &#39;cuda&#39;<br></pre><pre>tokenizer = GPT2Tokenizer.from_pretrained(&#39;gpt2-medium&#39;)<br>model = GPT2LMHeadModel.from_pretrained(&#39;gpt2-medium&#39;)<br>model = model.to(device)<br><br>dataset = SportsData(tokenizer= tokenizer )<br>article_loader = DataLoader(dataset,batch_size=1,shuffle=True)<br><br>BATCH_SIZE = 1<br>EPOCHS = 1<br>LEARNING_RATE = 0.0002<br>WARMUP_STEPS = 5000<br><br>from transformers import AdamW, get_linear_schedule_with_warmup<br><br>model = model.to(device)<br>model.train()<br>optimizer = AdamW(model.parameters(), lr=LEARNING_RATE)<br>scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=WARMUP_STEPS, num_training_steps=-1)<br>script_count = 0<br>sum_loss = 0.0<br>batch_count = 0<br><br>for epoch in range(EPOCHS):<br>    print(f&quot;EPOCH {epoch} started&quot; + &#39;=&#39; * 30)<br>    for idx,script in enumerate(article_loader):<br>        outputs = model(script.to(device), labels=script.to(device))<br>        #outputs = torch.tensor(tokenizer.encode(script)).unsqueeze(0).to(device) <br>        loss, logits = outputs[:2]                        <br>        loss.backward()<br>        sum_loss = sum_loss + loss.detach().data<br>                       <br>        script_count = script_count + 1<br>        if script_count == BATCH_SIZE:<br>            script_count = 0    <br>            batch_count += 1<br>            optimizer.step()<br>            scheduler.step() <br>            optimizer.zero_grad()<br>            model.zero_grad()<br>            <br>        if batch_count == 200:<br>            model.eval()<br>            print(f&quot;sum loss {sum_loss}&quot;)<br>            sample_outputs = model.generate(<br>                                    bos_token_id=random.randint(1,30000),<br>                                    do_sample=True,   <br>                                    top_k=50, <br>                                    max_length = 1000,<br>                                    top_p=0.95, <br>                                    num_return_sequences=1<br>                                )<br><br>            print(&quot;Output:\n&quot; + 100 * &#39;-&#39;)<br>            for i, sample_output in enumerate(sample_outputs):<br>                  print(&quot;{}: {}&quot;.format(i, tokenizer.decode(sample_output, skip_special_tokens=True)))<br>            <br>            batch_count = 0<br>            sum_loss = 0.0<br>            model.train()</pre><pre>output_dir = &#39;Raw data/&#39;<br><br>from transformers import WEIGHTS_NAME, CONFIG_NAME<br>output_model_file = os.path.join(output_dir, WEIGHTS_NAME)<br>output_config_file = os.path.join(output_dir, CONFIG_NAME)<br><br>torch.save(model.state_dict(), output_model_file)<br>model.config.to_json_file(output_config_file)<br>tokenizer.save_vocabulary(output_dir)</pre><p>Now that we have the fine-tuned model ready, we import it and test how it works against the same input string that we used previously.</p><pre>model = GPT2LMHeadModel.from_pretrained(output_dir)<br>tokenizer = GPT2Tokenizer.from_pretrained(output_dir)<br><br>input_ids = tokenizer.encode(&#39;Manchester City agree deal to sell Leroy Sane&#39;, return_tensors=&#39;pt&#39;)<br><br>sample_outputs = model.generate(<br>                        input_ids= input_ids,<br>                        do_sample = True,<br>                        #num_beams= 5,<br>                        max_length = 100,<br>                        top_k = 50,<br>                        top_p=0.85, <br>                        num_return_sequences=1<br>                    )<br><br>print(&quot;Output:\n&quot; + 100 * &#39;-&#39;)<br>for i, sample_output in enumerate(sample_outputs):<br>      print(&quot;{}: {}&quot;.format(i, tokenizer.decode(sample_output, skip_special_tokens=True)))</pre><p>Here’s the output:</p><pre>Output:<br>----------------------------------------------------------------------------------------------------<br>0: Manchester City agree deal to sell Leroy Sane to Liverpool<br><br>Leroy Sane was among three players who were sold this summer and Liverpool boss Brendan Rodgers admitted he felt the need to replace the former Manchester City winger.<br><br>&quot;We sold four players last year and I know I had to get another player in to improve our squad,&quot; Rodgers told Sky Sports News HQ.<br><br>&quot;We had to sell players and a few of them we did but it was Leroy Sane.</pre><p>We observe that this passage of text not only sounds like a human but has a much better flow to it. The manager quotes especially give this passage a much more realistic feel and make it look very similar to what an actual hand-written article would be like. Note that increasing the value of ‘max_length’ would allow us to get even lengthier pieces of text.</p><p>Please note that the facts are still not completely correct but these can be quickly rectified using our knowledge. What matters is that we have been able to get rid of the manual process of writing. Just run this command, edit some factual discrepancies that might be there, and voila, you’re done.</p><p>To try this tutorial out, sign on to Spell’s MLOps platform, using <a href="https://web.spell.ml/refer/sushrut17">this link</a> and get a $10 free GPU credit once you’ve made an account. Also, please feel free to post your questions and queries on this <a href="https://chat.spell.ml/">Slack link</a>.</p><p><strong>References:</strong></p><p><a href="https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb#scrollTo=mQHuo911wfT-">https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb#scrollTo=mQHuo911wfT-</a></p><p><a href="https://github.com/cdpierse/script_buddy_v2/tree/master/script_buddy">https://github.com/cdpierse/script_buddy_v2/tree/master/script_buddy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=157314eadd9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sports-article-generation-with-huggingface-157314eadd9e">Sports Article Generation with HuggingFace</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[Model Drift in Machine Learning models]]></title>
            <link>https://medium.com/data-science/model-drift-in-machine-learning-models-8f7e7413b563?source=rss-209e2c291e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7e7413b563</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[strategy]]></category>
            <dc:creator><![CDATA[Sushrut Shendre]]></dc:creator>
            <pubDate>Wed, 13 May 2020 22:40:16 GMT</pubDate>
            <atom:updated>2020-05-14T01:50:12.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Drift in Machine Learning</h3><h4>How and when should machine learning models be retrained</h4><p>Notions, people and societies have changed drastically over the course of time. What was once the state-of-the-art has now become obsolete; likewise, what is now a fresh idea is likely to be forgotten a few years down the line. Similarly, understanding change is vital for businesses. Imagine any mobile-phone manufacturing company 15 years back. Would they have been able to sustain themselves if they hadn’t upgraded to smartphones? Most probably not. While having a regular mobile phone was the norm 15 years back, the demand sharply migrated towards smartphones. Companies failing to match the pace of this change in customer behavior were hit the worst.</p><p>As we enter a world dictated by data and analytics, machine learning models have become the major drivers of business decisions. And as with any other business strategy, these models need to be revised with time, the technical reason behind which being ‘Model Drift’. While most course curriculums, articles, and posts define a machine learning (ML) lifecycle to start with the collection of data and to end with the deployment of the ML model in the respective environment, they forget a very important feature in the ML lifecycle, that of model drift.</p><p>What it essentially means is that the relationship between the target variable and the independent variables changes with time. Due to this drift, the model keeps becoming unstable and the predictions keep on becoming erroneous with time. Let us try to understand it from a technical viewpoint with the help of simple linear regression. In linear regression, we simply map the independent variables x_i­ to predict the target variable <em>y </em>:</p><blockquote>y = α + β_1*x_1 + β_2*x_2 + β_3*x_3 + …</blockquote><p>where, <em>α</em> is the intercept, and <em>β_i</em> correspond to the coefficients for the variable <em>x_i.</em></p><p>Often, we assume this mapping to be static, i.e. we assume that the coefficients <em>β_i </em>(and the intercept <em>α</em>) do not change with time and that the relationships governing the prediction of the target variable <em>y</em> will be valid for future data as well. This assumption may not hold true in all cases. And wherever it doesn’t, it poses a serious threat to the business. This is because the profits of the organizations depend on such models to a great extent; and while these models might be representative of the situation at the time of development, they certainly might not hold true in the future. Owing to these changes in the underlying conditions, the predictions will start getting less accurate with time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ih53letrZpXrlLSe" /><figcaption>Photo by <a href="https://unsplash.com/@enginakyurt?utm_source=medium&amp;utm_medium=referral">engin akyurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Types of drift</h4><p>Model drift can be classified into two broad categories. The first type is called ‘concept drift’. This happens when the statistical properties of the target variable itself change. As is evident, if the very meaning of the variable that we are trying to predict, changes, the model wouldn’t really work well for this updated definition. Duh!</p><p>The second and the more common type is ‘data drift’. This happens when the statistical properties of the predictors change. Again, if the underlying variables are changing, the model is bound to fail. So obvious! A classic example of when this might happen is when the patterns in the data change due to seasonality. Whatever business model works in the summer, might not work in the winter. While flight demand surges during the holiday seasons, airlines struggle to maintain occupancy in the off-seasons. Another example is when personal preferences change, which can be related to the smartphone example mentioned in the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*U1R15cH2Aj1MXfVox_Fx9A.png" /></figure><h4>How to address this?</h4><p>The best way to address this issue is to continuously re-fit the models. Based on past experiences, an estimate can be made as to when drift starts to creep in the model. Based on this, the model can be proactively re-developed so as to mitigate the risks associated with drift.</p><p>For situations where the data changes with time, weighing data can be a good option. For example, financial models deciding certain parameters based on recent transactions can incorporate features that give more weight to most recent transactions and lesser weights to past transactions. This not only ensures that the model is robust, but also helps keep the potential issues related to drift at bay.</p><p>A more complex methodology to fight model drift is to model the change itself. The first model developed is kept static, and serves as a baseline. Now, as a result of a change in behavior in the recent data, new models can be built to correct the predictions of this baseline model.</p><h4>How often should models be re-trained?</h4><p>Now that we have seen that the most common solution involves continuous re-training of the model, questions arise as to how often this needs to be done. There are multiple solutions to this, each of which differ depending on the situation.</p><p>Sometimes, the problem will present itself. While waiting for the problem to happen is not the most elegant method, it remains the only option when it comes to new models, wherein there is no past history to understand when things might go wayward. When the problem surfaces, investigations can be made into what went wrong, and modifications can be incorporated to suppress such issues in the future.</p><p>At other times, the data related to the entities addressed in the model, observe patterns of seasonality. Here, the model should be retrained according to these seasons. For example, with an increase in spending during festive seasons, the credit lending institutes need to have special models to tackle this sudden change in patterns.</p><p>The best way to detect drift, however, is continuous monitoring. Metrics related to the stability of the model need to be monitored at continuous intervals. This interval can be a week, a month, a quarter, etc. depending upon the domain and the business. The mode of monitoring can either be manual, or an automated script that triggers alarms and notifications whenever sudden anomalies are observed.</p><p>That brings us to the end of this article. As Heraclitus had famously said, ‘Change is the only constant’. Keeping that in mind, the organizations that embrace and monitor these changes with preparedness, are the ones destined to succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flg-_a6A415xYXrbHweLeA.png" /></figure><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7e7413b563" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/model-drift-in-machine-learning-models-8f7e7413b563">Model Drift in Machine Learning models</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[Clustering datasets having both numerical and categorical variables]]></title>
            <link>https://medium.com/data-science/clustering-datasets-having-both-numerical-and-categorical-variables-ed91cdca0677?source=rss-209e2c291e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed91cdca0677</guid>
            <category><![CDATA[mixed-data-types]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Sushrut Shendre]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 01:25:36 GMT</pubDate>
            <atom:updated>2020-05-11T18:53:40.006Z</atom:updated>
            <content:encoded><![CDATA[<p>With the advent of machine learning in the modern era, businesses have seen a transformation in the way they make decisions and drive profits. One of the most important attributes of a successful firm is how well they can understand their customers and how well they can cater to their personalized needs. It has become increasingly important for firms to understand that the ‘one size fits all’ model doesn’t work anymore.</p><p>This brings us to the topic of clustering. Clustering is nothing but segmentation of entities, and it allows us to understand the distinct subgroups within a data set. While many articles review the clustering algorithms using data having simple continuous variables, clustering data having both numerical and categorical variables is often the case in real-life problems. This article discusses a clustering approach using Gower distance, the PAM (Partitioning Around Medoids) method, and silhouette width and explains each of the steps with an implementation in R.</p><p>We are using the ‘<a href="https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/"><strong>germancredit</strong></a>’<em> </em>data taken from UCI’s Machine Learning Repository: (<a href="https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/">https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/</a>). To import the data in R, we use the ‘<strong>read.table’</strong> command as follows:</p><pre>set.seed(2020)<br>german_credit = read.table(&quot;<a href="http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data">http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data</a>&quot;)</pre><p>We observe that the column names of this data set are not self-explanatory, and therefore we rename the columns with the help of the <a href="https://archive.ics.uci.edu/ml/datasets/statlog+(german+credit+data)">documentation</a>.</p><pre>colnames(german_credit) = c(&quot;chk_acct&quot;, &quot;duration&quot;, &quot;credit_his&quot;, &quot;purpose&quot;, &quot;amount&quot;, &quot;saving_acct&quot;, &quot;present_emp&quot;, &quot;installment_rate&quot;, &quot;sex&quot;, &quot;other_debtor&quot;,                   &quot;present_resid&quot;, &quot;property&quot;, &quot;age&quot;, &quot;other_install&quot;, &quot;housing&quot;, &quot;n_credits&quot;, &quot;job&quot;, &quot;n_people&quot;, &quot;telephone&quot;, &quot;foreign&quot;, &quot;response&quot;)</pre><p>Further, to make things easier, we select only a few variables that are relatively more important. Please note that I have selected these particular columns only for illustration purposes, and readers are free to experiment with a different set of columns.</p><pre>library(dplyr)<br>german_credit_clean = german_credit %&gt;% select(duration, amount, installment_rate, present_resid, age, n_credits, n_people, chk_acct, credit_his, sex, property, housing, present_emp)</pre><p>We see that this data set contains both numerical (continuous) as well as categorical variables.</p><p><strong>Continuous Variables:</strong></p><p>· duration: duration in months<br>· amount: the credit amount of the loan<br>· installment_rate: Installment rate in percentage of disposable income<br>· present_resid: time since living in the present residence<br>· age: Age in years<br>· n_credits: number of existing credits at this bank<br>· n_people: number of people being liable to provide maintenance for<br>· credit_his: Credit history<br>· property: Property<br>· housing: Housing<br>· present_emp: Present employment since</p><p><strong>Categorical variables:</strong></p><p>· chk_account: status of an existing checking account<br>· sex: Personal status and sex<br>· credit_his: Credit history<br>· property: Property<br>· housing: Housing<br>· present_emp: Present employment since</p><p>Now that we are done with understanding and preprocessing the data, we turn our heads towards clustering. The basic premise of clustering is the similarity/dissimilarity between the data points. As we know, the K-means algorithm iterates over and over until it attains a state wherein all points of a cluster are similar to each other, and points belonging to different clusters are dissimilar to each other. This similarity/dissimilarity is defined by the distance between the points.</p><p>A popular choice for the metric to measure this distance is the Euclidean distance. Some researchers also advocate the use of Manhattan distance for particular types of problems. However, both of these distance metrics are applicable only for continuous data. In our data which contains mixed data types, Euclidean and Manhattan distances are not applicable and therefore, algorithms such as K-means and hierarchical clustering would fail to work.</p><p>Therefore, we use the Gower distance which is a metric that can be used to calculate the distance between two entities whose attributes are a mix of categorical and quantitative values. This distance is scaled in a numerical range of 0 (identical) and 1 (maximally dissimilar). The details about the mathematics of Gower distance are quite complicated and left out for another article.</p><p>In R, the Gower distance can be calculated using the ‘<strong>daisy</strong><em>’</em> package. Before we use the ‘<strong>daisy</strong>’ function, we observe the distribution of the numerical variables to understand if any of them need transformations. We find that the variable <em>amount</em> needs a log transformation due to the positive skew in its distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCCwKryux7MsmU5y5g1hrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdehsec3T6_K29vBflhJuA.png" /></figure><p>The following code shows the implementation of the Gower distance calculation. Note that we have specified ‘2’ as the parameter in the <em>type</em> argument. This ensures that the second variable, <em>amount</em><strong> </strong>undergoes a log transformation before the Gower calculations are performed.</p><pre>library(cluster)<br>gower_df &lt;- daisy(german_credit_clean,<br>                    metric = &quot;gower&quot; ,<br>                    type = list(logratio = 2))</pre><p>Next, we check the summary of the <strong>‘gower_df’ </strong>data frame. The type ‘I’ and ‘N’ tell us whether the respective columns are interval-scaled (numerical), or nominal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*4VweGqKXtSdEeWRMo8YzpA.png" /></figure><p><strong>K-medoids and Partitioning Around Medoids</strong></p><p>Now that we have a distance matrix in place, we need to choose a clustering algorithm to infer similarities/dissimilarities from these distances. Just like K-means and hierarchical algorithms go hand-in-hand with Euclidean distance, the Partitioning Around Medoids (PAM) algorithm goes along with the Gower distance. PAM is an iterative clustering procedure just like the K-means, but with some slight differences. Instead of centroids in K-means clustering, PAM iterates over and over until the <strong>medoids</strong> don&#39;t change their positions. The medoid of a cluster is a member of the cluster which is representative of the median of all the attributes under consideration.</p><p><strong>Silhouette Width to select the optimal number of clusters</strong></p><p>The silhouette width is one of the very popular choices when it comes to selecting the optimal number of clusters. It measures the similarity of each point to its cluster, and compares that to the similarity of the point with the closest neighboring cluster. This metric ranges between -1 to 1, where a higher value implies better similarity of the points to their clusters. Therefore, a higher value of the Silhouette Width is desirable. We calculate this metric for a range of cluster numbers and find where it is maximized. The following code shows the implementation in R:</p><pre>silhouette &lt;- c()<br>silhouette = c(silhouette, NA)</pre><pre>for(i in 2:10){<br>  pam_clusters = pam(as.matrix(gower_df),<br>                 diss = TRUE,<br>                 k = i)<br>  silhouette = c(silhouette ,pam_clusters$silinfo$avg.width)<br>}</pre><pre>plot(1:10, silhouette,<br>     xlab = &quot;Clusters&quot;,<br>     ylab = &quot;Silhouette Width&quot;)<br>lines(1:10, silhouette)</pre><p>The silhouette width is plotted versus the number of clusters, as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*aHl6e8zvZfu-inMqcInjbw.png" /></figure><p>As can be seen, the value is maximized at 5. Hence, we can conclude that clustering the data into 5 clusters gives us the best segmentation possible. Having said that, we construct a PAM model with 5 clusters, and try to interpret the behavior of these clusters with the help of the medoids.</p><pre>pam_german = pam(gower_df, diss = TRUE, k = 5)<br>german_credit_clean[pam_german$medoids, ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*fdSknCbkwUzSSMuzCbxK5g.png" /></figure><p>The figure above shows the medoids table, where each row represents a cluster. Using this table, we can infer that customers belonging to Cluster 1 have the following characteristics: the duration is 15 months, the credit amount is 1829$, the installment rate is 4, they have been living in the present residence since 4 months, their average age is 46 years, they have 2 loans pending, they have 1 dependent, they have no checking account (A14), their credit history is critical (A34), they are male singles (A93), they have a car as their property (A123), live in their own housing (A152), and have been employed for more or equal to 7 years (A75). Please note that not all customers will be exactly like this; and that the medoids are only a representation of the median values.</p><p>Similar interpretations can be made for the other clusters. To dig deeper into the characteristics of each cluster, we find the summary stats. The R code for the same is as shown below, along with the statistics for the first cluster.</p><pre>pam_summary &lt;- german_credit_clean %&gt;%<br>  mutate(cluster = pam_german$clustering) %&gt;%<br>  group_by(cluster) %&gt;%<br>  do(cluster_summary = summary(.))</pre><pre>pam_summary$cluster_summary[[1]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*ZtVkOqjh_zpXWEAQvPJIPw.png" /></figure><p><strong>Visualization</strong></p><p>Finally, let us wrap this article up with some fancy visualizations. For this, we use the t-SNE or the t-Distributed Stochastic Neighbor Embedding technique. This technique provides a great way to visualize a multi-dimensional data set such as the one we are working on.</p><pre>library(Rtsne)<br>library(ggplot2)</pre><pre>tsne_object &lt;- Rtsne(gower_df, is_distance = TRUE)</pre><pre>tsne_df &lt;- tsne_object$Y %&gt;%<br>  data.frame() %&gt;%<br>  setNames(c(&quot;X&quot;, &quot;Y&quot;)) %&gt;%<br>  mutate(cluster = factor(pam_german$clustering))</pre><pre>ggplot(aes(x = X, y = Y), data = tsne_df) +<br>  geom_point(aes(color = cluster))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Ix5sdE2op66YJ_p_fwtlAA.png" /></figure><p>As we can see, t-SNE has helped us visualize multi-dimensional data into a simple two-dimensional plot. Although the clusters seem to have some overlap, they are pretty distinctive overall.</p><p>This brings us to the end of this article. Summarizing, we discussed the concepts of Gower distance, PAM clustering, and Silhouette width to cluster data having both numerical and categorical features. Hope this helps all the data people around here who come across such data sets.</p><p>Happy Clustering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed91cdca0677" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/clustering-datasets-having-both-numerical-and-categorical-variables-ed91cdca0677">Clustering datasets having both numerical and categorical variables</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>