<?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 Duncan W. on Medium]]></title>
        <description><![CDATA[Stories by Duncan W. on Medium]]></description>
        <link>https://medium.com/@duncan-w?source=rss-6de39228b050------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UkZHYrUGatRnOAro8BEJfA.png</url>
            <title>Stories by Duncan W. on Medium</title>
            <link>https://medium.com/@duncan-w?source=rss-6de39228b050------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:58:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@duncan-w/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[Lesk’s Algorithm: A Method for Word Sense Disambiguation in Text Analytics]]></title>
            <link>https://medium.com/data-science/lesks-algorithm-a-method-for-word-sense-disambiguation-in-text-analytics-52c157a2fdff?source=rss-6de39228b050------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c157a2fdff</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Duncan W.]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 14:33:13 GMT</pubDate>
            <atom:updated>2023-03-24T14:33:13.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SHNhkkmUYGmx8weA" /><figcaption>Photo by <a href="https://unsplash.com/@amadorloureiro?utm_source=medium&amp;utm_medium=referral">Amador Loureiro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the English language, more than 38% of words are <strong>polysemous</strong>, a term referring to a single word which may have multiple definitions, or “senses” (Edmonds, 2006). The word “set” for instance — which can be used as a noun, verb, and adjective — has dozens of unique definitions, making it one of the most polysemous words recorded in the English dictionary. Thus, if we were to ask someone to “please set the set of cutlery on the table”, how would we instinctively know the difference between the two uses of “set”? The answer is all in the context. The human brain’s neural networks perform semantic processing, storage, and retrieval in a way which makes us naturally gifted at <strong>word-sense disambiguation (WSD)</strong>. This essentially means that we are able to be quite proficient at determining the meaning of a word with multiple definitions, based on what makes the most sense in a given context. As such, the natural language has consequently also developed in a way which reflects this innate ability to perform these complex contextual associations.</p><h3>Word-sense disambiguation in NLP</h3><p>While our brains can play these games with great success, words with multiple senses pose a significant problem in <strong>Natural Language Processing (NLP)</strong>, a branch of artificial intelligence which studies the ability of computers to interpret and “understand” the human language. While the sense of a word depends on its context, the context of a word can be difficult to capture by computers, as it is complicated by metaphors, modifiers, sentence negations, and countless other intricacies of language which make it difficult for a machine to learn.</p><p>Due to the significant value of word sense disambiguation in practical applications of NLP, several methods of performing word sense disambiguation have emerged over the years. Current machine learning approaches include supervised-learning methods, whereby a collection of manually sense-tagged words are used to train classification algorithms. However, these training sets can be expensive, time consuming to procure, and imperfect, since even human annotators often only agree on a word sense 70–95% of the time (Edmonds, 2006). Given the manual effort required, unsupervised learning methods are also used, many of which aim to cluster words based on some measure of similar context.</p><h3><strong>Lesk’s Algorithm: A simple method for word-sense disambiguation</strong></h3><p>Perhaps one of the earliest and still most commonly used methods for word-sense disambiguation today is<strong> Lesk’s Algorithm</strong>, proposed by Michael E. Lesk in 1986. Lesk’s algorithm is based on the idea that words that appear together in text are related somehow, and that the relationship and corresponding context of the words can be extracted through the definitions of the words of interest as well as the other words used around it. Developed long before the advent of modern technology, Lesk’s algorithm aims to disambiguate the meaning of words of interest — usually appearing within a short phrase or sentence — by finding the pair of matching dictionary “senses” (i.e. synonyms) with the greatest word overlap in dictionary definitions.</p><p>In the example Lesk uses, he references the words “pine” and “cone”, noting that the words return the following definitions from the Oxford English Dictionary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKuu_Gl4ND5wGWj7UD4bdw.png" /><figcaption>Example of sense-matching proposed by Lesk in 1986.</figcaption></figure><p>In the simplest terms, Lesk’s algorithm counts the number of overlaps between all dictionary definitions of a word of interest and all dictionary definitions of the words surrounding it, known as a “context window”. Then, it takes the definition corresponding to the word with the highest number of overlaps, without including stop words (words such as “the”, “a”, “and”), and infers it to be the word’s “sense”. If we consider “pine” to be the word of interest, and “cone” to be the only word in its context window, comparing dictionary definitions of “pine” and “cone” would find that “evergreen” is the most common “sense” to both terms. Thus, we can logically infer that the word of interest “pine” refers to an evergreen tree, rather its alternate definition.</p><h3><strong>Advantages and Disadvantages</strong></h3><p>There are numerous advantages to Lesk’s algorithm, the primary being that its simplicity makes it easy to implement, applicable in a variety of different contexts, and thus easily generalizable. Lesk notes that the algorithm does not depend on global information, meaning that since the same word could be referenced many times throughout a text but change each time, the meaning of a word is only derived from the collection of immediate supporting words in its context window, rather than from the entire text itself. In addition, Lesk’s algorithm is non-syntactic, meaning that the approach does not depend on the arrangement of words or structure of a sentence, since all associations are made by dictionary-definition only. This makes the algorithm a good approach to use in tandem to syntax based text analytics solutions. For instance, a part-of-speech based text tagger might be able to identify the use of “mole” as a noun, but would fail at accurately differentiating between the animal (mole), the skin growth (mole), and the unit of measurement (mole), since all three are nouns. In cases such as this, the benefits of Lesk’s algorithm shines through.</p><p>Despite its simplicity and power, the biggest drawback to Lesk’s original algorithm is its performance — its accuracy was proposed by Lesk to be only around 50–70%, and has been shown to be much lower when experimentally validated against sense-tagged texts (Viveros-Jiménez, 2013). The algorithm also notably suffers from low recall, in that it cannot provide a corresponding contextual definition for many words simply because there is either no overlap to be found between dictionary definitions at all, or that several definitions have the same number of overlaps. Furthermore, Lesk leaves several questions unanswered. This includes what dictionary is best used, if all matched terms should be considered equally or weighed by the length of the dictionary definition itself, and how wide the context window of words should be (Lesk proposes around 10 words but suggests that it is quite flexible).</p><h3><strong>Moving forward: more recent advancements from Lesk</strong></h3><p>While Lesk left several questions and weaknesses in his approach unaddressed, significant efforts have been made to build upon the logic of his original work. In 2002, researchers proposed an adaptation to Lesk’s dictionary based algorithm by replacing it with the lexical database, WordNet (Banerjee &amp; Pedersen, 2002). Unlike a dictionary, wherein words and definitions are arranged alphabetically in a sequence, <strong>WordNet </strong>is an online database which arranges words semantically, creating groups of databases of nouns, verbs, adjectives, and adverbs. Words that are synonymous to each other are grouped together into a relation known as a “synset”, and polysemous words can be identified in WordNet by their occurrence in multiple synsets, since each individual synset represents a distinct definition or “sense” of a word. WordNet considers word relationships such as hyponymy (a word that is part of a broader class, i.e. a tulip is a flower, a flower is a plant), and metonymy (a figure of speech where a word is referred to by the name of something closely related, i.e. the “crown” refers to the monarchy), and is therefore able to capture a much wider range of word definitions and relationships than the original Lesk algorithm. The structure of WordNet allows for more targeted searching of related words, since if the part of speech for the word of interest is known, relations and synsets subsequently searched will only be those within that part of speech.</p><p>The low-recall problem of Lesk’s algorithm has also been an area of improvement. In 2013, researchers published a paper comparing several experiments in which they adjusted the size of the context window of words considered, in an effort to improve the performance of the algorithm (Viveros-Jiménez et al., 2013). A novel proposition made was to both consider only four words with at least one overlap when defining the size of the context window, as well as removing the target word of interest itself from consideration in sense-matching. Since dictionary definitions will often include the word of interest itself in an example sentence, &quot;i.e. the pine tree is a type of evergreen tree&quot;, for the word &quot;pine&quot;, this may create false overlaps on &quot;pine&quot; in which case the top matched word from all senses results in &quot;pine&quot; itself being output, instead of &quot;evergreen&quot;. Researchers found that when combining these two approaches, both precision and recall of the Lesk algorithm improved significantly, benchmarked against the alternative of simply choosing a context-window of 4 words.</p><h3>Applying Lesk’s Algorithm in Python</h3><p>The following is a simple example of how Lesk’s algorithm can be implemented, using the <strong>pywsd</strong> package for word-sense disambiguation in Python. The following function was developed as an implementation of the Adapted Lesk algorithm described by Banerjee &amp; Pederson in 2002, which uses the WordNet implementation of Lesk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8hsLE0ASEJRIyU7j5nMNQ.png" /><figcaption>Example of the Adapted Lesk’s Algorithm implemented in Python</figcaption></figure><p>We can see here that given the word “bank”, Lesk’s algorithm is able to infer that when used in context, one sense of bank refers to the financial institution, while the other refers to a type of sloping land. Again, when making such associations, the syntactical structure does not matter, rather, the success of Lesk’s algorithm depends on the availability of contextual cues, such as “river” and “fish”, when referring to a river bank, and “deposit” and “money” when referring to a financial bank. It can be seen through this example that Lesk is robust to sentence structure, and can therefore be used to extract word senses from a variety of unstructured text data types, whether it is excerpts from a classical novel or a Twitter comment. However, since Lesk’s algorithm is sensitive to the size of the context window, this data structure constraint perhaps most limits its implementation. As such, the data must be structured and tokenized into appropriately sized windows so that enough contextual information is provided, but the true meaning of the words of interest can still be captured. Since Lesk’s algorithm is perhaps best applied to short phrases and groupings of related terms with contextual information, it could be applied to query-and-retrieve type situations, such as an automated chatbot or search box where some contextual information is input, it is interpreted, and then a response or result is returned.</p><p>Though simple in intuition, Lesk’s algorithm and similar word sense disambiguation methods have served as foundational stepping stones for current work in developing intuitive everyday tools where word-sense disambiguation is necessary. Most notably, the intuition behind such algorithms can be practically applied to develop new algorithms to improve the relevance of information retrieval by search engines used by billions of people around the world today. After all, when we search for an ambiguous term, we instinctively know to include a “contextual window” of terms to increase the likelihood of an accurate hit.</p><p>And why? Because context is everything.</p><p><em>Thanks for reading! Please feel free to reach out to me on Linkedin if you want to share any thought</em>s!</p><p><a href="https://www.linkedin.com/in/duncan-w/">https://www.linkedin.com/in/duncan-w/</a></p><h3><strong>Resources</strong></h3><p>Banerjee, S. &amp; Pedersen, T. (2002). An Adapted Lesk Algorithm for Word Sense Disambiguation Using WordNet. Computational Linguistics and Intelligent Text Processing. 2276. 136–145. 10.1007/3 − 540 − 45715 − 111.</p><p>Edmonds, P. (2006). Disambiguation, Lexical. Encyclopedia of Language and Lingustics (second edition), Elsevier, p. 607–623.</p><p>Lesk, M. (1986). Automatic sense disambiguation using machine readable dictionaries. Proceedings of the 5th Annual International Conference on Systems Documentation — SIGDOC<br> Liling Tan. 2014. Pywsd: Python Implementations of Word Sense Disambiguation (WSD)</p><p>Technologies [software]. Retrieved from https : //github.com/alvations/pywsd</p><p>SAP Conversational AI. (2015, November 20). From context to user understanding. Retrieved February 11, 2021, from https : //medium.com/@SAPCAI/from − context − to − user − understanding − a692b11d95aa</p><p>Viveros-Jiménez F., Gelbukh A., Sidorov G. (2013) Simple Window Selection Strategies for the Simplified Lesk Algorithm for Word Sense Disambiguation. In: Castro F., Gelbukh A., González M. (eds) Advances in Artificial Intelligence and Its Applications. MICAI 2013. Lecture Notes in Computer Science, vol 8265. Springer, Berlin, Heidelberg. https : //doi.org/10.1007/978 − 3 − 642 − 45114 − 017</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c157a2fdff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/lesks-algorithm-a-method-for-word-sense-disambiguation-in-text-analytics-52c157a2fdff">Lesk’s Algorithm: A Method for Word Sense Disambiguation in Text Analytics</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[How AI Can Help Us Recycle]]></title>
            <link>https://medium.com/data-science/how-ai-can-help-us-recycle-c2f82d0d50de?source=rss-6de39228b050------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f82d0d50de</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[recycling]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-for-change]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Duncan W.]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 20:53:27 GMT</pubDate>
            <atom:updated>2021-07-23T21:14:30.612Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/data-for-change">Data for Change</a></h4><h4>An application of Convolutional Neural Networks (CNNs) to waste image-classification</h4><p>Authors: <a href="https://medium.com/u/6de39228b050">Duncan Wang</a>, <a href="https://medium.com/u/4ac115d4b44f">Arnaud Guzman-Annès</a>, <a href="https://medium.com/u/cb27d9879fcd">Sophie Courtemanche-Martel</a> &amp; <a href="https://medium.com/u/f43e9159f39">Jake Hogan</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cDITTi4lEtlfZUt1" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The recycling problem</h3><p>Reduce, Reuse, and Recycle. Otherwise known as the three Rs of waste management, this aphorism has been largely popularized as the solution for solving the rising waste crisis. In North America, rising environmental awareness amongst the general public and the spread of movements such as <a href="https://www.nytimes.com/2019/10/01/smarter-living/sustainabile-shopping-conscious-consumer.html">conscious consumerism</a> have put waste reduction at the forefront of socio-environmental concerns, and most cities have mature recycling programs today. Yet for consumers, while the principles behind “Reduce” and “Reuse” are generally quite straightforward, the processes behind the third R remain complex and poorly understood.</p><p>While recycling may seem as simple as placing specific waste items in a special bin to be shipped off to a magical plant and turned into new materials, the actual outcomes of recycling programs are often quite dismal. In fact, the <a href="https://www.gpetrium.com/waste-and-recycling-in-north-america/#:~:text=The%20United%20States&#39;%20Environmental%20Protection,Waste%20%26%20Recycling.%E2%80%9D).&amp;text=A%20decent%20contamination%20rate%20may,facility%20and%20materials%20being%20recycled.">United States Environmental Protection Agency (EPA) estimates that while 75% of American waste is recyclable, a mere 30% is actually recycled</a>. In Canada, only 9% of the 3.3 million tons of plastic waste produced is successfully recycled, while over <a href="https://www.gpetrium.com/waste-and-recycling-in-north-america/#:~:text=The%20United%20States&#39;%20Environmental%20Protection,Waste%20%26%20Recycling.%E2%80%9D).&amp;text=A%20decent%20contamination%20rate%20may,facility%20and%20materials%20being%20recycled.">75% ends up in landfills</a>. Poor recycling outcomes can be attributed to a combination of a lack of coordination between producers, consumers, and municipalities, differing regulations and capabilities governing recycling, and low public understanding. <a href="https://www.nationalobserver.com/2021/03/09/canada-drowning-plastic-waste-recycling-wont-save-us">In Canada, municipalities govern and set guidelines for what is recyclable and what is not,</a> depending on where waste is sold, what buyers are willing to process, and what waste is deemed financially justifiable to recycle. As a result, fragmented recycling systems can confuse consumers, which ultimately leads to large amounts of potentially recyclable items ending up in our landfills.</p><h3><strong>How artificial intelligence can help us recycle</strong></h3><p>Recent advances in artificial intelligence (AI) have led to a rise in AI-driven solutions to help tackle socio-environmental issues, ranging from the use of predictive forecasting to balance the supply and demand of grid-powered energy, to the use of optimization to help reduce waste from manufacturing facilities. In terms of recycling, <a href="https://www.mckinsey.com/business-functions/sustainability/our-insights/artificial-intelligence-and-the-circular-economy-ai-as-a-tool-to-accelerate-the-transition">a recent report by McKinsey &amp; Co. identified that the market opportunity for reducing waste from consumer electronics is up to $90 billion a year,</a> derived from solutions such as the use of image recognition and robotics to automate recycling infrastructure.</p><p>One particular difficulty with recycling, and an area of opportunity for AI-driven solutions, is the issue of improper sorting. Due to the variety of waste-material types and differing regulations, consumers can find it difficult to identify the composition of waste items, and therefore improperly classify an item as recyclable or non-recyclable. Such mixing of recyclable and non-recyclable goods decreases the value of and makes it difficult to sell to-be-recycled items, and increases the volume of recyclables that end up in landfills. As such, one potential AI-application is the use of image-classification to identify and help consumers recognize the material composition and consequent recyclability of their waste items.</p><h3><strong>Objective</strong></h3><p><strong>The objective of this guide is to walk through the process of how we can use </strong><a href="http://tensorflow.org/tutorials/images/cnn"><strong>Convolutional Neural Networks (CNNs</strong></a><strong>) using the </strong><a href="https://keras.io/"><strong>Keras API</strong></a><strong> in Python to identify and properly classify common waste items into their associated material groups.</strong> CNNs are a popular class of neural network architecture used in deep learning, and are commonly used to perform image classification. After being trained on images of waste items labelled by their associated material type, our goal is to enable the CNN to take an unclassified image of a waste item submitted by a user and generate a prediction representing the item’s material composition. Though simple in nature, such a tool can be used to help inform user decision-making to reduce the quantity of improperly sorted waste items, so that everyone can play a role in improving the recycling process.</p><p>The full code needed to replicate the project can be found <a href="https://github.com/hoganj15/Waste_Image_Classifier"><strong>here</strong>.</a></p><h3>Table of contents</h3><ul><li><a href="https://medium.com/p/c2f82d0d50de#0500"><strong>Introduction to CNN architecture</strong></a></li><li><a href="https://medium.com/p/c2f82d0d50de#83d7"><strong>Data preparation</strong></a></li><li><a href="https://medium.com/p/c2f82d0d50de#720a"><strong>Building the CNN model</strong></a></li><li><a href="https://medium.com/p/c2f82d0d50de#9879"><strong>Generating waste category predictions</strong></a></li><li><a href="https://medium.com/p/c2f82d0d50de#d156"><strong>Final thoughts</strong></a></li></ul><h3>A gentle introduction to CNN architecture</h3><p><a href="https://cs231n.github.io/convolutional-networks/">Convolutional Neural Networks (CNNs), or ConvNets</a>, are a type of neural network widely used in image recognition and classification tasks. The basic idea behind how a neural network does this is through mimicking how the human brain makes decisions by simulating a network of interconnected layers, each layer of which is composed of “neurons” — i.e. mathematical functions for synthesizing the input features. Neural networks are thus able to identify hidden relationships between large amounts of data that may seem invisible to the human eye.</p><p>In order to be able to detect and classify images, a CNN model will take as input a colour image which has been converted into a 3D array representing numerical pixels. It will then pass this input through a series of convolutional layers, pooling layers and fully connected layers, each of which performs a different task. The final layer of the CNN then applies a function known as softmax, which outputs a probability (0–1) that the image belongs to a specific class — in our case, the material composition of the waste item.</p><p>Without going into too much detail, the hidden layers in the CNN are generally convolution and pooling layers. In the <strong>convolution layers</strong>, a filter of a predefined size is moved across the image to perform convolution operations — element-wise matrix multiplication between the filter values and the pixels of the images. The sum of the resulting values will form a feature map, where each feature map extracts a distinct characteristic or quality of the original image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPHQJlGTD--xcIf_FlPkTw.png" /><figcaption>Steps to creating a convolutional layer. Figure by authors.</figcaption></figure><p>Then, we have the <strong>pooling layers</strong>. These are used to downsample the feature maps by reducing the parameters required to train the network and thus the number of computations required. This also helps “generalize” the inputs, which helps prevent the network from overfitting based on the training images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmT_Zq8xgnQL1f1z5GJqIw.png" /><figcaption>Steps to creating a pooling layer. Figure by authors.</figcaption></figure><p>After a series of convolutional and pooling layers, we reach the third type of layer present in the CNN architecture: the <strong>fully-connected (FC) layer</strong>, a type of layer also typically seen in regular neural networks. The FC layers form the last few layers in the network and will take the flattened output from the final pooling or convolutional layer. Using a <strong>softmax activation function</strong>, the final layer of the network will output the classification of probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_yXEdVv1aqd4jwF18Xsxg.png" /><figcaption>Flattening of the pooled feature map. Figure by authors.</figcaption></figure><p>Now that we’ve had a brief introduction to the CNN architecture, let’s jump into how we built our model, starting with the data.</p><h3>Preparing the data</h3><p>The data we will use contains 2,532 images of recyclable items made of cardboard, glass, metal, paper, plastic, as well as items that are non-recyclable (trash). The data source is available <a href="https://www.kaggle.com/asdasdasasdas/garbage-classification">here.</a></p><p>In order to feed into our model a set of images that can be digested, the first step is to transform every picture of our dataset to a 3D array of pixels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc3410527433c483df8d4e0dd3bbfb43/href">https://medium.com/media/fc3410527433c483df8d4e0dd3bbfb43/href</a></iframe><p>For our images, the shape of the resulting array is (384, 512, 3), where the the first and second elements in the array represents the pixel dimensions and the third element represents three colour channels for red, green, and blue (RGB).</p><h4><strong>Data augmentation</strong></h4><p>Next, we randomly crop and flip some images in order to augment the data through introducing some randomness. <a href="https://arxiv.org/pdf/1811.09030.pdf">Adding variability helps reduce the risk of overfitting, and therefore increases the ability of the model to identify future unseen images.</a></p><p>Here, we either artificially introduce variability by applying either a random crop or a center crop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trY-iTFXuIHbWMBFLpruDQ.png" /><figcaption>Random crop vs. center crop. Note that the random crop’s location may differ each time. Figure by authors.</figcaption></figure><p>Here is a look at how we did so. Note that each of the below cropping functions incorporates the previous code snippet for converting each image into a 3D array before cropping. We then bring the cropping functions together into a new function which randomly either applies the random crop or center crop to the images with a 50% probability of each, and also flips approximately 50% of the images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06556c12766512e781b12ed445051929/href">https://medium.com/media/06556c12766512e781b12ed445051929/href</a></iframe><p>Let’s look at how these data augmentation techniques would modify a sample image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*e9HpYWTjs9FoLmDf" /><figcaption><strong>Note:</strong> The original image and augmented image shapes differ as the original image shape is (384, 512, 3) but is sized down to (224, 224, 3) during the cropping process. The fully augmented image has both a random crop and image flip applied. Figure by authors.</figcaption></figure><p>To process the images, we pass each image through the augmentation function, and scale the resulting arrays so that the pixel values lie between -1 and 1, which is required for input to the CNN model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7699102ea3891a72338f8a1d8e8f3180/href">https://medium.com/media/7699102ea3891a72338f8a1d8e8f3180/href</a></iframe><h4>Data exploration</h4><p>To get a better understanding of the data we’re dealing with, let’s look at the distribution of waste items by category. It seems that the classes are relatively balanced with the exception of trash. For now, we’ll leave the data as is, but if we wanted to create more balanced classes, we could source additional samples or further augment the existing trash photos to produce new representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*uIpjB8UiNAm8xXvd" /><figcaption>Figure by authors.</figcaption></figure><p>Let’s also have a look at a sample of the images that we currently have in each category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Mo_KQVAaIkptSpO9TjQb4Q.png" /><figcaption>Sample of various waste images sorted by category.</figcaption></figure><h4><strong>Preparing the model inputs</strong></h4><p>To prepare the model inputs, we first factorize the six waste item material types into numerical format, since the CNN model cannot interpret a word-label category directly:</p><ul><li>0: Cardboard</li><li>1: Glass</li><li>2: Metal</li><li>3: Paper</li><li>4: Plastic</li><li>5: Trash</li></ul><p>Since the images are loaded sequentially by category, we also shuffle the data so that each dataset does not contain a vastly unequal proportion of images from a specific waste type once split.</p><p>Lastly, we split the data into three sets: train, validation, and test. The resulting split creates <strong>1750 training</strong> observations used to fit the model, <strong>518 validation</strong> observations used to provide an unbiased evaluation of the model’s fit while tuning the parameters of our model during the training phase, and <strong>259 test</strong> observations which will allow us to evaluate how our model performs once it is fully built and trained.</p><p>After preparing the model inputs, now comes time to build our model.</p><h3><strong>Building the CNN model</strong></h3><p>To build a CNN classifier, we first leverage an external pre-trained model to use as the base model of the network. This idea is known as <a href="https://www.image-net.org/download.php"><em>transfer learning</em></a>, which allows us to use layers that have already been trained on another model to help build our model, so that the waste-item classifier does not have to start learning from scratch. Since we do not have a pre-trained garbage-classifier, we use the <a href="https://www.image-net.org/"><strong>ImageNet</strong></a> model instead, which is trained on a large collection of images of various items and could be useful for identifying waste items too.</p><p>In short, transfer learning allows us to do three key things:</p><ol><li>Instantiate a base model and load pre-trained weights onto it</li><li>Freeze all layers in the base model and create a new model on top</li><li>Train the new model on our dataset.</li></ol><p>Here, we define the base ImageNet model and extract its trained weights:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23746ae00f86f25e1ed4e43f55994f1/href">https://medium.com/media/f23746ae00f86f25e1ed4e43f55994f1/href</a></iframe><p>We will initially freeze the entire convolutional base so that we only use its outputs to feed into our classifier, without re-training the ImageNet model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jN_fleNWCc6OTYeWqV47bQ.png" /><figcaption>Freezing the convolutional base model. Figure by authors.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae305860a6b85d755acf141c89dde6c/href">https://medium.com/media/cae305860a6b85d755acf141c89dde6c/href</a></iframe><p>We can now build the layers for our customized classifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6cc1f931d8eac8a8638bc7e9648aa0a/href">https://medium.com/media/d6cc1f931d8eac8a8638bc7e9648aa0a/href</a></iframe><p>Here is a quick look at our layers:</p><ol><li><strong>Pooling layer: </strong>The pooling layer is used to prepare the data as an input that will be pushed into a dense, or fully connected layer.</li><li><strong>Batch normalization layer: </strong>Implements a regularization technique which re-centers and re-scales the network to stabilize the learning process and accelerate training. This fixes the means and the variances of each layer’s input and thus can be added anywhere in the neural network to improve performance.</li><li><strong>Dropout layer: </strong>Dropout<strong> </strong>temporarily deactivates 20% of the nodes in the network at every epoch to redistribute weights and help the network focus on weak features. This can help prevent overfitting on the training dataset.</li><li><strong>Flatten Layer: </strong>The flatten layer will convert our data into a 1-dimensional array that will be the input of our fully-connected/dense layer.</li><li><strong>Prediction layer: </strong>In our final layer, the softmax activation normalizes the output of the network to a probability distribution over the 6 possible output classes.</li></ol><p>Here’s a look at the summary of our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*JvhdhuAye8WcW6Se" /></figure><p>Now, let’s compile our model. We specify sparse categorical cross-entropy, used for multi-class classification tasks, and evaluate its performance using classification accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8012687dbdb35f40794cf6186bc5d0f2/href">https://medium.com/media/8012687dbdb35f40794cf6186bc5d0f2/href</a></iframe><h4>Call-back functions</h4><p>Next, we implement a few <strong>callback</strong> functions to use when training the model. A callback is an object that can perform specific actions at a given stage of the training process, which allows us to customize the behaviour of the model.</p><p>The first callback creates a custom function which stops training if accuracy on the training data is over 0.999, to prevent overfitting. The second callback logs model statistics using the TensorBoard visualization toolkit, which we can use to track the model’s metrics during training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34c264042c79a8a4c509af24df2dcfba/href">https://medium.com/media/34c264042c79a8a4c509af24df2dcfba/href</a></iframe><h4><strong>Training the model</strong></h4><p>We first train the model for 40 epochs (or until our custom callback stop or the keras <em>EarlyStopping</em> callback is activated) with the base model layers frozen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e186003380fed5d4301e26aab13a045/href">https://medium.com/media/9e186003380fed5d4301e26aab13a045/href</a></iframe><p>After the model has converged on the new data, we can unfreeze the base ImageNet model and retrain with the unfrozen base model layers by specifying <em>base_model.trainable = True . </em>Note that this is an important step, given that if the randomly-initialized trainable layers are mixed with trainable layers from the base model that hold pre-trained features, the randomly-initialized layers will cause very large gradient updates during training, which will destroy the pre-trained features from the base model.</p><p>With the initial training done, we can now re-train the model again in the same manner, but with the un-frozen base layer.</p><p>Here’s a look at our model’s training performance with the active base layer. We can see that the model completed five training epochs before the callback function was activated, indicating that the training accuracy was over 99.9%. At the time of training completion, we can see that the classification accuracy on the validation set is: <strong>79.54%.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEY_PE-ix14089AC-0go9A.png" /></figure><p>The TensorBoard callback function also allows us to view and interact with various metrics associated with the training process. Here, we can track how accuracy increases and loss decreases at each training epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71ysZilTzqL4u5g0" /></figure><h3>Predicting waste categories</h3><p>After training the model, we can evaluate its performance with “unseen” data: our test dataset of 259 images. Here, we can generate an array containing the predicted classes (0–5) of each waste image in the test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c27de0c177670e52280b34f6f7790979/href">https://medium.com/media/c27de0c177670e52280b34f6f7790979/href</a></iframe><p>To interpret these results, we can assign each label back to its material type. We can also plot the comparisons between the predicted waste item types and the actual waste item types in the test dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*ouyQ8ZW8tDQBFdNWUvOlFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*bESwbqCIXqDKjdj9Vgc1TA.png" /><figcaption>Sample of correct vs. incorrectly classified waste items. Figure by authors.</figcaption></figure><h4><strong>Evaluating performance</strong></h4><p>We can analyze the predictions of the image classification model using a confusion matrix. This allows us to compare the predicted vs. actual material types to evaluate the number of correct vs. incorrect classifications, for each waste type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*604uG7UxIjcDP1b9wL3VTA.png" /><figcaption>Confusion matrix for predicted vs. actual classes of waste. The prediction breakdown for the trash class has been highlighted for demonstration purposes. Figure by authors.</figcaption></figure><p>We see that overall, 202 of the 259 (78%) of the images were predicted correctly. While the prediction accuracy is decent, the model’s ability to identify trash is most important to us, since we want to be sure that the classifier can separate trash from recyclable items.</p><p>If we examine <strong>trash</strong> , we have the following results:</p><ul><li>True positives (rate): <strong>4 (33.3%)</strong></li><li>True negatives (rate)<strong>:</strong> <strong>240 (96.8%)</strong></li><li>False positives (rate):<strong> 8 (3.2%)</strong></li><li>False negatives (rate): <strong>7 (63.6%)</strong></li></ul><p>For trash, the overall prediction accuracy is 94.2%, representing the total number of correctly classified trash or non-trash predictions. If we look at the false-positive rate, we see also that a very low percentage of non-trash items are mistakenly identified as trash. While accuracy is high and false-positives are low, this is mostly because the majority of items are not trash in the first place.</p><p>However, we see that the false-negative error rate is quite high, suggesting that trash items are often mistakenly classified as non-trash items. For recycling purposes, this is not ideal, since the cost of a false-negative is high. In other words, to avoid the contamination of to-be-recycled items, it is less important that non-trash items are mistakenly classified as trash and thrown out, but more critical that trash items are not mixed in with recyclable items. Since there are less trash items in our dataset overall, we would therefore recommend to further augment the dataset with additional trash images in order to improve the false-negative error rate of prediction.</p><h4>Generating new predictions</h4><p>We’ve now seen how the model performs using the existing dataset. Let’s examine how it responds to new data. In this final step, we create a new function which intakes a new image, processes it, and feeds it into the trained CNN model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a1b718c82deba4bfee5cf204bef3b2/href">https://medium.com/media/f3a1b718c82deba4bfee5cf204bef3b2/href</a></iframe><p>Here, we’ve uploaded our own photo of a somewhat-destroyed post-it note with some coloured text print. We can see below that our model correctly classifies its material as <strong>paper</strong>. Success!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xz3hW-d1qciEv5e7dsMw_A.png" /></figure><h3><strong>Final thoughts</strong></h3><p>The overall goal of this project was to examine how we can build an AI-driven model and apply it towards the current waste crisis. By exploring the intuition behind Convolutional Neural Networks (CNNs) and the steps taken to build one, we were able to successfully train a popular deep learning framework to classify images of waste items from five recyclable groups and distinguish them from non-recyclable trash items.</p><p>Though classifying common waste items can seem like a trivial task, applications of CNN such as this can be powerful when manifested at scale. Since North America produces <a href="https://www.gpetrium.com/waste-and-recycling-in-north-america/#:~:text=The%20United%20States%27%20Environmental%20Protection,Waste%20%26%20Recycling.%E2%80%9D).&amp;text=A%20decent%20contamination%20rate%20may,facility%20and%20materials%20being%20recycled">14%</a> of the world’s waste, CNN-driven algorithms could be scaled into industrial solutions for automated waste sorting, and improve the effectiveness of modern recycling systems. If designed properly, CNN driven solutions have the potential to help combat human judgment based errors, contribute to reducing overall sorting costs, and can redefine what it means to be green in the 21st century.</p><h4>Resources</h4><ul><li><a href="https://github.com/duncan-wang/Waste_Image_Classifier"><strong>Github repository</strong></a></li><li><a href="https://www.kaggle.com/asdasdasasdas/garbage-classification"><strong>Waste data</strong></a></li></ul><p><em>Please feel free to reach out to us on Linkedin if you want to share any thought</em>s!</p><h4>More about us:</h4><ul><li><a href="https://www.linkedin.com/in/james-hogan9/">James Hogan - McGill University - Desautels Faculty of Management - Greater Boston | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/sophie-courtemanche-martel/">Sophie Courtemanche-Martel - UX/UI Specialist - Consultant - Loblaw Companies Limited | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/duncan-w/">Duncan Wang - McGill University - Desautels Faculty of Management - Montreal, Quebec, Canada | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/arnaud-guzman-ann%C3%A8s/">Arnaud Guzman-Annès - Test Development Engineer - Pratt &amp; Whitney Canada | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f82d0d50de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-ai-can-help-us-recycle-c2f82d0d50de">How AI Can Help Us Recycle</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[Understanding Patient Hospital Stays: A Classification and Clustering Analysis in R]]></title>
            <link>https://medium.com/data-science/understanding-patient-hospital-stays-a-classification-and-clustering-analysis-in-r-bba200c9323?source=rss-6de39228b050------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba200c9323</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Duncan W.]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 15:25:00 GMT</pubDate>
            <atom:updated>2021-03-19T21:46:57.847Z</atom:updated>
            <content:encoded><![CDATA[<h4>An application of machine learning methods to patient hospitalization records</h4><p>Co-author: <a href="https://medium.com/u/cb27d9879fcd">Sophie Courtemanche-Martel</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ma1amFwqWe4fSjg3" /><figcaption>Photo by <a href="https://unsplash.com/@camstejim?utm_source=medium&amp;utm_medium=referral">camilo jimenez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The effective management of patient hospital stays is one of the most challenging yet paramount priorities of modern healthcare systems. It is currently estimated that managing patient admissions and stays costs the US over $377.5 billion each year [1], and long term hospital stays risk overwhelming hospitals with limited capacities and patient resources. Research demonstrates that longer term stays can increase the probability of hospital-acquired conditions and infections [2], while decreasing a patient’s length of stay (LOS) can more effectively allocate resource consumption by hospitals and decrease the social and economic burden borne by patients.</p><p>Machine learning and data mining techniques have been increasingly used to draw insights from healthcare data, which can aid public health agencies and hospitals in managing human and financial resources. As such, there is significant value in being able to apply advanced analytics techniques to patient hospital records — such as using patient data to predict the length of a hospital stay, or to better understand the utilization of hospital resources by different patient groups.</p><h3><strong>Objective</strong></h3><p>The <a href="https://mimic.physionet.org/gettingstarted/access/">Medical Information Mart for Intensive Care (MIMIC)</a> database is one source of patient data which provides a comprehensive stream of patient hospitalization records that have proven useful in past descriptive, predictive, and hypothesis-driven studies. Developed by the Massachusetts Institute of Technology Computational Physiology lab, the database contains anonymized entries for roughly 60,000 intensive care unit admissions at the Beth Israel Deaconess Medical Center, a teaching hospital of Harvard University located in Boston, Massachusetts.</p><p>For this analysis, we used data extracted from the MIMIC database to build two models in order to generate both predictive and exploratory insights regarding patient hospital stays. We first built a machine learning classification model to predict the categorical length of a patient’s hospital stay, given a patient’s observable characteristics at time of admission. Then, we used unsupervised learning techniques to cluster patients based on the number of various patient-caretaker interactions — such as procedures, inputs taken, and drugs prescribed — which can quantify the amount of human or physical resources used by a patient during their stay.</p><blockquote><strong>By combining these models, our aim is to explore both characteristics inherent to a patient’s background and condition upon admission, and attributes associated with a patient’s treatment process and resource consumption. These indicators can be used to benchmark and increase the effectiveness of medical service provision, enable the proactive allocation of critical healthcare resources, and potentially reduce the length of unnecessary stays.</strong></blockquote><h3>Contents</h3><ul><li><a href="https://medium.com/p/bba200c9323#db16"><strong>Data Description</strong></a></li><li><a href="https://medium.com/p/bba200c9323#a2b5"><strong>Model Building</strong></a></li><li><a href="https://medium.com/p/bba200c9323#0854"><strong>Classification of patients by length of hospital stay</strong></a></li><li><a href="https://medium.com/p/bba200c9323#dd13"><strong>Clustering of patients by patient-caretaker interactions</strong></a></li><li><a href="https://medium.com/p/bba200c9323#762e"><strong>Limitations</strong></a></li><li><a href="https://medium.com/p/bba200c9323#d811"><strong>Final Thoughts</strong></a></li></ul><p>Note that the models were built in R, and you can reference the full code <a href="https://github.com/duncan-wang/LOS-prediction"><strong>here</strong></a>.</p><h3>Data Description</h3><p>The MIMIC III database contains more than 50,000 stays for adult patients and 8,000 neonatal patients recorded between June 2001 and October 2012.</p><p>For the purposes of the analysis, we utilized a <a href="https://www.kaggle.com/drscarlat/mimic3d">subset of attributes </a>from the MIMIC III database compiled by physician Dr. Alexander Scarlat. This dataset contains information on patient demographics, admission details, patient condition, as well as information on the average daily number of various patient-caretaker interactions. In addition, the data includes the total length of a patient stay and whether or not the patient passed away during their stay.</p><p>Here’s a subset of the attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWovDk0ZKP_KwZ477Jz9lA.png" /></figure><h4><strong>Taking a Look at the Data</strong></h4><p>Even though the pre-prepared dataset extracted from the MIMIC III database was relatively clean, we still found that it was necessary to perform further preprocessing to facilitate the analysis. Class variations of the same category — such as “GI” vs. “Gastrointestinal”, were regrouped into the same class, and several high-cardinality categorical variables were reclassified to reduce the number of classes. Our key variable of interest — patient Length of Stay (LOS) — ranged from 0–294 days. To categorize the target for the classification task, we re-grouped LOS into three classes with a comparable number of observations in each class:</p><ul><li>Short stays: 0–5 days</li><li>Medium stays: 6–10 days</li><li>Long stays: greater than 10 days</li></ul><p>By looking at the various patient attributes, we see below that older patients more frequently experienced medium to long stays, whereas younger patients had the shortest hospital stays. While there is considerable variation across patients, it also seems that white patients tend to be older overall when compared to all other ethnicities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtQ7weGzMK40Cyv7DQQSsg.png" /><figcaption>Patient length of stay (LOS) by age, across various patient ethnicities. Figure by authors.</figcaption></figure><p>We also see that most patients were covered by either Medicare or private insurance, and the majority of patients were white. The most common admission diagnosis was for childbirth, which might explain the high number of emergency admissions but low mortality rates observed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8vXZlOnPSwkRD7wWyQpSA.png" /><figcaption>Distributions of various patient characteristics. Figure by authors.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20y0P5_8NOUMPk29Dl4aJQ.png" /><figcaption>Frequency of patient admissions by admission diagnosis. Figure by authors.</figcaption></figure><h3>Model Building</h3><h4>Classification Model</h4><p>After data preparation, our first task was to predict the length of a patient’s hospital stay — as either short (0–5 days), medium (6–10 days), or long term (more than 10 days).</p><p><strong>Feature selection</strong></p><p>After eliminating invalid predictors (i.e. variables that can only be observed once the patient is admitted to the hospital), we were left with only categorical variables with the exception of age. To perform feature selection, we conducted Chi-Squared tests of independence, which is a hypothesis test used to establish the presence of a significant relationship between two categorical variables. Then, for the features identified as significantly related to LOS, we used Bonferroni-adjusted post-hoc tests to perform pairwise comparisons and identify which specific categories of each significant predictor were significantly related to LOS. This left us with the following variables, which were dummified prior to classification:</p><p>After eliminating invalid predictors (i.e. variables that can only be observed once the patient is admitted to the hospital), we were left with only categorical variables with the exception of age. To perform feature selection, we conducted Chi-Squared tests of independence, which is a hypothesis test used to establish the presence of a significant relationship between two categorical variables. Then, for the features identified as significantly related to LOS, we used Bonferroni-adjusted post-hoc tests to perform pairwise comparisons and identify which specific categories of each significant predictor were significantly related to LOS. This left us with the following variables, which were dummified prior to classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6WUTbS5DyFnzYSp_c51YQ.png" /><figcaption>List of features and classes selected for classification.</figcaption></figure><p><strong>Model Training</strong></p><p>To predict the length of a patient’s stay, we decided to explore the following 3 different classification models and compare their relative performances:</p><ul><li>Multinomial Logistic Regression (MLR)</li><li>Random Forest (RF)</li><li>Gradient Boosting Machine (GBM)</li></ul><p>In simple terms, the models we tested generate a LOS prediction by calculating the probability that a patient record belongs to each LOS class (short/medium/long), and assigns a LOS class to the patient based on the highest predicted probability.</p><p>MLR does this by using maximum likelihood estimation to define a likelihood function for calculating the conditional probability of observing a given outcome under an assumed probability distribution. It then “searches” for the optimal coefficients of the function that achieves the maximum likelihood of that function. On the other hand, RF and GBM are ensemble learning methods that construct a number of decision trees and output the LOS class corresponding to the average prediction of each individual tree. The key difference between RF and GBM is that RF constructs several full trees in parallel, resulting in fully grown trees with low individual bias (error) but potentially high prediction variance between trees, while GBM grows several small trees sequentially. Each of these small trees produced by GBM has a high bias, but learns from and corrects for the error produced by the previous tree, therefore reducing the overall variance between predictions.</p><h4><strong>K-Means Clustering Model</strong></h4><p>To complement the classification task, we also decided to explore unsupervised methods by clustering patients by the average daily number of various patient-caretaker interactions, as a measure of the quantity of human or physical resources utilized on patients during their stay. To simplify the process, we targeted a priority group of 1349 “emergency” patient admissions under the following five most common admission diagnoses: gastrointestinal bleed, coronary artery disease, pneumonia, sepsis, and congestive heart failure.</p><p>We subsequently selected eight quantitative variables to cluster patients by, which are measured on an average daily scale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw7bbnSVY4L9ao5wTwWYpg.png" /><figcaption>Selected features for K-Means clustering model.</figcaption></figure><p>Due to different ranges of each variable, we first scaled the variables using min-max normalization before applying the K-Means clustering method. After assigning each patient to a cluster, Principal Component Analysis was applied to the dataset to perform dimension reduction in order to visualize the clusters by the top two principal components.</p><h3>Classification of patients by length of hospital stay</h3><p>From our classification models, we can see that the Gradient Boosting Machine marginally outperformed the other two models tested. Since GBM uses an ensemble approach to grow classification trees sequentially, with each tree using knowledge gained from previous trees to improve aggregate performance, it generally performs more optimally than simple logistic regression or random forest. However, we still see here that the overall performance of the models is poor; in fact, we weren’t able to obtain an accuracy much higher than that of a random guess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIyc0g9KpoP88EWsjNkbDg.png" /><figcaption>Accuracy of models used to predict patient Length of Stay (LOS).</figcaption></figure><p>These results suggest that it is difficult to predict the length of a hospital stay based on patient characteristics, diagnosis, and admission circumstances alone. This is unsurprising, given that the length of a hospital stay may be determined by many factors exogenous to the patient, such as the availability of physicians, specialized equipment, and the effectiveness of managing patient cases, or if the treatment of an initial condition leads to the discovery of additional conditions requiring treatment.</p><p>We also generated confusion matrices to further break down our results and examine the precision and recall of the models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*051sHFEkhlnDqEZmEperoQ.png" /></figure><p>As a quick refresher: Recall is a measure of the classifiers’ completeness; the ability of the model to correctly identify a short, medium, or long stay over all true existing observations of that class, while Precision counts the number of correctly identified observations in each LOS class over the total number of observations predicted as as a short, medium, or long term stays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGeuS3h11E-bLiOrzuVJIg.png" /><figcaption>Confusion matrix comparisons of MLR, RF, and GBM models.</figcaption></figure><p>The confusion matrices reveal that all models performed best at identifying short stays. However, it appears that this may be due to the tendency of the models to overwhelmingly predict short stays over any other class, as the models were much less likely to identify medium and long term stays when they did occur. Under this model, hospitals would most likely underestimate the duration of patient stays, which could lead to an inadequate preparation of beds, staff, and resources to handle realized capacity needs. Given the high-consequential risk of misinformation in the context of healthcare resource allocation, we can infer that hospitals wouldn’t have enough information to make any LOS related decisions based on a patient’s admission characteristics alone.</p><h3><strong>Clustering of patients by patient-caretaker interactions</strong></h3><p>Next, let’s look at the results from the clustering model. With three clusters, we found that the total sum of squares variation — calculated as the variation between clusters relative to the total variation — was 64.5%, representing a total measure of variance in the patients which can be explained by the three clusters. The plot of clusters by the top two principal components reveals that cluster 3 represents the vast majority of patients, who experienced comparably lower average daily numbers of patient-caretaker interactions and with a relatively low degree of variation. Patients assigned to cluster 2 show a higher variation in patient-caretaker interactions, while cluster 1 represents patients with the highest overall number of and variation in patient-caretaker interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Cb1pXN47E5dx6DQP9Z8_w.png" /><figcaption>Results of the K-Means clustering of patients by patient-caretaker interactions, plotted by the first two principal components. Figure by authors.</figcaption></figure><p>Now, let’s break down each cluster by looking at the relative frequency of patient characteristics within each cluster, Here, we see that patients in <strong>cluster 1</strong> were most likely to have been diagnosed with sepsis, had the shortest stays, and most frequently died. This observation is logical, given that sepsis is classified as a medical emergency which can rapidly progress to septic shock, triggering tissue damage, organ failure, and is oftentimes fatal [3]. Although we aren’t able to assume causality, it is possible that the high variation in patient-caretaker interactions in this cluster could be driven by the dominance of high-fatality conditions whereby a patient either died before treatment, or died while being treated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gppRTqaTR3KD5R9UHZJL7w.png" /><figcaption>Relative frequency of patient traits clustered by patient-caretaker interactions. Figure by authors.</figcaption></figure><p>We found that the majority of patients in the <strong>clusters 2 and 3</strong> had a much smaller and less variable number of patient-caretaker interactions, and longer lengths of stay. Compared to cluster 1, it could be that the number of interactions may be initially high immediately following admission, but eventually plateaus once the patient is stabilized. Patients in these groups were also less-likely to die, and were more likely to be diagnosed with conditions such as gastrointestinal bleed, coronary artery disease, and congestive heart failure. These conditions have varying levels of severity, but are less likely to be immediately life-threatening.</p><p>Overall, we were able to identify a few key traits associated with the number of patient- caretaker interactions, which mainly concerned a patient’s condition rather than their demographic traits. The distribution of clusters suggests that there are few patients which may require more resources on an average daily basis, but that the majority of patients utilized a similar amount of resources. However, the overlap in clusters nonetheless suggests that patient-caretaker interactions may be influenced by factors outside of the scope of this analysis — such as patient history and condition severity — and varies widely on a case-by-case basis.</p><h3><strong>Limitations</strong></h3><h4><strong>Model interpretation and patient cost quantification</strong></h4><p>Applying predictive analytics to the healthcare setting can be quite challenging, given that the modeling of patient outcomes must take into consideration both the generalizability of models as well as the substantial variation in treatment costs and outcomes even amongst similar patient groups. Patients are admitted with conditions requiring varying treatment procedures, and into different units with varying capacities and resources. Since the current data was also collected over an 11 year period, restructuring of hospital programs, units, and divisions may have also occurred over time. Therefore, to quantify the cost of a patient’s LOS, it may be useful to segment patients by diagnosis, admission location, as well as time period.</p><p>While we tried to group patients by patient-caretaker interactions to measure patient resource consumption, it is also important to keep in mind that an interaction such as taking a patient’s vitals is considerably less costly than performing a surgical procedure, making it difficult to quantify the dollar-cost of each patient group based on these results alone.</p><h4><strong>Sample bias</strong></h4><p>It is important to recognize that the data used for the analysis consists of admissions to one hospital only. These patients were also predominantly white, covered by private insurance or Medicare (federal health coverage for patients 65 years and older), and had a median age of 59 years old. Interestingly, we found that 70% of patients were classified as emergency room admissions, and over 10% of admitted patients ultimately died, compared to the US average of 0.77–1.48 deaths per 1,000 emergency room admissions [4]. Since the patient profile of the MIMIC III dataset is not a representative sample of the demographic composition of US patients, care needs to be taken not to extrapolate the results to the wider US population.</p><h4><strong>Feature validity</strong></h4><p>One of the major limitations of our classification model is the lack of comprehensive and quantitative measures. In fact, we were only able to use six categorical predictors (admission type, location and diagnosis, religion, marital status, ethnicity), one binary predictor (gender) and only one continuous predictor (age). Including other critical metrics recorded upon the time of admission — such as Body Mass Index (BMI), heart rate, temperature, nervous reflexes, as well as general indicators such as pain levels and pre-existing medical conditions — would potentially improve the predictive power of the classification models.</p><h3><strong>Final Thoughts</strong></h3><p>One of the central aims of this analysis was to use machine learning models to better understand the underlying patterns of patient hospitalizations and subsequent Length of Stay (LOS). While the results of the models demonstrated that it might be difficult to predict a patient’s LOS based on admission characteristics alone, we were able to cluster patients by patient-caretaker interactions to successfully identify three groups of patients on the basis of hospital resource utilization, and understand what characteristics, diagnoses, and patterns of mortality this was associated with.</p><p>Healthcare analytics shows great potential for contributing to advances in healthcare resources management, prognostic and diagnostic analysis, and even for the early detection of disease and disability. Yet, in order to operationalize predictive models for such tasks, data collection, algorithm tuning, and model interpretation must be undertaken in a manner which ultimately furthers the interest of the individuals, communities, and populations they are designed to serve. These models can have large benefits, but must be approached with care when human lives are on the line.</p><h4>Project Code:</h4><p>Github: <a href="https://github.com/duncan-wang/LOS-prediction">https://github.com/duncan-wang/LOS-prediction</a></p><h4>References:</h4><p>[1] Health Catalyst (2016), “<a href="https://www.healthcatalyst.com/success_stories/reducing-length-of-stay-in-hospital">Patient-centered los reduction initiative improves outcomes, saves costs</a>”.</p><p>[2] Hassan M., David K. (2006), “<a href="https://www.researchgate.net/publication/235314589_Hospital_Length_of_Stay_and_Probability_of_Acquiring_Infection">Hospital length of stay and probability of acquiring infection</a>,” <em>International Journal of Pharmaceutical and Healthcare Marketing</em>, vol. 4, no. 4, pp. 324–338.</p><p>[3] Center for Health and Diseases (CDC) (2020), “<a href="https://www.cdc.gov/sepsis/what-is-sepsis.html#:~:text=Sepsis%20is%20the%20body&#39;s%20extreme,%2C%20organ%20failure%2C%20and%20death.">What is sepsis?</a>”.</p><p>[4] Shmerling, R. (2018), “<a href="https://www.health.harvard.edu/blog/where-people-die-2018103115278">Where people die</a>.” <em>Harvard Health Blog.</em></p><h4>MIMIC III Database:</h4><p>MIMIC-III, a freely accessible critical care database. Johnson AEW, Pollard TJ, Shen L, Lehman LH, Feng M, Ghassemi M, Moody B, Szolovits P, Celi LA, and Mark RG. Scientific Data (2016). DOI: 10.1038/sdata.2016.35. Available at: <a href="http://www.nature.com/articles/sdata201635">http://www.nature.com/articles/sdata201635</a></p><p><em>Please feel free to reach out to us on LinkedIn if you want to share any thought</em>s!</p><ul><li><a href="https://www.linkedin.com/in/duncan-w/">Duncan Wang - McGill University - Desautels Faculty of Management - Montreal, Quebec, Canada | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/sophie-courtemanche-martel/?originalSubdomain=ca">Sophie Courtemanche-Martel - UX/UI Specialist - Consultant - Loblaw Companies Limited | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba200c9323" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-patient-hospital-stays-a-classification-and-clustering-analysis-in-r-bba200c9323">Understanding Patient Hospital Stays: A Classification and Clustering Analysis in R</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[A Mixed-Integer Optimization Approach to Rebalancing a Bike-Sharing System]]></title>
            <link>https://medium.com/data-science/a-mixed-integer-optimization-approach-to-rebalancing-a-bike-sharing-system-48d5ad0898bd?source=rss-6de39228b050------2</link>
            <guid isPermaLink="false">https://medium.com/p/48d5ad0898bd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Duncan W.]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 14:29:10 GMT</pubDate>
            <atom:updated>2021-02-15T16:49:19.498Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>An application of the traveling salesman problem to BIXI Montreal</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YAFjQQ_VilvsGdsI9ERWWQ.jpeg" /><figcaption>Photo by JsTremblay on <a href="https://commons.wikimedia.org/wiki/File:Station_de_v%C3%A9los_Bixi_-_Ville_de_Qu%C3%A9bec.jpg">Wikimedia Commons</a></figcaption></figure><blockquote>The year is 2022. Canada’s population is fully vaccinated, the parks of Montreal are filled to the brim with life on a hot July afternoon, and BIXI riders fill the streets, zipping between coffee shops in the Old Port and circling along the Lachine Canal. Life is good once again.</blockquote><p>Derived from the words “BI-cycle” and “taXI”, <a href="https://bixi.com/">BIXI</a> is a non-for-profit, Montreal-based public bike-sharing system with a network of over 8000 bikes dispersed across 600+ stations on the island. Available from April to November of each year, BIXI fills an important niche in Montreal’s public transportation system, both by connecting users between the gaps in the bus and metro systems, and by providing a healthy, fun, and environmentally friendly alternative to vehicle-based transit for short-duration trips. A customer can simply pick up a bike from one station, rent it for a certain period of time and cost, and subsequently return to another station in the network. However, since BIXI’s cost scheme is designed for short-term trips, the dynamic nature of the system may create situations where bike shortages occur in locations with high demand, while bike surpluses accumulate in locations with low demand.</p><p>The ability to strategically reallocate bikes is a key customer service determinant for BIXI. In order to reduce potential imbalances within the bike-share system, operators of BIXI known as “drivers” are required to redistribute bicycles from one station to another using trucks, in order to rebalance the system when necessary. As such, there is a significant value in examining how BIXI can meet the fluctuating demands of customers through rebalancing bikes to alleviate shortages and surpluses. Doing so can ensure that BIXI can continue to attract more riders, while minimizing inefficiencies due to imbalances in the system.</p><h3><strong>Designing a bike rebalancing strategy</strong></h3><p><strong>For this project, we aimed to use mixed-integer optimization to generate a bike rebalancing strategy which meets the fluctuating demands of BIXI customers, while minimizing estimated costs incurred from running the distribution system.</strong></p><p>In short, an optimization problem involves selecting the optimal options, known as <em>decision variables, </em>from a series of available alternatives, where the best option is that which maximizes or minimizes an <em>objective function </em>while satisfying a series of criteria known as <em>constraints</em>. Optimization is a fundamental branch of operations modelling, and has a wide range of practical applications, from scheduling hospital personnel to helping Amazon design the best routes for package delivery. To create the best BIXI rebalancing strategy, our <em>decisions</em> are to find the optimal schedule and number of bikes to rebalance which will minimize the <em>objective function </em>which is BIXI’s operational costs. To do so, we will also need to satisfy various <em>constraints</em> imposed by the system<em>, </em>such as the number of bikes a truck can carry at one time.</p><p>For model building, we used <a href="https://www.gurobi.com/">Gurobi Optimization Solver</a>, a programming tool for solving linear, quadratic, and mixed-integer optimization problems. Gurobi supports a variety of programming languages, and our models were coded in Python. Feel free to check out <a href="http://link/">Github</a> to see the code.</p><h3><strong>Data and Scope</strong></h3><p>BIXI provides <a href="https://bixi.com/en/page-27">publicly available records</a> for all stations and rides taken from the years 2014–2019. This includes the geographic coordinate locations of each station, as well as records of all trips taken by users, such as the trip date, duration, and which stations a bike was picked up and dropped off at. We found that due to the large expansion of BIXI’s operations since inception, ridership and station configuration vary widely between each year. Therefore, we took the most recent data available, from 2019, to base our model off of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mao7cwytmHKRTEiY77cHdg.png" /><figcaption>Sample of BIXI station names with coordinate locations — each station is identified by a unique code.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Riui6nCYGWV3yV7tKSKiEg.png" /><figcaption>Sample of BIXI ridership history from May, 2019</figcaption></figure><p>The BIXI system includes 611 stations in the Greater Montreal area; however, the majority of these stations are located in and around the downtown area. To save on computation time as well as to achieve a realistic possible route, 18 stations covering 13.65 km² within the borough of Verdun were chosen as the region of interest. Each of these stations also has a varying number of bike docks. Since this information wasn’t available to us, we randomly generated dock capacities within an estimated range of 10–25 bikes per dock. To complete the rebalancing activities for the borough of Verdun, we assumed that one truck with a capacity of 40 bikes would be assigned to pick up bikes from stations with surplus and transport them to stations with shortage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M86eFbxSReI2ydir9GWaKA.png" /><figcaption>18 BIXI stations in the borough of Verdun, Montreal, used as the area of interest.</figcaption></figure><h3>Model Formulation:</h3><p>The basic optimization model was built by quantifying the operational costs of the rebalancing system and subtracting these costs from the estimated revenue from ridership in order to minimize organizational costs, subject to routing and rebalancing constraints. We built our model based on the intuition behind the classic <strong>Traveling Salesman Problem (TSP)</strong>, an optimization problem whereby a “salesman” must visit a list of designated locations exactly once, while taking the shortest possible route and returning to the starting location.</p><h4><strong>Parameters</strong></h4><p>We first defined the following parameters to incorporate into our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJI3Lp7_BduU8ER0Rb7Xwg.png" /></figure><h4><strong>Decision Variables</strong></h4><p>Next, we defined our decision variables. These variables define the choices the truck driver must make, specifically whether the driver will visit a station or not, and how many bikes they will pick up or drop off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0D6LLa-uqi5c0nHMmSgAQ.png" /></figure><h4><strong>Objective Function</strong></h4><p>Our overarching objective here is to minimize the total operational costs, which is composed of estimated bike disinfecting costs per bike (<em>h</em>), gas costs per kilometre (<em>g</em>) and a fixed hourly wage for the truck driver (<em>w</em>). Here, <em>B</em> stands for the number of bikes that are relocated, while <em>D</em> represents the total distance that the truck has traveled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAL1XOkCDzOMd43AYs2iAw.png" /></figure><h4><strong>Constraints</strong></h4><p>Lastly, we constructed two groups of constraints — one regarding the route taken and one regarding bikes rebalanced — to replicate various real-life requirements that must be satisfied. From a routing perspective, we adapted the constraints of the Traveling Salesman Problem to ensure that the truck was not required to visit every station when rebalancing was not required, since for BIXI, the truck only needs to visit stations when the number of bikes is lower or higher than a predetermined threshold that we defined.</p><p>For the rebalancing constraints, we needed to ensure that the truck rebalances each station back to its ideal level and that it does not carry more bikes than its capacity.</p><p>For an in depth description of how we formulated the problem, please visit our <a href="https://github.com/duncan-wang/BIXI-optimization/blob/main/MGSC662_Team_Project_Report.pdf">Github.</a></p><h4>Estimating costs of rebalancing</h4><p>To ensure that BIXI can maintain sufficient funds to carry out this rebalancing process, we also estimated costs and revenues arising from its operations. We estimated the following costs of rebalancing as follows:</p><ul><li><a href="https://ca.indeed.com/Truck-Driver-jobs-in-Quebec-Province">Wage for truck driver</a>: $20.52/hour</li><li><a href="https://bixi.com/en/info-covid-19">COVID-19 bike disinfecting cost</a>: $0.875/relocated bike</li><li><a href="https://www150.statcan.gc.ca/t1/tbl1/en/tv.action?pid=1810000101">Fuel cost</a>: $1.256 /L</li><li>Estimated fuel efficiency: 4.25 km/L</li><li>Price of travel (fuel cost * efficiency): $0.294/km</li></ul><h4>Estimating revenue from ridership</h4><p>Total revenue from ridership on a daily and weekly basis for the area of interest was estimated by multiplying the cost per trip by the number of member vs. non-member trips. While BIXI offers additional discounts and packages, the data does not differentiate between these trips, and so all trips were ultimately grouped under the following cost schemes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJCGRiwlXMqxai0K6EST7w.png" /><figcaption>Cost scheme for member vs. non member trips. Note that after a certain period of time, there is a $3 fee for every additional 15 minutes.</figcaption></figure><h4>Putting it all together!</h4><p>The model formulation was done using Gurobi 9.1 and Python 3.7. In all, we defined four main decision variables pertaining to (1) whether the truck would travel between stations, (2) how many bikes it was carrying before arriving at a station, (3) the number of bikes it was dropping off, and (4) the number of bikes it was picking up. The model subsequently selects the best decisions such that the costs associated with rebalancing are minimized, while ensuring that routing and rebalancing constraints remain satisfied.</p><h3>Results</h3><p>Once the model was built, we were able to simulate and evaluate its performance at any given time by feeding the ridership data (bike pick-ups and drop-offs at each station) into the model. The model was evaluated repeatedly on an hourly basis, whereby the flow of bikes was updated at the start of each hour and the rebalancing route and decisions was subsequently generated for that hour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS2GCVEyKSoudxIyre3k4Q.jpeg" /><figcaption>Results of simulated bike rebalancing operations for Verdun BIXI stations from 8:00–9:00AM on July 8th, 2019.</figcaption></figure><p>To give a glimpse into what the rebalancing system would look like on an hourly basis, we created a map showcasing the movements of the truck from 8:00–9:00 on July 8th. We see that during this hour, a total of 5 stations needed to be rebalanced. When the truck arrives at Station (1), we assumed it was carrying 20 bikes (half the total capacity). Then, at station 2, the truck it picks up two bikes, meaning the station must have been over the upper ideal capacity limit before this point. Arriving at station 3, the truck is now carrying 22 bikes, and subsequently drops off one bike, meaning that station 3 was under its lower ideal capacity limit. At station 4, the truck is now carrying 21 bikes, and drops off two bikes, and at station 5, it is carrying 19 bikes and drops off one. The truck then returns to station 1, and the rebalancing task for that hour is complete. We can see from the chart below that during this hour, a total of <strong>5.56 km</strong> is traveled,<strong> 6 bikes</strong> are rebalanced, and the cost comes out to <strong>$27.40</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTL-wKbmoFV7Ya1aMHMk4w.png" /><figcaption>Hour-by-hour results of truck rebalancing schedule for July 8th, 2019</figcaption></figure><p>To track the rebalancing progress, we calculated the net difference at the beginning of each hour from 8:00 to 20:00, as these were observed as the most active times for BIXI pick-ups and drop-offs. If we run the model for the entire day, we find that the most costly hour is from 16:00–17:00, where 10 bikes had to be redistributed. The middle of the day, 12:00–13:00, was the second most costly; however, this seemed to relate more to the larger distance traveled rather than the number of bikes redistributed. Logically speaking, these busier times make sense for the time period chosen, as from16:00–17:00, customers would be using the service to travel home from work, while from 12:00–13:00, customers could be using the service during their lunch break.</p><h3><strong>COVID-19 Extension: Prioritizing Bike-Access for Essential Workers</strong></h3><p>With the recent COVID-19 pandemic, businesses have had to drastically evolve their business models to adapt to changing conditions and newly arising customer demands. Bike-share systems are no exception. At the onset of the pandemic, BIXI experienced an increase in ridership amongst essential health care workers, and to meet these needs, BIXI began offering free 30-day memberships to essential workers.</p><p>Based on this information, we explored an extension to the original model by prioritizing the availability of bikes near hospitals to ensure access to healthcare workers. To do so, we modified the original optimization problem to include a required sub-tour for hospitals within a new sub-region of the system. Essentially, the truck would be required to visit all stations near hospitals sequentially to ensure the demands of hospital workers were met first, before moving on to the rest of the stations in the region. For the extension, we chose a sub-region within Montreal’s downtown core, which covers of 57 stations and an area of 6.07 km², and includes the Montreal Neurological Hospital (Neuro) on the West end, and the Centre Hospitalier de l’Universite de Montreal (CHUM) on the East end. Three stations around the CHUM and seven stations around the Neuro were chosen to be the predefined sub-tours, and the starting station was also set to be one of the priority stations near the CHUM hospital.</p><p><a href="https://www.mdpi.com/2076-3417/10/10/3502">While a recent study</a> proposed a similar idea in a more complex setting, we achieved a routing solution with priority by adding the following two constraints, where , ℙ denotes a set of priority stations and ℝ denotes a set of regular stations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUJFvgqDNaUyYuIIl7NuCQ.png" /></figure><p>Constraint (3.1) ensures that the truck first visits a priority station after leaving the starting priority station, and constraint (3.2) guarantees that visits from a priority station to a regular station happen no more than once. This action occurs only when all priority stations have been serviced and there are subsequent regular stations to be serviced afterwards. Note that when all stations that needed rebalancing are priority stations, constraint (3.2) is non-binding.</p><p>The two maps below show how the route changed with the addition of the priority constraints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOY1t1fYLFLe5xdcCZDv4w.jpeg" /><figcaption>Route without (left) and with (right) the addition of constraints for priority visitation of stations near hospitals.</figcaption></figure><p>By adding this set of constraints, we observe that the truck is still able to satisfy the hourly rebalancing demands, but that as expected, the order of visitation is shifted so that each selected hospital station is visited first. For instance, by running one iteration of rebalancing from 12:00- 13:00 on July 8th, 2019, it is observed that the distance increases from <strong>6.97 km </strong>to <strong>7.62 km</strong>, representing an associated cost increase from <strong>$33.94</strong> to <strong>$40.14</strong>. It’s interesting to note that the computational complexity also increases significantly; while the base model was solved in under 1 second, solving for an equal time period of one hour with priority constraints took 36.84 seconds. Given that there are over 10 major health networks in Montreal and many with several branches, such potential increases in hourly rebalancing costs and computational intensity is not trivial when considering whether or not to undertake such operations.</p><h3>Final Thoughts</h3><p>The goal of this project was to take advantage of BIXI’s open access dataset on historical ridership to simulate how the continuous rebalancing of bikes is necessary to keep the system running smoothly and satisfy demand for bikes, all while meeting BIXI’s bottom line.</p><p>In reality, BIXI’s bike rebalancing system is likely to be quite a bit more complicated, such that thresholds for bike rebalancing requirements may be generated through algorithms that take into account factors such as weather, population density, time of the day, and traffic. The assumption we made to choose fixed thresholds for rebalancing evidently don’t capture the entire set of potential variables which may influence rebalancing decisions. In addition, while we created fixed boundary regions within which the truck would operate exclusively, BIXI normally deploys multiple trucks which travel flexibly across the island, making it easier to handle fluctuating demand. We also made significant simplifications in estimating costs and expenses, since BIXI also incurs marketing, management, and data collection expenses. Therefore, our model cannot be interpreted in terms of the success of the business as a whole, rather only in terms of the effectiveness of the simulated rebalancing process.</p><p>Overall, our analysis aimed to take a deep dive into Montreal’s BIXI bike sharing operations by using mixed integer programming techniques to optimize the rebalancing of bikes in a way which meets anticipated demands, alleviates surpluses and shortages in the system, and remains cost efficient. While we focused on a few select regions and time periods, the models created are scalable and can be extended to other boroughs or time periods. By providing key insights into the requirements of maintaining such a dynamic system, we ultimately sought to demonstrate the opportunities which exist to further enhance the value of friendly and efficient transportation shared transportation systems on the island of Montreal.</p><p><em>Please feel free to reach out to us on Linkedin if you want to share any thought</em>s!</p><h4><strong>Additional resources:</strong></h4><ul><li><a href="https://bixi.com/en/page-27">BIXI Open Source Data</a></li><li><a href="https://github.com/duncan-wang/BIXI-optimization">Github Repository</a></li></ul><h4>More about us:</h4><ul><li><a href="https://www.linkedin.com/in/duncan-w/">Duncan Wang - McGill University - Desautels Faculty of Management - Montreal, Quebec, Canada | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/hannaswail/">Hanna Swail - Machine Learning Solutions Intern - Stradigi AI | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/beiqizhou/">Beiqi (Becky) Zhou - McGill University - Desautels Faculty of Management - Canada | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/tzhang96/">Tiancheng Zhang, IWS - Product Manager and Data Scientist Consultant - Rogers Communications | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48d5ad0898bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-mixed-integer-optimization-approach-to-rebalancing-a-bike-sharing-system-48d5ad0898bd">A Mixed-Integer Optimization Approach to Rebalancing a Bike-Sharing System</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[Drag Race Analytics with Plotly and Dash]]></title>
            <link>https://medium.com/data-science/drag-race-analytics-using-plotly-and-dash-838f7d71b3e1?source=rss-6de39228b050------2</link>
            <guid isPermaLink="false">https://medium.com/p/838f7d71b3e1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[rupauls-drag-race]]></category>
            <dc:creator><![CDATA[Duncan W.]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 01:00:48 GMT</pubDate>
            <atom:updated>2021-01-06T04:13:54.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating an interactive dashboard to compare RuPaul’s Drag Race contestants.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2qCsXnEpi-Y6aePB" /><figcaption>Photo by <a href="https://unsplash.com/@wesson?utm_source=medium&amp;utm_medium=referral">Wesson Wang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Like many, the onset of the pandemic has given me the opportunity to explore new interests and to revisit old ones. I wrapped up my undergrad and started a master’s degree in business analytics, got back into running, and had the time to brush up on my coding skills. Arguably more importantly, is that I <em>finally</em> got the chance to binge-watch <strong>RuPaul’s Drag Race.</strong></p><p>Without getting into too many details, RuPaul’s Drag Race is a competition-style reality series where each season features a dozen or so drag queens who compete in acting, dancing, and runway challenges with the hopes of being crowned America’s next drag superstar. At the end of every episode, two of the bottom queens lip-sync for their lives, and one queen is (<a href="https://rupaulsdragrace.fandom.com/wiki/Category:Double_Sashay">usually</a>) saved by RuPaul while the other is asked to “<em>sashay away</em>”.</p><p>I’ve never been a big fan of reality television, so the whole concept of Drag Race initially seemed a bit frivolous to me. But after the first episode, I must admit that the hilarious feuds, meme-worthy moments, and boundary-pushing fashion statements have all served as a much welcomed escape from reality in this time of social and political uncertainty.</p><p>Aside from the drama of it all, I’ve also grown to appreciate how the show has managed to take an underrepresented and often misunderstood niche of queer culture, and not just break into, but achieve significant recognition within the world of mainstream entertainment. Since its inception in 2009, RuPaul’s Drag Race has spawned 13 seasons, several spinoffs, and featured over 150 contestants. Many Drag Race alumni have moved on to build substantial careers since competing on the show, and have played significant roles in increasing queer visibility and representation in the arts, fashion, and popular culture. All the more reason to love Drag Race!</p><p><em>Season 7 winner Violet Chachki and season 10 winner Aquaria for instance, were amongst the first drag queens to have been invited to the exclusive Met Gala, and Chachki has also walked for the luxury fashion house Moschino.</em></p><h3><strong>RuPaul’s Drag Race: Plotly Dashboard</strong></h3><p>The show has a significant following, so I wasn’t surprised to find a <a href="https://rupaulsdragrace.fandom.com/wiki/RuPaul%27s_Drag_Race_Wiki">Drag Race Wiki</a> available with pretty much every last detail about the show. The data is pretty scattered however, so<strong> I wanted to see if there was a way to condense the most important statistics on Drag Race contestants into a simple and easy-to-navigate dashboard</strong>.</p><p>After playing around with a few tools, I decided to use <a href="https://dash.plotly.com/introduction"><strong>Dash</strong></a>, a relatively new open source Python library by <a href="https://plotly.com/about-us/">Plotly</a>, for creating web-based data analytics and visualization applications. Dash is powered by “components” written on top of the web-frameworks Flask (back-end) and React (front-end), while graphs are rendered using Plotly’s own library, plotly.js. What makes Dash really cool is that it is fully reactive, meaning that front-end users can select and query based on any number of input options to generate different types of analyses. Dash also allows users to take advantage of HTML, CSS, and Javascript for web-customization by providing a Dash/Python abstraction of these tools. Best of all, many of the features are free, making it an attractive alternative to Tableau or PowerBI, though I would say that the learning curve is a bit steeper since Dash requires a basic understanding of Python.</p><p>Here’s a summary of the contents of the dashboard I created:</p><ul><li><a href="https://medium.com/p/838f7d71b3e1#4635"><strong>Contestant performance by season</strong></a></li><li><a href="https://medium.com/p/838f7d71b3e1#1e1b"><strong>Ranking winners</strong></a></li><li><a href="https://medium.com/p/838f7d71b3e1#4027"><strong>Ranking Miss Congenialities</strong></a></li><li><a href="https://medium.com/p/838f7d71b3e1#61e8"><strong>Ranking contestants by “Dusted or Busted” score</strong></a></li><li><a href="https://medium.com/p/838f7d71b3e1#a3ac"><strong>Cluster analysis of contestants</strong></a></li></ul><h3><strong>Data &amp; Preprocessing</strong></h3><p>I managed to semi-successfully scrape some data from the Drag Race Wiki before finding the R package <a href="https://cran.r-project.org/web/packages/dragracer/index.html"><strong><em>dragracer</em></strong></a>, which contains a relatively comprehensive collection of data on RuPaul’s Drag Race episodes, contestants, and their rankings. Rather than to continue on my scraping mission, I decided to use the <em>dragracer </em>package, from which I downloaded one dataset containing episode-level data for each contestant, and another containing individual-level information for each contestant, such as their age and which season they competed on. Both datasets include information on 153 unique queens which competed on seasons 1–12 of the original series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N67XgCXRIC6g6YlptKwcEQ.png" /><figcaption>Example of episode-level data for contestants on season 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*QGH3DabyTT3x_DumKPXKXA.png" /><figcaption>Example of individual-level data for each contestants on season 5</figcaption></figure><p>From there, I performed the following preprocessing tasks:</p><ul><li>Remove episodes where no competition occurred (i.e. reunion episodes)</li><li>Regroup episode outcomes into fewer classes for simplicity of ranking</li><li>Create separate data frames for winners, Miss Congenialities, Dusted or Busted scoring, and variables for clustering</li></ul><p>RuPaul also loves to throw curve-balls each season, so there are some anomalies in the episode data. For instance, Trixie Mattel was eliminated in early on in Season 7, but later earned a spot back in the competition by winning a “return challenge”, before being eliminated again in episode 10. Season 12 frontrunner, Sherry Pie, was also infamously disqualified right before the finale after admitting to allegations of sexual misconduct. To simplify comparisons across seasons and contestants, I did not consider episode anomalies, and re-grouped such instances within the dominant five episode outcomes: Win, High, Safe, Low, Bottom, or Out.</p><h3>Creating a Plotly Graph</h3><p>All graphs were created using Plotly’s graphing modules. Here, I’ll demonstrate how to create a basic stacked bar chart of contestant performances for a given season.</p><p>I first import the<em> plotly.express </em>module, which allows me to create a<em> px.bar </em>figure. For demonstration purposes, I limit the dataset to season 5 contestants, and input the following parameters:</p><ul><li><strong>s5</strong>: pandas data frame filtered to season 5 contestants</li><li><strong>x</strong>: contestant column</li><li><strong>color</strong>: partition bars by the outcome column to display different colours for different outcomes</li><li><strong>color_discrete_sequence</strong>: hexadecimals specifying a different colour for each outcome class</li><li><strong>category_orders</strong>: order outcome column sequentially from “Win” to “Out”</li></ul><p>I also call <strong>update_layout</strong> on the x-axis to reorder the contestants by their rank in the competition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/864c4107beca0ae5aaf2e6b8944b6b11/href">https://medium.com/media/864c4107beca0ae5aaf2e6b8944b6b11/href</a></iframe><p>Using the above code, the following graph is output, which shows all of season 5’s contestants ordered by their overall rank in the competition. Voilà!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DC6MJxzS2L-dKdO1JDUUuw.png" /><figcaption>Example of a simple Plotly graph comparing both overall and episode level performance for Season 5 contestants. Image by author.</figcaption></figure><h3><strong>Dash: Putting It All Together</strong></h3><p>While a basic Plotly graph has limited features, Dash provides the dynamic framework necessary to build user interactivity around Plotly graphs. So once each of the graphs have been created, we can now use Dash to put everything together into one fully functioning dashboard.</p><p>To create a simple Dash application with one interactive graph, I first import the<em> dash_html_components</em> library for displaying Python abstracted HTML features, and <em>dash_core_components</em> library for displaying controls and graphs. Since I coded this project in Jupyter Notebook, I initialize the app using <em>JupyterDash</em>, but the call would be <em>Dash </em>otherwise. Lastly, I input an external CSS stylesheet to make things simple and pretty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90272d518527ef57751cc7168c99209e/href">https://medium.com/media/90272d518527ef57751cc7168c99209e/href</a></iframe><p>Next, I define the layout of the app using <em>app.layout</em>, which serves as the “skeleton” for formatting the structure and design of the dashboard. Here, I create three components which will be displayed in sequential order: an<em> </em>HTML header component, <em>html.H6, </em>to display the dashboard title, a <em>dcc.Dropdown</em> component to display a dropdown tab, and a <em>dcc.Graph</em> component to display the graph. In the dropdown component, I iterate through the “seasons” column of the contestants data frame, which allows the user to choose which season’s data to display.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830efd1d6b15a6fc8eb84a24eda718a9/href">https://medium.com/media/830efd1d6b15a6fc8eb84a24eda718a9/href</a></iframe><p>Lastly, I define inputs and outputs in the <em>@app.callback </em>section. Dash callbacks essentially tell Dash what to display based on the value of the input(s). Here, the input is defined by referencing the ID of the previously created dropdown component, as well as the selected season value. This updates the ID of the graph component, prompting Dash to display the graph. To display the graph I previously created, I slightly modify the the previous code to incorporate it within a function. This function takes the “season” value selected by the user in the dropdown component, and updates the graph by filtering to that season’s data as input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b776f957847ffe419f5a21a3686e041b/href">https://medium.com/media/b776f957847ffe419f5a21a3686e041b/href</a></iframe><p>With the above code, we can generate the following Dash app! As can be seen, the dropdown tab proves useful as it allows information from all 12 seasons to be displayed in a condensed format. This is what makes Dash so great — through the use of callbacks, each option in the dropdown filters to a different subsection of the underlying data, in this case, the specific season, which in turn outputs only data corresponding to the season queried.</p><p>Plotly graphs also contains an inbuilt feature which allows the user to query specific episode outcomes, say if I only wanted to visualize number of “Win” or “High” outcomes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Fa%2FEFQYuNv%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Fa%2FEFQYuNv&amp;image=https%3A%2F%2Fi.imgur.com%2FW0y09uv.jpg%3Ffbplay&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="609" frameborder="0" scrolling="no"><a href="https://medium.com/media/d554cf3e41c085b870b8652cf5b34a53/href">https://medium.com/media/d554cf3e41c085b870b8652cf5b34a53/href</a></iframe><h3><strong>Results:</strong></h3><p>Here we have the final product, which features all five tab-separated graphs. Two of the graphs have callbacks built in, allowing the user to filter based on the dropdown tab options to display different results. Ideally, the app would be deployed to a web server, but since I’m running this on my local machine for now, the full code can be accessed on my <a href="https://github.com/duncan-wang/dragrace">Github</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Fa%2FfJ539x3%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Fa%2FfJ539x3&amp;image=https%3A%2F%2Fi.imgur.com%2F5hKU44k.jpg%3Ffbplay&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="506" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19fe0ff666256dc49ae37b816cdd162/href">https://medium.com/media/b19fe0ff666256dc49ae37b816cdd162/href</a></iframe><h4><strong>Ranking winners</strong></h4><p>Because each season is a different length, the number of episodes are first scaled to 1. Doing so allows comparisons of relative performances across all season winners to be made. For simplicity’s sake, I grouped the finale win in the class “Win”. We see that Bob leads the race with the greatest proportion of wins, and is tied head-to-head against Sharon Needles, Bianca Del Rio, and Violet Chachki in terms of total number of wins. Meanwhile, Yvie Oddly rounds up the pack by contributing only one win prior to winning her season. This is really quite low, considering that 43 of the 153 queens have at least two wins to their name. <em>Sorry Yvie</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j88WHG4q-l0diLIiOB2KWA.png" /><figcaption>Relative comparison of season winner performances. Image by author.</figcaption></figure><h4><strong>Ranking Miss Congenialities</strong></h4><p>“Miss Congeniality” is a title awarded to one contestant each season for being the nicest or the most charismatic. Since prior to season 10, the title was decided via a fan-vote, some have argued that Miss Congeniality should <em>really</em> be “Miss Fan Favourite” instead, especially after season 9 winner, Valentina, was criticized for being, well, <a href="https://www.youtube.com/watch?v=VNxgdIxZtdk">not very congenial</a>. From the results, it makes sense that most Miss Congeniality winners place relatively high in the competition, considering that in order to win, contestants have to actually stick around long enough for their personalities to play out on screen. This makes Cynthia Lee Fontaine’s placement in the list all the more impressive, given that she was eliminated after just three episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Gmpg1nk-L1vOr0k-jzicg.png" /><figcaption>Relative comparison of Miss Congeniality performances. Image by author.</figcaption></figure><h4><strong>Ranking contestants by “Dusted or Busted” score</strong></h4><p>Dusted or Busted (DOB) is a fan-based scoring system used to rank players based on their overall performance in each challenge, regardless of their final ranking in the competition. To rank queens accordingly, I decided to slightly modify the DOB scoring system and only include data from challenge performances prior to the finale. Both “bottom” and “eliminated” contestants are assigned a score of 0, given that the ranking system does not differentiate between contestants that land in the bottom and are eliminated, and contestants who land in the bottom but are ultimately saved. My modified scoring system is as follows:</p><ul><li>Win: 10</li><li>High or Top 2: 7.5</li><li>Safe: 5</li><li>Low: 2.5</li><li>Bottom: 0</li><li>Eliminated: 0</li></ul><p>The following graph shows the top 20 queens based on DOB score, scaled relative to the number of challenges each queen competed in. There are no big surprises here, and it appears that RuPaul is a pretty fair judge since half of the queens in the top 20 are season winners, while the other half all happen to be finalists as well. An interesting observation is that neither Season 11 winner, Yvie Oddly, nor Season 12 winner, Jaida Essence Hall, appear anywhere on this list, while runner ups — Brooke Lynn Hytes (S11) and Gigi Goode (S12) — both make the cut. Snubbed? The <a href="https://rupaulsdragrace.fandom.com/f/p/4400000000000001169">internet</a> seems to think so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huV_Z2v3rMgxfmSRliS9Qg.png" /><figcaption>Comparison of 20 contestants by Dusted or Busted score. Image by author.</figcaption></figure><h4><strong>Cluster analysis of contestants</strong></h4><p>Another cool feature is that Dash can display the results of just about any sort of data-driven visualization. To further explore Dash functionalities, I used the K-Means clustering algorithm from the <em>sklearn</em> machine learning library to cluster contestants by combinations of the following variables:</p><ul><li>Age</li><li>Season</li><li>Placement in competition</li><li>DOB score</li></ul><p>K-Means is an unsupervised learning algorithm that is great for identifying patterns through exploratory analysis. In this case, the user is able to specify any of the six combinations of two variables to cluster by, as well as the number of clusters to produce. While the details of this algorithm are outside the scope of this article, with Dash callbacks, users are able to control the input parameters of various machine learning models and subsequently visualize different outputs produced by the model.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Fa%2FfVGGPn9%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Fa%2FfVGGPn9&amp;image=https%3A%2F%2Fi.imgur.com%2FmAfiM8D.jpg%3Ffbplay&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="609" frameborder="0" scrolling="no"><a href="https://medium.com/media/730bd20ea784b73ad3110b6224ff90a2/href">https://medium.com/media/730bd20ea784b73ad3110b6224ff90a2/href</a></iframe><h3><strong>Conclusion</strong></h3><p>The goal of this project was to combine two things I’ve grown to love this year— data science and Drag Race — and to create a fun and intuitive tool which incorporates both. The growing popularity of Drag Race means that there is no shortage of data available to work with, and the fact that there is now a package called dragracer (<em>who would have thought!</em>) makes it quite easy to do so. Overall, I found that Plotly/Dash’s open-source options provide a large number of data visualization and analysis tools for people who like to have complete creative control over their projects, and know a bit of code. User interactivity and customization are perhaps two of Dash’s biggest selling points, though there might be a bit of a learning curve for those more accustomed to traditional visualization tools.</p><p>For data-loving fans of Drag Race, this dashboard provides a compact alternative to <a href="https://en.wikipedia.org/wiki/RuPaul%27s_Drag_Race_(season_12)">episode-by-episode</a> breakdowns by condensing 12 seasons of data into just a few visuals, while still managing to convey the most pertinent statistics. The main value of the dashboard is its simplicity, which allows users to make quick, high-level comparisons of contestants on a relative scale. For future iterations, it might be interesting to incorporate the option of allowing users to mix-and match their favourite contestants across any number of seasons, or to include data from <a href="https://en.wikipedia.org/wiki/RuPaul%27s_Drag_Race_All_Stars">All Stars</a> to see how contestants fared their second time around the track. But for now, please enjoy my small tribute to RuPaul’s Drag Race.</p><p><em>Please feel free to reach out to me on </em><a href="https://www.linkedin.com/in/duncan-wang-b4a038163"><em>LinkedIn</em></a><em> or email me at duncan.wang@mail.mcgill.ca if you want to share any thought</em>s!</p><h4><strong>Project Code:</strong></h4><p><a href="https://github.com/duncan-wang/dragrace">duncan-wang/dragrace</a></p><h4><strong>Additional Resources:</strong></h4><ul><li><strong>Data:</strong> <a href="https://cran.r-project.org/web/packages/dragracer/index.html">https://cran.r-project.org/web/packages/dragracer/index.html</a></li><li><strong>Plotly/Dash:</strong> <a href="https://dash.plotly.com/">https://dash.plotly.com/</a></li><li><strong>Drag Race Wiki:</strong> <a href="https://rupaulsdragrace.fandom.com/">https://rupaulsdragrace.fandom.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838f7d71b3e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/drag-race-analytics-using-plotly-and-dash-838f7d71b3e1">Drag Race Analytics with Plotly and Dash</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>