<?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 Hshan.T on Medium]]></title>
        <description><![CDATA[Stories by Hshan.T on Medium]]></description>
        <link>https://medium.com/@hshan0103?source=rss-3f53bf89d0aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KOR9YtEmJ8z5FPO6jLP5Yg.jpeg</url>
            <title>Stories by Hshan.T on Medium</title>
            <link>https://medium.com/@hshan0103?source=rss-3f53bf89d0aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:07:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hshan0103/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[Evolution of Irreplaceable Data Team]]></title>
            <link>https://hshan0103.medium.com/evolution-of-irreplaceable-data-team-ec9d74fe90b4?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9d74fe90b4</guid>
            <category><![CDATA[data-strategy]]></category>
            <category><![CDATA[digital-transformation]]></category>
            <category><![CDATA[data-leadership]]></category>
            <category><![CDATA[ai-leadership]]></category>
            <category><![CDATA[data-culture]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 06:01:15 GMT</pubDate>
            <atom:updated>2025-11-25T02:23:58.799Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data teams become victims of their own early success — celebrated for quick wins, yet sidelined later because they remain tactical rather than architectural.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*TkuEZyjB55AaTu6C.png" /><figcaption>Credit: Hshan.T</figcaption></figure><p>Digital transformation is no longer optional, it is a critical driver of operational efficiency and competitiveness. As organizations accelerate their digital journeys, fostering digital mindset across all levels becomes essential. But, in the midst of these efforts, one key question arises — How should data team — once the sole group of data practitioners — position itself within the organization, to remain not just relevant, but influential and irreplaceable?</p><p>At the early stage of transformation, data team takes the role as catalyst to cultivate and boost data-driven culture within organization, by democratizing data access, introducing digital tools and enabling self-service analytics, making a shift from being service provider to innovation partner, celebrating organizational success alongside other functional teams. However, is this a long-term and sustaining plan to elevate team visibility and credibility?</p><p>The answer lies in moving beyond isolated project based outputs and taking a more holistic view of data initiatives. While the typical project based delivery model provides local quick wins, it results in redundancy, limited scalability and sustainability complexities. Quick wins build momentum and instant credibility, but it’s the connected horizontal influence that demonstrates long-term value and builds legacy. Bridging isolated success stories across different domains to shape a strategic ecosystem scaling across organization.</p><h3>Local Wins to Global Strategies</h3><p>Consider a manufacturing environment where the team has completed a number of impactful but independent projects:</p><ul><li>Product defect detection system</li><li>Machine anomaly monitoring system</li><li>Predictive maintenance system</li></ul><p>These systems deliver localized values. True potential unlocked when they are connected technically and intelligently. Imagine an integrated self healing ecosystem:</p><p>Spike in product defects triggers cross checking with the machine abnormality, that is then correlated to maintenance logs and recommends targeted maintenance.</p><p>This system sounds idealistic but it serves as an example how we should identify the missing pieces, uncover the interdependencies and connect the dots across domains/roles. The key idea here is not about the topic “self-healing” itself, it is about seeing through silos and immediate project successes, recognizing opportunities to intertwine fragments to close the loop end-to-end across operations.</p><h3>Evolve or Sideline</h3><p>Change doesn’t happen overnight. It begins with a shift in mindset, where data leaders no longer see their role as managing isolated projects, but as architects of a strategic, scalable, and sustainable data ecosystem. Deliver fast, but design with the full landscape in mind. Treating each quick win as a modular piece of a larger puzzle. We are not only delivering value, we connect and amplify the value across the entire organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9d74fe90b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improved Sqrt-Cosine Similarity From Scratch]]></title>
            <link>https://hshan0103.medium.com/improved-sqrt-cosine-similarity-from-scratch-c1e40e5a2e5b?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e40e5a2e5b</guid>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-processing]]></category>
            <category><![CDATA[similarity-score]]></category>
            <category><![CDATA[entity-matching]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 13:46:10 GMT</pubDate>
            <atom:updated>2023-04-16T01:57:16.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>Back then one year ago, I came across an interesting similarity scoring function when I was researching for some entity matching tasks — Improved Sqrt-Cosine Similarity.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNqcjoroTB7OQKSC-AQzVw.png" /></figure><p>The data industry has been evolving at unprecedented pace. There are dozens of papers published each day, some good research outcomes might be overlooked, and hence no open sourced library actually provides simplified and easy accessibility to these methods. Nonetheless, if the advantages of these research findings are actually justified, they should be appreciated. I do not see difficulty translating it from theory to code as an obstacle pulling us back from applying it. It might not be gaining the popularity but if you think it can be the best solution to your problem why not give it a try and investing some time on it.</p><p>Similarity score is a measure of how similar two vectors are. Understanding your data characteristics is the most crucial part in the computation process which aids the decision making on function for quantifying degree of similarity. Similarity score for text data can be computed geometrically or semantically, where the latter takes into consideration the relationship between words. It depends on the text encoding method applied. Commonly used quantifying function can be based on distance, orientation in space, set theory, measure of surface or probabilistic distribution, etc.</p><p><strong>Improved Sqrt-Cosine Similarity (ISC)</strong></p><p>Every approach has its pros and cons. Two most widely used similarity measures are Euclidean distance and cosine similarity function. Euclidean distance suffers from the curse of dimensionality. As the dimension of data getting large, the distance computed approaching constant value. Meanwhile, cosine similarity only takes into account the angle between two vectors, without considering other components in the space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*KC2FZvQCl7oiKpW5gN-pKQ.png" /><figcaption>Since AB and AC have same angle, x, similarity(AB) = similarity(AC).</figcaption></figure><p>ISC is an approach proposed which improved the issues encountered by earlier version sqrt-cosine similarity where the similarity between two identical vectors are not equal to 1. ISC updated the normalized components in the function and proposed the computation formula as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*4VvxFZ2UHGYefGIz" /></figure><p>This will be a matrix computation. To speed up the process, instead of Numpy arrays, tensors is used. Try to compute the score using the ABC example given above, you are expected to get a different score for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwQaMMbGJWT9uE06ETPL1w.png" /><figcaption>ISC function defined. mat_x and mat_y are vectorized text data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBiJW611GZr_rtNnIUr-rQ.png" /><figcaption>Note the difference in score computed.</figcaption></figure><p>I strongly recommend to go through the original paper for a more detailed about the experiments and comparison against existing methods. There is another scoring function applying measure of surface that caught my attention, however, it did not work well for my use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e40e5a2e5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spotting The Right Targets for Your Marketing Strategies]]></title>
            <link>https://medium.com/codex/spotting-the-right-targets-for-your-marketing-strategies-37472ae09496?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/37472ae09496</guid>
            <category><![CDATA[data-driven-decisions]]></category>
            <category><![CDATA[uplift-modeling]]></category>
            <category><![CDATA[data-driven-marketing]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 13:41:43 GMT</pubDate>
            <atom:updated>2022-06-23T08:55:58.844Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uplift Model — A predictive model to identify targets who are most likely to buy because they are targeted, unlike spray and pray marketing strategies with customer segmentation and propensity modeling.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*A9S0g8U7NvGndZUi.jpg" /></figure><p>Previous <a href="https://medium.com/p/93aa4c79f7a7">post</a> discussed customers segmentation with RFM analysis where the associated marketing strategy will be the so called spray and pray approach. We identify groups of customers with specific spending behaviour from basic transaction data based on three measures Recency, Frequency and Monetary Value, as targets for marketing promotion. The target group can be possibly lapsed, new acquisitions or those frequent purchasers of the similar items. The drawback of such a strategy is that we are clueless about who will be reacting to the content, some might not even open up the mail, like me? As compared to catalogue marketing in older days, digital marketing such as email marketing and social media marketing, are the current main streams in the industry. Flooding customers’ mailbox with unrelated promotions might frustrate them, reducing the tendency of content viewing.</p><p>Instead of searching for marketing targets by predicting who will be possibly making a purchase, the uplift model predicts who will be buying because the marketing campaign is directed to them. In other words, they buy because of the marketing effort, so your business spending/investment is more profitable (higher ROI) and creating value. Advantages of uplift model:</p><ul><li>improve customer experience (Reducing bulk of unrelated promoting emails.)</li><li>increasing efficiency of marketing strategies (Increasing return of marketing investment.)</li><li>avoiding overuse or addiction to promotions</li></ul><p>Before talking about the uplift model, let’s have a brief overview of another popular marketing model, propensity model. In simpler terms, the propensity model is actually a classical supervised machine learning model, but the specific problem statement and procedures following the prediction give it the title. Propensity model can also be applied with minimal RFM data, but as data collected by business is increasing in terms of width and depth the model can be more extensive or better performed. From the past marketing campaigns, we can get the target variable (binary variable) whether each customer responds by making a purchase. It works as follow:</p><ol><li>Data collection about marketing campaigns and customers receiving the promotion.</li><li>Data pre-processing, including cleansing, features synthesized, data normalization, etc.</li><li>Modeling.</li><li>Customers with the highest top-k responding probability will be targeting utilizing the quota available.</li></ol><p>In contrast to the propensity model, the uplift model gives a more actionable prediction. Instead of acting passively by sending the campaign brochures to potential responders and leaving everything to chance or fate, the uplift model puts business at a more proactive position to influence the outcomes by exploring how our intervention will increase the likelihood of desired outcome. Why uplift models? Let me answer this question with another question.</p><p><em>“ Would you spend an extra dollar on someone who is most likely to make a purchase or to persuade someone to change his mind and make a purchase? ”</em></p><p>The uplift model starts with two distinct setups for data collection, control and treatment. If you remember your science lesson, control is the setup where all the conditions are kept constant, in other words samples in the control set are not treated. Two different datasets enable us to compute differential advantages of action taken. At this point of time, you might be confusing or wondering how uplift modeling is done. Two models approach will be discussed briefly in this post. Target variable for uplift model can be numerical or categorical, it decides on the models to be trained on control and treated datasets. Similar to the propensity model, it is actually a supervised modeling problem which is slightly more complex as it involves two separate datasets simultaneously.</p><p>Nevertheless, the name ‘ two models approach ’ should have given hints on how the problem will be handled. 2x2 matrix below gives you an intuitive of what we are hunting for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*naiylQ64Fs45dNlHDbtBsA.png" /><figcaption>R: Responding; N: Not responding</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*r6YTbV6L3xKUkPpO9prH5w.png" /></figure><p>If you have a second thought of the matrix, targeting <strong>A</strong> does not make a difference because they respond whether they are targeted or not. Why don’t you save the marketing expenses for better use? We are looking for the group of customers in <strong>B</strong> as campaign targets and trying to avoid sending campaigns to those in <strong>C </strong>to avoid negative impact from our marketing effort and possible loss of customers. Two models are trained on control set and treated set respectively, <strong>MC</strong> and <strong>MT</strong>. Uplift score is then calculated to evaluate the impact of treatment given.</p><pre><strong>Uplift_Score = MT(X) - MC(X)</strong></pre><p>In some cases, Uplift_Score mentioned here is also known as individual treatment effect. Sign of the score depends on the nature of the target variable we are looking for. In particular,</p><ul><li>If predicting churned probability, we expect a drop in churned probability and hence <em>MT(X)&lt;MC(X)</em>, negative score is preferable.</li><li>predicting probability of purchasing, we expect an increment in buying probability and hence <em>MT(X)&gt;MC(X)</em>, positive score is preferable.</li></ul><p>Next step will be answering the aim of the analysis that you should have been deciding in the very beginning of the analysis. Are you intending to conduct population level analysis or prediction at a higher granularity of individual level. For population level analysis, we will be looking at the average uplift score and its confidence interval. If zero is included, treatment effect may not be considered significant depending on overall distribution of the scores. By conducting an A/B test, uplift modeling can be intermediate steps to choose between the range of treatments available. For individual level, as discussed earlier, we are able to identify the right targets through the scoring for our campaign to maximize return on investment. I hope the discussion above is brief enough as an introduction for uplift models and, this will excite interest and curiosity to further explore this topic.</p><h3><strong>Example</strong></h3><p>Consider a retailer who would like to conduct uplift analysis by offering a 20% discount to sell a new product. 1000 customers are selected randomly from the customers database for the experiment. There is cost associated with every marketing campaign so it is logical thinking to have a smaller treatment set. Cost referred here can reduce profit margin.</p><p>Experiment Set: 250 randomly picked from 1000 customers.</p><p>Control Set: remaining 750 customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*RFVUoYggils_xBRFtc0b3Q.png" /></figure><p>There are 100 customers (40% responding rate) and 600 customers (80% responding rate) respond by placing an order for treated and control sets, respectively. An overall uplift score for treatment given is -0.4, showing an adverse effect. Confidence interval at 99% is computed from the control set using the individual uplift score. Plotting a histogram of uplift score to visualize the distribution and draw insights from statistical point of view, such as distribution function, range of values, location of zero, skewness, etc.</p><h3><strong>Implementation of Uplift Model</strong></h3><p>Let’s get our hands dirty by applying the uplift model using a simple python library with simple implementation, evaluation and visualization, scikit-uplift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*iB9-p4htuZIht9n-SUZ6QA.png" /><figcaption>Dataset.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*kJATFiMk7DvuDdXr4DsrAQ.png" /><figcaption>Two models approach training.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*GXou0z20pucg91N3SF2jsA.png" /><figcaption>Average uplift predicted and its confidence interval at 99%.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*8pT3c4G787j8vDnGNA8Q7A.png" /><figcaption>Distribution of uplift prediction.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*fteFHgm3HWocT_1W668yYw.png" /><figcaption>Qini Curve for evaluating uplift models.</figcaption></figure><p>Implementation shown above is the most basic application of the uplift model. scikit-uplift is selected here as I think it is a good idea to begin with something fundamental. There are some drawbacks associated with this two-models approach and hence there is single-model approach introduced and now even more advanced meta-learner algorithms. Other elegant and sophisticated python libraries are available out there to build more performing models. Explore it if you are interested to go further and deeper!</p><h3><strong>Summary</strong></h3><p>Advanced development in modeling algorithms, storage and computing hardware makes data application or data driven decision making more seamlessly, provided you have enough and good quality data. It is always too late to realize data captured for past events is insufficient for a model to learn. For example, in the case discussed above, a business might consider storing not only customers data but also campaigns data. Data is always the foundation of a decent data solution.</p><p>Regardless of the types of marketing model you choose, improving customer relationship management (CRM) is the ultimate goal, typically for up-selling, cross-selling, customers retention (high cost for new acquisitions), boosting sales cycle, etc. Uplift model is investigating causal effect of actions/treatments for effective resources allocation, enhancing the customers conversion and minimizing negative impact of marketing campaigns forwarded. Although we focus on business application, the uplift model is suitable for use cases in other industries as well, as long as our main objective is to model the incremental impact of an action. Its modeling setups that are identical to classical scientific experimental setup reveals its degree of generalization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37472ae09496" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/spotting-the-right-targets-for-your-marketing-strategies-37472ae09496">Spotting The Right Targets for Your Marketing Strategies</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Association Rule — Your Business Booster]]></title>
            <link>https://hshan0103.medium.com/association-rule-your-business-booster-58a8b0ea45c5?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/58a8b0ea45c5</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 13:04:34 GMT</pubDate>
            <atom:updated>2023-04-15T13:57:30.989Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Association Rule (</strong>Market Basket Analysis)<strong>— Your Business Booster</strong></h3><h4>Availability of connectivity coverage, advancement of tools and devices push the effort in digitalization of most of our activities. Sometimes, we get lost in enormous amount of data that we have whether from internal databases, surveys, sample collections or web crawling. This post will discuss about ideas on data usage mainly in retail business based on association rule mining although the rule itself is appropriate for a number of industries including bioinformatics, manufacturing, pricing, etc. We will go through the idea and implementation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*k6-leJRu5CPx7qTM.jpg" /></figure><p>Adoption and application of software or computer system to automate business process make every move leaves footprints. The initial purposes of these systems are for recording and storing business transactions automatically in more organized manner especially in retailing and e-commerce, with intention from business monitoring to management. Moving into new era, supercharge your business with data driven strategies and decision making using vast amount of records stored from day one. But, how? The term ASSOCIATION RULE sheds light on relevant questions. Content below will mainly focus on market basket analysis in retailing sector, but few examples of its application in different industries will be shared.</p><p><strong>Association Rules</strong></p><p>A rule-based method to discover relation or correlation and co-occurrence between variables, it is well represented by ‘if-then’ statement. However, do note that this is not a causal relationship. Each rule is composed of two elements, if {antecedent}, then {consequent}. ‘Antecedent’ does not cause ‘consequent’, instead ‘consequent’ happens in combination with ‘antecedent’. The model is trying to learn pattern out of a pool of variables in database where all data points seem to be independent. The model aims to search for set of relationships out of combinations of attributes and out of those relationship it tries to find interesting subsets to be defined as RULES. The idea is statistical based and is published long ago, it does not involve any advance technique but it is still quite useful for data mining today as it reveals insights. In fact, lots of building blocks of sophisticated models/methods that catching attentions today are published decades ago, popularity remains low until recent decade due to exploding development in computing power.</p><p>Let’s imagine we have a tabular data of shape N x M, such that each row represents a sample and column represent an attributes, so we have N samples with M attributes each. The rule defines relationship if {A} then {B}, where {A, B} are subset of attributes. Of course in practical, we are not looking for rule for each sample. Our goal is too uncover the statistically significant patterns out of N samples. If we have 100k samples, 10 of the samples share the same subset of attributes, it is not frequent and significant enough to call it a rule.</p><p><strong>Use Cases for Association Rule</strong></p><ul><li>Market basket analysis — Typical example in retails, e-commerce or any shopping transactions, business will determine the sets of items that are most likely to be purchased together. This will be example for the more technical content discussed below in this post, since data is available open source.</li><li>Medical diagnosis — associated symptoms are analyzed for diseases diagnostic after the rule is scientifically proved, doctors will imply it as practice or evidence to detect diseases.</li><li>Loss Leader Strategy — Not all deals are expected to be profitable for every business, some deals are made at par with cost or at low profit level just to attract new customers with propensity to buy the associated items. The complete flow for this strategy is definitely involving some analysis on pricing individual item in subset identified through association rule.</li></ul><p><strong>Measures Definition</strong></p><p>We mentioned in previous paragraph, each rule formed is statistical significant. Question, how do we compute and define its significance? There are quite a number of measures used to evaluate and judge how interesting a relationship is, including all-confidence, collective strength leverage and others that are beyond the scope of this post. Below are few common measures to be applied for market basket demonstration here:</p><ul><li>support(A,B) — Probability of transactions where item A and item B occur together. The higher the better, as they are often bought together. Mathematically, this refers to the probability of intersection of A and B, P(A n B).</li><li>confidence(A -&gt; B) — Probability of transactions having all items in A also have items in B. This is different from support in such a way that, we are talking about given a transaction has itemset A, how many of those transactions also have itemset B. Obviously, this is a conditional probability in mathematical term, P(B|A). It does not provide outlook on association in entire dataset, as compare to support.</li><li>lift(A -&gt; B)—support(A, B) divided by product of support(A) and support(B) such that A and B are uncorrelated in the denominator. Lift of 1 means A and B are independent. Lift &lt; 1 means substitute relationship between A and B (customer buys A might not buy B, vice versa). Lift &gt;1 means strong association between A and B.</li><li>conviction(A -&gt; B) — Expected frequency of incorrect association between A and B (A occurs by B does not) declared by the rule.</li><li>others, such as all confidence, collective strength, leverage, etc.</li></ul><p><strong>Algorithms</strong></p><p>Next question comes after knowledge about measures used for evaluation is, how do we use it to perform the search across entire dataset to find the rules? There are multiples algorithms available for implementation based on your data properties. I am not planning to dive deep into each of these. To make it understandable, they will only be discussed along their implementation and illustration in current or future posts.</p><ul><li>Apriori</li><li>Eclat</li><li>FP growth</li><li>Multi-Relation Association Rules (MRAR)</li></ul><p><strong>Demonstration of Market Basket Analysis</strong></p><p>Scope of discussion for remaining sections will be narrowed to specific type of association rule application in retailing sectors, the market basket analysis (MBA). To be frank, MBA is simple. It used the most simple mathematics (typically set and probability) and analytics knowledge to provide the effective way to look for likelihood of various items to be purchased together in single transaction. Are you a online shopping lover? Is the term ‘frequently bought together’ familiar to you? Association rule is what happened behind the scene.</p><p>Insights drawn from MBA help to boost business by developing more effective marketing strategies in a number of ways:</p><ul><li>store layout/display decision to increase cross selling</li><li>catalog design and cross marketing for online business</li><li>customized promotion for target customers</li><li>loss leader strategy</li><li>purchasing trends</li><li>customers needs and behavior</li></ul><p><strong>Implementation of Association Rules</strong></p><p>Two main frequent itemsets mining approaches to be discussed and compared, Apriori, Eclat and FP Growth algorithms, using python language. You can easily get public dataset for MBA. For methods used for the remaining section, we do not consider number of units purchased, the information we need is just binary data. Each transaction is set of items. These mining algorithms extract frequent itemsets and association rule impart information on antecedents and consequents.</p><p><strong>Apriori Algorithm</strong></p><p>Given a support threshold, T, we are going to search for subsets of items that occur in at least T transactions. T is how we defined ‘frequent’ itemset. Apriori works in such a way that frequent subset of items are extended one at a time, which mean if we have {A, B} that are currently identified as frequent itemset, {A, B} will be extended to {A, B, C} in next step and count the number of transactions with this combination. This iterative process continues until there is no further extension found. Apriori holds on to the principle, if an subset is infrequent, its superset is infrequent, vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Fzfcxg4I-lg3t-ybVe96qQ.png" /><figcaption>Fig 1: Searching for frequent itemsets with support threshold. (Apriori)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnTJ3wXgNy5Py2n49UbqXA.png" /><figcaption>Fig 2: Dataset.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*88e1c665vMfBpBPUxlKaKw.png" /><figcaption>Fig 3: Apriori from mlxtend generating frequent itemsets.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cwc6k2D66jIk_pdYNW5Rrw.png" /><figcaption>Fig 4: Association rule from mlxtend generating antecedent and consequent. (Apriori)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*WiUJ5rI338yvcL8mQxTctA.png" /><figcaption>Fig 5: Number of rules formed at different confident level. (Apriori)</figcaption></figure><p>Limitation of Apriori:</p><ul><li>Inefficiency, searching time increases exponentially with dataset size. The algorithm scans whole dataset repeatedly for every subset formed to compare and test against the support threshold.</li><li>Memory issue, especially when the dataset is large.</li></ul><p><strong>Equivalent Class Clustering and Bottom-Up Lattice Traversal (ECLAT) Algorithm</strong></p><p>As opposed to the breadth first search algorithm, Apriori, Eclat is depth first search algorithm. Theoretically, it is more efficient in term of computation time and memory required, and more scalable as compared to Apriori algorithm. Nonetheless, execution time is much longer than Apriori with library used below. The algorithm runs recursively such that those itemsets with more than T transactions are combined to form the itemset for next level of N, until there is no pairs can be formed. To make this clearer, figure below might give a better illustration on the process. Instead of running the process till N=4 as in Apriori, it stops at N=3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*kJaC64kryuNdZimjgIz1SA.png" /><figcaption>Fig 6: Searching for frequent itemsets with support threshold. (ECLAT)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAwrYNDKdFEZkmbeGtexkA.png" /><figcaption>Fig 7: Input dataset format for pyEclat.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC9KL5hXpEMAQB1iUhHCyg.png" /><figcaption>Fig 8: ECLAT mining.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*tNtWh2QOySFpcX1vL5MFpA.png" /><figcaption>Fig 9: Formatting output.</figcaption></figure><p>Limitation of Eclat:</p><ul><li>Memory issue remains if we are expecting to have dataset with large subset of items in most of the transactions.</li><li>Does not provide more insights/information on the occurrences such as those computed in Apriori, Confidence, Lift, etc.</li></ul><p><strong>Frequent Pattern (FP) Growth Algorithm</strong></p><p>FP-growth algorithm is seen as alternative to Apriori as it overcomes Apriori shortcomings by representing entire dataset in tree structure. The tree is growing and splitting as we go through each transaction by considering the support of each item in the transaction by descending order, more shared branches on top of the tree, smaller tree constructed. Items that do not meet the minimum support are discarded and it does not generate candidates itemsets. Hence, searching is reduced significantly and execution time is shorter. Illustration with diagrams below might give better intuition how the mining algorithm works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*w8s6VoMe0X2MrFwRLz53xQ.png" /><figcaption>Fig 10: Computing and ordering by support count. The table should be further expanding by forming itenset of size more than 1.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*RNqGoWVSGARiyqjjF8lYyw.png" /><figcaption>Fig 11(a): Tree construction based on simplified table given in Fig 7.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*UFvSi2mDxGT5N1x3XLzH4A.png" /><figcaption>Fig 11(b): : Tree construction based on simplified table given in Fig 7.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*R9duW9VyXSWkG7BMo9XTXA.png" /><figcaption>Fig 12: FP-Growth from mlxtend, generating table of itemsets with support more than min set. (Using same dataset as Apriori)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_2oc1wuFh2pKXs4vXq4ZQ.png" /><figcaption>Fig 13: Association rule from mlxtend generating antecedent and consequent. (FP-growth)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*pujFB_tFqvAQ9D0JHJ8myg.png" /><figcaption>Fig 14: Number of rules formed at different confident level. (FP-Growth)</figcaption></figure><p>Limitation of FP-growth:</p><ul><li>Cumbersome and expensive to build.</li><li>Memory issue. Long list of items is stored and scanned if setting low min_support_count.</li></ul><p><strong>Summary</strong></p><p>Following the pace of technology and data science field advancing, dozens of sophisticated models published everyday. Most of the simple and basic models might be left out as we are amazed by how powerful the recent innovation is. Nonetheless, there is no model that best fit all problem but there is always the best model for a particular problem, we still need to do some testing to prove model proposed works. Why don’t we start from the fundamental solution for every situation encountered? If simple method solves the problem, why are we spending too much time and resources on complex model for negligible improvement? You might lose the best timing to stand ahead of other businesses. There are always times where simple methods outperform complex ones. This post covers only the popular and commonly known algorithms. Looking forward to put more effort in exploring list of algorithms available for association rule mining in future. Marking the end of this post by something I think worth a thought … will the amount of purchase for each item (so called item ‘weight’) in each transaction has some kind of contribution to MBA? And how?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58a8b0ea45c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insightful Analysis Begins With A Right Question]]></title>
            <link>https://hshan0103.medium.com/insightful-analysis-begins-with-a-right-question-4d92a4ae075b?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d92a4ae075b</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-insights]]></category>
            <category><![CDATA[data-strategy]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[business-strategy]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 12:27:40 GMT</pubDate>
            <atom:updated>2022-02-16T03:16:03.762Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simplified flow of data analysis. Understand the requirement. Defining the needs. Analyze the information. Interpret the result. Presenting the findings. Storytelling. Recommending solutions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*I4iALAOKVXM-6BbL8uFMYg.png" /></figure><p>How to get start to work with data? What kind of data to adopt for solving your business problem? What tool is best suit to answer your question? These questions worth a deep thought if you are serious to change your business model from a traditional way to systematic data driven strategies in this digital age.</p><p>As the data storage and management architecture and system are improving from day to day, the trend for data collection is switching from goal oriented to massive, unstructured and non-goal oriented by capturing whatever a business is being exposed to. From there onwards, subset of data is then extracted for further analysis according to the requirement. This setting is trying to avoid the loss of information. Whether or not you are currently getting ready to impose data related approach in your business, most of us believe the day where application of data is no longer a trend but a must in every business model will not be long from now. Therefore, it is vital to have awareness to capture, collect and store every data available so will not be trapped in condition lack of data for modelling.</p><p>No matter how sophisticated your infrastructures or analysis tools are, it does not bring any value to you if you failed to use it appropriately. Data is just collection of words, numbers, pictures and others, it is meaningless until you utilize it in a proper way to explore its indispensable value. Taking a scientific experiment as an example, the process is always starting with problem statement and hypothesis. Scientists are clear about what they intend to test out or to prove then they proceed with experiment and data collection. The same concept should be applied to data analysis, you are ‘blind’ until you find your ‘target’. The analysis journey can be broken down into several steps as below:</p><p><strong>What is your problem? Who are the audience?</strong></p><ul><li>Evaluate well-being of business. Have an overview of current situation.</li><li>Who are the audience asking for the analytics job to be done? Different departments may look at each business challenge from different perspectives.</li><li>Identify business challenges. Think broad and deep. So, you can foresee potential challenges in near future.</li><li>Your goal corresponds to challenges. May it be business expansion and revenue boosting plans.</li></ul><p><strong>Asking a question?</strong></p><ul><li>Previous step talks about wider business landscape, analysis should begin with a narrower, attainable and more specific focus. Properly frame your question.</li><li>For example, instead of the goal mentioned, you may ask, what are the marketing plans to boost sales? which cost to be controlled/reduced? Which are the most profitable products?</li><li>Focusing one target at a time, the accumulated outcome will be achieving our main goal.</li></ul><p><strong>Data source and data quality</strong></p><ul><li>If having proper planning about data application, a business should have massive/adequate amount of data.</li><li>Identify subset of dataset that is useful for analysis to give insights regarding the business problem.</li><li>Data cleaning, extraction, transformation and loading to data warehouse for analysis.</li></ul><p><strong>Analysis modelling</strong></p><ul><li>Always hold on to the principle. There is no perfect methods/models that handle all cases. Nonetheless, there is always one method works the best for each case.</li><li>Look at the types, distribution and behavior of our data.</li><li>Plan for proper analysis pipeline and proposed models.</li><li>Train, test and evaluate our statistical models. Optimize and selecting the most performing one.</li></ul><p><strong>Result interpretation and presentation</strong></p><ul><li>When doing analytics task, it is a good practice to assume our audience is not expertise in analytics.</li><li>Presenting visualization of results for better illustration. Explaining results in plain English rather than all the technical term which may be difficult for people without statistics background.</li><li>Ensure interpretability and expandability of findings.</li></ul><p><strong>Suggestion</strong></p><ul><li>Outline how the results provides valuable and actionable answer to the crucial problems raised.</li><li>Recommending solution to stakeholders.</li><li>Documented or properly written as report for submission and record purposes.</li></ul><p>Analytics team deal with data to aid business process along the workflows, from sales, finance, marketing to management. Data analysis is not about communicating with data solely. Talk to departments to understand their needs. It should assist them to find solution in systematic and scientific way. We do not use sixth sense, we do not guess, the results are supported by evidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d92a4ae075b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayesian Approach in Logistic Regression]]></title>
            <link>https://medium.com/codex/bayesian-approach-in-logistic-regression-981f1387505b?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/981f1387505b</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[frequentists]]></category>
            <category><![CDATA[generalized-linear-model]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 10:36:11 GMT</pubDate>
            <atom:updated>2021-09-05T08:21:14.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>As the field data science are evolving, machine learning and deep learning are gaining attention from the crowds. Are we forgetting the fundamental knowledge lying behind these sophisticated methods? We are tending to call a complex but powerful model, a black box model’, because it is losing interpretability as it gains the power to give final desired output, but we are losing track of the development and some insight beyond those data. So, let’s back to the basic about statistics, its importance should not be fading.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*V99KUKXOiyu4f0K9" /></figure><p>It has been long since my last time working a Bayesian analysis. Until recently, I was exposed to its application in logistic regression. What worth to be mention is that, coincidentally I came across a paper working on unsupervised natural language case by applying Bayesian concept in generative distribution at the same time. Let’s take a look at difference between classic and Bayesian analysis.</p><p>If you are from statistics background, whether it is pure statistics, analytics or actuarial like me, I believe you will not be strange with the terms ‘classical statistics’ and ‘Bayesian statistics’. First lesson about statistics in high school, we were asked, ‘What is probability?’. And, today we will be questioned in slightly more tricky way, ‘What do probability mean in frequentist statistics and Bayesian statistics.?’. Frequentist interprets probability as frequency of an event out of large number of trials for a repeatable experiment. Yet, Bayesian probability is a way of expressing our degree of belief about an event.</p><p>Back then during my degree study, we were exposed to theoretical application in treating parameters of a distribution as random variables, updating prior belief about parameters using data provided and hence drawing conclusion about predictive model with updated posterior distribution of its parameters. The overview of this topic is restricted to well-known and formally defined distribution. Until I came across the term Bayesian Machine learning, I always wonder its application in machine learning. My journey then started from here, a simple example about logistic regression using Bayesian statistics with Markov Chain Monte Carlo (MCMC) method without going through the detailed and more formal pipeline including deduplication and outliers inspection. Assuming dataset is free from those data quality issues.</p><p><strong>Data Loading and Checking:</strong></p><p>Target variable in dataset given is numeric data, but we aim to perform logistic regression here, where target variable supposed to take only values of 0/1. Let’s assume, a score above 6 is good wine (y=1). There is no missing value in dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQvZUYjd3kon7vEnbbgfXA.png" /><figcaption>R1: Data loading and NA checking.</figcaption></figure><p><strong>Data Summary and Classical Analysis (Generalized linear model, GLM):</strong></p><p>Statistics summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_mJSQAOILeukletogUBFQ.png" /><figcaption>Table 1: Statistics summary.</figcaption></figure><p>Standard Deviation of Variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*OVcY8FoPzWLzUvknG_hkGw.png" /><figcaption>Table 2: Standard deviation of variables.</figcaption></figure><p>Frequency Table of Wine Class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*wFAjhqcwBpTCtUYw7P8shw.png" /><figcaption>Table 3: Frequency table.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*ik6VLOD8KmEDwkBp_uGFQQ.png" /><figcaption>Plot 1: Histogram of wine class.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ek1DuMM20kpe6fNPzMuO5w.png" /><figcaption>R2: Statistics summary.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24dnRJRiVyx7uC5UfTLhpg.png" /><figcaption>R3: Standard deviation.</figcaption></figure><p><strong>Generalized Linear Model (Logistic Regression Model):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB6eVUIxw3NeqTPmRQ-kUg.png" /><figcaption>R4: GLM model.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKmbxayBAMHJoIHif_22XQ.png" /><figcaption>R5: Confidence Intervals.</figcaption></figure><p>Ranges of values for variables varies a lot, from a minimum of 0.0136 to maximum of 283. Total.sulfur.dioxide reported standard deviation of 32.895 and density has standard deviation of 0.002, which are the maximum and minimum among all variables. There are 217 good wines (quality score &gt;= 6.5) and 1382 wines not classified as good.</p><p>Assuming null hypothesis stating coefficient of variable k is zero, at significance level of 5%, variables pH, free.sulfur.dioxide and citric.acid have p-value of 0.822, 0.376 and 0.498 respectively. Thus, there is no statistical significant evidence to reject null hypothesis for these three coefficients. It may be removed from the model. In addition to that, obvious drop in residual deviance, comparing to null deviance which assume all coefficients to be zero except intercept, implies that saturated model trained is better fit.</p><p><strong>Generalized Linear Model (Logistic Regression Model) Without Insignificant Variables:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzI7S4O3Ua1MqRe_rhqTIw.png" /><figcaption>R6: GLM Model for insignificant variables removed.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DuUgm8wIgsICjLYGhvmTA.png" /><figcaption>R7: Confidence intervals for insignificant variables removed.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*4D8TlChS9hiUCkmdedhF3w.png" /><figcaption>Plot 2: ROC curve of model in R4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRmW57j5WC-UPSK1PgGLTA.png" /><figcaption>R8: Area under AUC of GLM in R4.</figcaption></figure><p>After removing insignificant variables, remaining variables are still statistically significant in this model. The model reports lower AIC of 890.08, it does not provide information of best model, but it indicates the better fit model out of all experimented. But there is very slight increment of 2 in residual deviance which means a very small amount of unexplained variation in the second model as compared to first model. ROC curve for both models are almost overlapped with similar amount of area under the curve, indicating same classification performance. Nonetheless, the first logistic regression model coefficients will be used for the Bayesian analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1sqf0eMgsZ6uaYIeUSotQ.png" /><figcaption>R9: Probability of Good wine with varying total sulfur dioxide given other variables are held fixed.</figcaption></figure><p><strong>Bayesian Analysis</strong></p><p>Consider the logistic regression equation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*OoXW1qytu5PzSxJV" /></figure><p>We will be generating samples for coefficients of the linear model. Assuming independent distributed coefficients, taking prior distribution of coefficients as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*sTyS5M5o02u0JaL8gRVLxA.png" /></figure><p>The log-likelihood equation in term of beta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*SJnLCh0cbfNDJh4JsCu5CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*OZZuSTVuXOdOWctztw-LEg.png" /></figure><p>Find p in term of Beta and X then substitute into likelihood function. We then generate the posterior distribution of the vector of Beta using formulas above. Omitting derivation process here. To ease the computation as usual, we will transform it into log-likelihood function. A multivariate normal distribution which is impossible to derive analytically by deriving differential equation to find the maximization point. Hence, posterior samples are generated by MCMC sampling process, such that we believe the chain will converge to a point regardless of initialization state if it is ran long enough. Multiple initializations are tested to visualize how it influences MCMC sampling process, MH-sampling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCSqF1-0kzvip2wQBLOj7Q.png" /><figcaption>Table 4: Initializations for MH-algorithm.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8cim0MsSzn2gfvt6UTB9A.png" /><figcaption>R10: MH-algorithm and prediction of classes (step 5: Prediction)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6N4YXgXx_Pp7EwUw2gqW0A.png" /><figcaption>R11: Simulations with different initializations.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1frEdAm7SC5CWWdzNuzqQ.png" /><figcaption>R12: Plots of the chains simulated.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhVVbWv6ZzCvqDS_dhuoUA.png" /><figcaption>Plot 3: Markov chains simulated.</figcaption></figure><p>The ideal acceptance level suggested by experts is around 20–30% by tuning the parameter <strong>c</strong> in the code, which we use to scale the variance of multivariate normal distribution used in MCMC process.</p><p>All the four chains generated with different initializations converged within 10000 simulations, but there are some fluctuations in the beginning of the chains. Chains initialized with coefficient from frequentist analysis converge the fastest and the third initialization option appears to fluctuate the most among all four. Nevertheless, there are some coefficients obtained from Bayesian analysis do not convergence to the MLE estimate regardless of te initialization applied. Coefficients for intercept, fixed.acidity, volatile.acidity, residual.sugar, density, pH and alcohol do not convergence to classical estimates. If we set a very strange initial vector, the chains will take longer run to attain convergence, regardless of whether it converges to estimates obtained for frequentist analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qT2_92hTy5LTK4uZt8JCow.png" /><figcaption>Plot 4: Barplots of target variable predicted for models with different initialization.</figcaption></figure><p>Probability of Good wine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*MZJDL03nRSfcRh8nfCYbtA.png" /><figcaption>Table 5: Probability of good wine.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMU2A89l4LHI0VTDXFAf9A.png" /><figcaption>R13: Barplot and probability computation.</figcaption></figure><p>There is difference observed in the number of samples predicted as good for Bayesian model formed with different initializations. Third initialization give probability (0.0885) that is most distinct from original data (0.1570). The remaining three are close to each other but still slightly away from 0.1570.</p><p><strong>MH-Algorithm with library metrop:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDFrPSJzXU82bTcUwxgYQA.png" /><figcaption>R14: Samples generation with library metrop() in R.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIkT5NS8_QjQMwqYK7oo5g.png" /><figcaption>R15: Acceptance probability with metrop().</figcaption></figure><p>Running code above, you are expecting to obtain the same plots as Plot 3 above after attaining stationary state or convergence. There are some fluctuations in the beginning of the chains as compared to the former. This method is readily available and easy to apply in a single line of code, but the challenge is to tune the best scaling parameters for each coefficient, especially when we have a set of variables with large differences in degree of variation. Dataset for this project is the best example, the variation ranges from 0.00005 to 0.1. The situation is getting even complicated when we set initialization to be a vector of weird values, differ a lot from the possible coefficient. We might even face the problem to reach convergence, if the parameter is not properly tune. An example of such a situation is illustrated below. Instead of reversing the computation of variance of multivariate normal distribution given by c*omega in self-defined M-H algorithm to obtain parameter scale for metrop() function, scaling parameter is set to be a different matrix. Most of the chains do not converged even after a long run. An example shown below to illustrate importance of setting the right arguments in the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sfP5CdT6Xs5YN92g17ppzA.png" /><figcaption>Plot 5: Failed Case with Impropriate Argument Set for Scaling.</figcaption></figure><p>Sometimes, readily available MCMC function ease the work to write a lengthy code, but it does not always give a good result and bringing negative impact if we do not analyze the result carefully before publishing. The most optimal or suitable approach depends on the data available to us. Rather than trying to take on the risk to define the function where we might expect some mistake along the process, we may make it simple by performing normalization or scaling on the data. But, do note that the model built is based on the transformed data. Hence, when we try to make any prediction in new data, transformation needs to be performed before substituting in the model.</p><p><strong>Conclusion</strong></p><p>Since the aim of this piece of work is to gain hands-on experience with Bayesian and MCMC, the experiment can be improved by splitting samples into training and testing dataset for more convincing performance evaluation. A further statistical inference that plays similar role to hypothesis testing by inspecting p-value in frequentist statistics is through computation of highest density interval. Searching for the shortest interval giving the specified confidence level, then check if the value you are tested is falling beyond the interval to draw conclusion.</p><p>Beyond all the debates between frequentist and Bayesian, I believe innovation and publication of every new idea is to overcome drawbacks of existing methods or to provide a different perspectives to look at the problem. The existing should not be completely replaced and wiped out. Choosing the right methods for every case boosting performance, you may discover gems behind the digits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981f1387505b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/bayesian-approach-in-logistic-regression-981f1387505b">Bayesian Approach in Logistic Regression</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sales Prediction: Multi-Steps Forecast from Classical Time Series Models to Machine Learning Models]]></title>
            <link>https://medium.com/geekculture/sales-prediction-multi-steps-forecast-from-classical-time-series-models-to-machine-learning-models-b5718b242648?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5718b242648</guid>
            <category><![CDATA[sales-prediction]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 16:41:27 GMT</pubDate>
            <atom:updated>2021-04-22T08:57:04.491Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time series analysis is applicable in numerous industry, such as business, economic, financial and even healthcare. Scientists were doing research on this topic since 19th century. As the name suggests it is highly dependent on point of time when it is collected. Have you ever thought of what make it a special kind of dataset and what makes it different from regression problem?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9IC0x-W2LFpAHvkJLOXWA.png" /></figure><p>Time series is a collection of ordered data points collected sequentially over a period of time. Generally, it is collected at regular intervals. It is special as data points are not independent, we expect a certain degree of serial correlation. There are no independent variables and time-dependent make it distinct from the regression problem. Time series forecasting is about predicting the future based on historical data by extracting useful statistics and characteristics within data. We will be going through time series description, analysis, and modeling in this piece of writing.</p><p>Time series is mainly comprising of three components:</p><ol><li>Trend — general long term direction in which data is changing</li><li>Seasonality — patterns recur systematically over specific period of time</li><li>residuals — short term, random fluctuation</li></ol><p>Discussing how to identify possibility presence of these components in time series and decompose it for visualization to validate whether it justify our hypothetical statements about investigation domain or analysis goal. For example, a businessman expects increasing trend in their yearly revenue and a decreasing or constant budget allocation, a doctor expects a rather consistent heartbeat rate. Basically, time series forecast begins with data visualization to have an overview and inspecting presence of each component, trend and seasonality. These components are then estimated and eliminated, leaving it with a stationary series. Models are built and optimized on the stationary series. Informally, a series is so called stationary if they have constant statistics property, such as variance, covariance and mean at all point of time. Formally speaking, let <em>X(t)</em> be a time series, we are considering only weak stationarity which states a series is stationary if</p><ul><li>Mean of <em>x(t)</em> does not depend on <em>t</em></li><li>Variance of <em>x(t)</em> does not depend of <em>t</em></li><li>Covariance of <em>x(t)</em> and <em>x(t+h)</em> does not depend on<em> t</em>, solely depend on <em>h</em> only</li></ul><p>However, predicted output by model is not the answer to our question. It needs to be rescale to original scale by adding back removed components to output obtained. Of course, there are models where stationarity is not the strict assumption, process will be much simplified by skipping the components decomposition and rescaling. Some concepts or terms used in time series analysis will be discussed along the process.</p><p><strong>Problem Statement</strong></p><p>Assuming you own a store and currently working on stocks planning for coming years. By taking data of monthly sales in past 11 years , you try to predict monthly stocks consumption for next 12 months, to ensure healthy cash flow and minimize wastages by avoiding oversupply.</p><p><strong>Data Loading</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKOHGni4elWh512RepzQKA.png" /><figcaption>Data Loading and Info.</figcaption></figure><p>Note that data type for date after loading, it is changed to datetime for extraction of date components if necessary.</p><p><strong>Data Description</strong></p><p>Since this is a time series data, it should not be shuffled and partition randomly. Else, we will encounter situation where we might be predicting past based on future data which does not make any sense. The order must be preserved and we take the last 12 months as test data. There is no null data.</p><p>Train Dataset: Monthly sales record for a particular product in a store, from 2000 to end of 2009.</p><p>Validation Dataset: Monthly sales for Jan 2009 — Dec 2010</p><p>Test Dataset: Monthly sales for Jan 2011 — Dec 2011</p><p>Size: 122 records for training , 12 for validation and 12 for testing</p><p><strong>Exploratory Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYK_U3H68wBBk8sTq1Vh_g.png" /><figcaption>Data Summary and Boxplots</figcaption></figure><p>Statistics summary shows that the mean and standard deviation are increasing from year to year suggesting presence of uptrend and wider spreading of data, except 2002. Spreading of data is visualized through a series of boxplot by aggregating sales by year for clearer inspection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8FFUwRHjAWoBO0KgQ4HJA.png" /><figcaption>Time Series Plot.</figcaption></figure><p>Time series plot agrees hypothetical statement about uptrend, a more careful observation exposes presence of seasonality through repetition of pattern along the line plot, similar shape with different degree of spike or spread.</p><p><strong>Data Transformation</strong></p><p>We notice presence of trend and seasonality from previous section. As most of statistical analytics tools or models rely very much on stationarity assumption, elimination of those components is crucial before proceeding with modeling. So, series to be model will have constant statistical characteristic over time. There are numerous methods introduced to verify stationarity of time series, however, only a direct inspection through visualization and Dickey-Fuller test. Dickey-Fuller test is a hypothesis testing with null hypothesis states the series is non-stationary. You may wish to test on variogram, a stationary series is expected to reach state of stability on variogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgEPL97mer-eG5RPpmqG9w.png" /><figcaption>Time Series Plot with Rolling Mean and Standard Deviation (window=12).</figcaption></figure><p>A red line representing moving average with window of 12 and an orange line of standard deviation of rolling data with same window are plotted. Standard deviation of rolling data is much lower as compared to data values. At current stage of analysis, we are almost confirm there is increasing trend components decomposition is done. Python library applied here imposed moving average in decomposing the time series. Such kind of decomposition is usually not the straightforward method telling you if there is seasonality and trend. It intends to break it down for visualization after you have identify them. Typically, this step solely is insufficient to prove stationarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rL3GHz23vF5Rbv1mK-QPNw.png" /><figcaption>Components Decomposition.</figcaption></figure><p><strong>Illustrate how does shifting, rolling mean and standard deviation work</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*GhwDmeuUl56yjIyrEQhMVA.png" /><figcaption>Shifting illustration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*E_xnKGUbJyDafN-XpLlx0Q.png" /><figcaption>Rolling mean illustration.</figcaption></figure><p>Rolling standard deviation works in similar way as rolling mean, but calculation function is change from ‘mean’ to ‘standard deviation’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91JKZGB4aY-CJBJj7fyWhA.png" /><figcaption>Plot of Training Data — Rolling Mean (window=12).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtF_fy_5NJpSsUZlJpG3IQ.png" /></figure><p>A series of transformation and differencing required to make the series stationary. After substracting rolling mean out of original series, note the increment in spreading of data and rather constant rolling mean over time. Hence, a log transformation might be suitable as it penalize large number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej_1GNK4p53WZWWyQVmzug.png" /><figcaption>Time Series Plot of Log-transformed Data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qbSytj-izxBDRMA8OCKAA.png" /><figcaption>Plot of Log-transformed Data — Rolling Mean (window=12).</figcaption></figure><p>Although range of values for log-transformed, degree of spreading of log-transformed series with rolling mean removed does not show obvious change over time as compared to original series. Nonetheless, rolling mean and standard deviation are fluctuating without significant pattern observed. Overall scale is changed, but we do not expect changes to conclusion of presence of each time series components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GY3JgjUeIjuJ110CU7hfXg.png" /><figcaption>Components Decomposition.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24mYyudog6iQMImYRagRAw.png" /><figcaption>Differencing Code.</figcaption></figure><p>Argument of <strong>.shift() </strong>is adjusted accordingly to test on different order, d.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LANmRhfz5MLDxhBR7GegJQ.png" /><figcaption>Differenced Series.</figcaption></figure><p>Next, differencing is done on log-transformed series. Rolling mean and standard deviation are now fluctuating much slightly and can be said to be constant throughout the period. Stationarity is further proved by conducting Dickey-Fuller test, reporting a test statistics smaller than critical values at all three significant levels, rejecting null hypothesis. Modeling will be done based on stabilized series underwent log-transformation and differencing. Visualizations time series with differencing at 1,2,3 tell us d=1 is the best, having the consistent rolling mean and lower rolling standard deviation. What is the appropriate model? How to judge?</p><p><strong>Time Series Modeling</strong></p><p>This step is rather less complicated than previous part. We are considering mainly four types of classical time series models, autoregressive (AR), moving average (MA), Autoregressive–moving-average model (ARMA, combination of AR and MA) and finally Autoregressive Integrated Moving Average (ARIMA). We decide on differencing previously, ARIMA is opted so there is no extra step in creating substracted series needed. MA and AR can be constructed by setting the order of <em>ARIMA(p, d, q)</em>. By setting<em> p=0</em> and <em>q=0</em>, it is MA and AR respectively. Setting for <em>p</em> and <em>q</em> involve analysis on autocorrelation (ACF) and partial autocorrelation (PACF).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OajBBwyg7D_TLWvA1JNOTQ.png" /><figcaption>ACF and PACF Plots.</figcaption></figure><p>ACF measures correlation coefficient of time series and its series at lag <em>k</em>, means we are quantify correlation between <em>x(t) </em>and <em>x(t-k)</em>. PACF measures partial correlation between time series and its lagged values. Difference between ACF and PACF is, considering PACF at lag k, it takes into account correlation between data points at shorter lag <em>h</em> (<em>h&lt;k</em>). Some people tend to think of this as a regression problem. Taking <em>w=ax+by+xz</em>, PACF reports correlation between <em>w</em> and <em>z</em> that is remain unpredicted by <em>x</em> and <em>y</em>. Sharp drops in ACF and PACF determine values of <em>q</em> and<em> p</em> respectively. If both ACF and PACF decline gradually, ARIMA is opted. AR and MA models have been tested, their performances are not as good as combined model. Hence, adopting ARIMA here. From resulting ACF and PACF plots in this case, three combinations of ARIMA order, [ (2,1,1), (0,1,1), (2,1,2) ] will be trained and validated. Code below can be modified accordingly by changing argument ‘order’ for ARIMA().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*Zfc_9sncHuqBmDlCYkQoGg.png" /><figcaption>Code.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PmGZVapY1JbGQ2wwin9AZg.png" /><figcaption>Model Summary for ARIMA (2,1,2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*7WY6WwX3e0EFbb-ioCk3tg.png" /><figcaption>Performance Summary.</figcaption></figure><p><em>ARIMA(2,1,2)</em> has the lowest AIC among all three models, and all its parameters estimates are statistical significant. One point that worth noting is ARIMA(2,1,2) has much smaller difference between training and validating RMSE. We will go on with <em>ARIMA(2,1,2).</em></p><p>Model selected is refit with a complete set of training and validating data. Forecast will be made from the last point of time onwards. This is a time series data, it is not valid to skip the validation set. If you do skip, prediction for test data will be made based on the history that happened before validation set, which mean you gonna predict 2011 sales using 2009 sales. This is a multi-steps forecast problem. 12 months forecast will be done based on recursive forecasting, <em>X(t+2)</em> will be based on prediction for <em>X(t+1)</em> and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*N_MYN_R6QVeYCRFKuq9zBA.png" /><figcaption>Forecast for 01/2011–12/2011.</figcaption></figure><p>Predicted output obtained is same scale as log-transformed time series that is adopted in modeling. Reverse log-transformation to get final valid forecasts by taking exponential of model predicted values to convert it back to original scale.</p><p>The whole process involved rather subjective interpretation of plots with support from statistics theories. Python library, pmdarima provides us with methods called auto_arima. It will undergo iterations with range of values for each parameters and optimized based on some other arguments specified to find the best performing model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*iRIMQniCfKS408eUC-IvWw.png" /><figcaption>Code.</figcaption></figure><p><strong>Machine Learning Models</strong></p><p>Time series problem can be rephrased as supervised learning in ML, such that output in previous step will be input for next steps. Each data points is assumed to be independent as serial correlation between output has been accounted by creating new features for each record.</p><p>Classical time series models are still attractive and useful for solving our concerns after decades. Nevertheless, restructuring time series forecasting task into a machine learning problem is thought-provoking, due to the possibility of including more factors which are suspected to be contributor to changes in dependent variables. Predicting is no long depending only on history but it take into account other meaningful predictors from surroundings. For example, groceries sales show a noticeable spikes during festival seasons, so a boolean variable whether people celebrate on a particular day worth to be included as predictors. An example of how a new data frame can be created from this dataset is as follow and any regression model, such as linear regression, SVR, neural network, etc, can be experimenting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuqG2e9GEhPm6Fbn-QZ5Qg.png" /><figcaption>Example of DataFrame Creation for Supervised Learning</figcaption></figure><p>Please be noted, data splitting method will still be a concern as sequence of events is important.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5718b242648" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/sales-prediction-multi-steps-forecast-from-classical-time-series-models-to-machine-learning-models-b5718b242648">Sales Prediction: Multi-Steps Forecast from Classical Time Series Models to Machine Learning Models</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demonstrating Customers Segmentation with DBSCAN Clustering Using Python]]></title>
            <link>https://hshan0103.medium.com/demonstrating-customers-segmentation-with-dbscan-clustering-using-python-8a2ba0db2a2e?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2ba0db2a2e</guid>
            <category><![CDATA[unsupervised-clustering]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[density-based-clustering]]></category>
            <category><![CDATA[dbscan]]></category>
            <category><![CDATA[business-analytics]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 06:12:28 GMT</pubDate>
            <atom:updated>2021-03-06T09:01:03.431Z</atom:updated>
            <content:encoded><![CDATA[<h4>Density-Based Spatial Clustering Application with Noise (DBSCAN), an award-winning clustering algorithm that catches our eyes. Understanding what is DBSCAN and its application in customer segmentation, a critical area in business analytics.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-sJ6yO4XcIkRTKozI8oAg.png" /><figcaption>What is clustering?</figcaption></figure><p><strong>Intro</strong></p><p>We always try to focus on a subset rather than broad coverage of potential customers to optimize our business objectives by shrinking our target customers through customers segmentation effort. Recall customer segmentation via centroid-based clustering — K-Means, discussed in previous <a href="https://medium.com/swlh/exploring-customers-segmentation-with-rfm-analysis-and-k-means-clustering-93aa4c79f7a7">post</a>, there are some drawbacks associated with model applied that we may wish to minimize or even eliminate with goal of proposing more flexible or robust model as an alternative. In this piece of writing, we will be going through a density-based solution — DBSCAN, that overcome the issues.</p><p><strong>Why DBSCAN?</strong></p><p>Looking at clustering result from K-Means, every data point is assigned to a cluster and mean of points is centroid of each cluster. Thus, each point played their role in determining the cluster. In reality, it is not unusual to expect some data points to be deviated from ‘normal’, so called anomalies or outliers. Presence of a single outlier or minor change in a single point might distort entire clustering result. Besides, clusters form by K-Means is rather more spherical, problem arises if clusters are of other odd or elliptical shapes. Scree plot and silhouette plot serve as a guidance in deciding parameter k, but they are highly influential by model sensitivity to anomalies. Creation of a new approach intends to overcome complications of existing methods. DBSCAN deals or handles most downsides of K-Means.</p><p><strong>DBSCAN</strong></p><p>DBSCAN is density-based non-parametric unsupervised learning as well, we do not prescribe any model where data is from. Fewer assumptions, more flexible the model built, wider application. Similar to K-Means, DBSCAN is grouping data by their similarities based on distance functions and density. Density here means number of points in region defined by model parameters. Let us define terms used in explaining the process happening behind the scenes:</p><p>1. <em>eps </em>— define neighborhood of a point, <em>x</em>, or radius of a circle (or hypersphere in N-D space) with <em>x</em> as centre</p><p>2. <em>minPts</em> — minimum number of points in neighborhood to form a dense region</p><p>3. Core point — a point that has at least <em>minPts</em> data points within <em>eps.</em></p><p>4. Border point — a point that is within a dense region or a cluster but it is not a core point</p><p>5. Noise — not belong to any cluster</p><p>6. Directly density reachable — point <em>x</em> is directly density reachable from <em>y</em> if x is within <em>eps</em>-neighborhood of <em>y</em></p><p>7. Indirectly density reachable — point <em>x(1)</em> is said to be indirectly density-reachable(<em>eps, minPts</em>) from <em>x(n)</em> if there is a chain of points {<em>x(1)</em>, …, <em>x(n)</em>} such that <em>x(i+1) </em>is directly density reachable from <em>x(i)</em>.</p><p>8. Density connectivity — point <em>x</em> is density-connected(<em>eps, minPts</em>) from <em>y</em> if there is a point <em>z</em> such that both <em>x</em> and <em>y</em> are directly reachable from <em>z</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*ucmrRr3QpoqxzZvXPpOAqA.png" /></figure><p>DBSCAN partitions data such that dense region is separated by sparse region. It works with data of following characteristics:</p><p>· irregular clusters shapes</p><p>· different clusters sizes</p><p>· presence of outliers</p><p>Algorithm:</p><p>1. Randomly picking a point and check if it is a core point with <em>minPts</em> points in <em>eps</em>-neighborhood, form a cluster.</p><p>2. Run recursively on the points in neighborhood of a core point until all are visited, assigning density-reachable points as a cluster.</p><p>3. Iterate the process on remaining unvisited points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*-15_aekTt82CxfpxoGH2oA.gif" /><figcaption>Illustrating DBSCAN process. credit: <a href="https://www.digitalvidya.com/blog/the-top-5-clustering-algorithms-data-scientists-should-know/">https://www.digitalvidya.com</a></figcaption></figure><p><strong>Implementing DBSCAN</strong></p><p>Data is only useful if we try to dive into meaning behind the numbers. Data will only be a record if we do not analyze, digest and make it visible. After some brief introduction about DBSCAN, text below is demonstrating application of DBSCAN by adopting preprocessed real-world data from previous <a href="https://medium.com/swlh/exploring-customers-segmentation-with-rfm-analysis-and-k-means-clustering-93aa4c79f7a7">post</a>. Overall planning will be same, but this round DBSCAN will take over role of K-Means and be in-charge of doing partitioning task.</p><p>First, we need to estimate and specify parameters for DBSCAN, start by <em>minPts</em> and follow by <em>eps</em> using the former. If <em>minPts=1</em>, every data point will form a cluster by itself, means if we have n data, we gonna have <em>n</em> clusters. This does not make any sense for clustering to be done. If <em>minPts=2</em>, it will be same as single-linked hierarchy clustering. Hence, <em>minPts</em> should be set as <em>minPts ≥ D+1</em>. Nevertheless, by rule of thumb, it is set to be <em>minPts=2*D</em> below for simplicity. Moving forward,<em> eps</em> is determined from k distance graph. Mean distance from <em>k</em> nearest neighbors is computed and plotted against range from 1:n. The y value of point where ‘’elbow’ is spotted on the curve,<em> eps=0.7</em> for this case.</p><p><em>Python code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*us7rJaAMp9KGlXeetf6w3A.png" /><figcaption>code for determining parameter eps.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*xcINWnvdp7Bcbo-kIa6xWA.png" /><figcaption>k distance graph</figcaption></figure><p>Applying parameters estimated, a DBSCAN model is fitted and result is visualized in 3D plot. Note that black dots are anomalies detected, DBSCAN model in sklearn library will label as ‘-1’. Anomalies are spotted loosely distributed away from denser regions. Number of clusters and set of outliers are largely affected by parameters settings. Spotting ‘elbow’ might be subjective in some confusing cases, where curve does not show aggressive change of distance between successive points. So, it might be importance to note the possible or logic number of clusters to look for. Try to change parameters in this case, a large number of clusters might be obtained which is not too reasonable and digress from what we are interested in. One of the reason to explain the scenario is due to small sample size of processed data. Important characteristics or aggregated features for each cluster is then analyzed and summarized in snake plot below to aid business business decision making.</p><p><em>Python code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*PXBLL8JOZihd9tHI--vvkw.png" /><figcaption>code for fitting a model.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*owfydN6U06RWVVR58kQ8FQ.png" /><figcaption>code for visualizing clusters in 3D plot.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*nowTMu_mSIvCiiNtinJISQ.png" /><figcaption>3D plot. Black color points are anomalies detected.</figcaption></figure><p><em>Python code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOitlk8oMyobIykBHbx19w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*oRyRdmDLQSGbPt0iCnMzyQ.png" /></figure><p>Overall shapes in this snake plot is similar to Figure 6 <a href="https://medium.com/swlh/exploring-customers-segmentation-with-rfm-analysis-and-k-means-clustering-93aa4c79f7a7">here</a>, but look carefully into numbers recorded or plotted above, there are some differences. Slightly more obvious difference in ‘Monetary’. Cluster 2 is most economically valuable to business with the lowest ‘Recency’. highest ‘Monetary’ and ‘Frequency’. When goal of this task changed, the way how we look at this result should be updated to make sound business decision. For example, if business wish to retain potential churning customers or seeking targets for some new products or promotions, cluster with high ‘Recency’ grabs our attention, subsequently other cluster is selected instead of 2. A carefully and thoroughly planned analysis goal is crucial because it affects how data is processed and hence result will be highly impacted.</p><p><strong>DBSCAN vs K-Means</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RqtwgERyGeyEJ7RUn2YHJQ.png" /><figcaption>Comparing kmeans and dbscan.</figcaption></figure><p><strong>Conclusion</strong></p><p>Distance function is used to compute similarities between samples. Choices on parameters is made based on function selected. In simpler case, we manage to determine dense regions in scatter plots visually and intuitively. Such a phenomenon is pretty rare, especially as we are exposed to higher dimensional data or data without clear boundaries between dense regions. Although advantages of DBSCAN over K-Means is outlined, its result expected to deteriorate as data dimension is too big, problem of ‘curse of dimensionality’ comes in. Clustering result with data of different densities or loosely distributed will not be too decent or even departure from our goal. There are times the points fall in confusing regions of unclear boundaries, they may be grouped into either cluster. Understand data we have, choose model that is able to handle the data structures to get the most veracious result telling true story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2ba0db2a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abalone Sex Classification via Physical Measurements — R]]></title>
            <link>https://medium.com/swlh/abalone-sex-classification-via-physical-measurements-r-3b72526d5326?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b72526d5326</guid>
            <category><![CDATA[multiclass-classification]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[forecast-profitability]]></category>
            <category><![CDATA[multivariate-analysis]]></category>
            <category><![CDATA[wildlife-sustainability]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 08:40:31 GMT</pubDate>
            <atom:updated>2021-04-01T17:30:05.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abalone Sustainability and Profitability — Sex Classification and Weights Prediction from Physical Measurements via on R</h3><h4>Application of Multivariate Analysis and Classification on R. Forecasting profitability and enhancing sustainability through the weights and gender prediction by inspecting its physical size.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*lYwxr_UWtcvEsVMl" /><figcaption><em>Abalone diver, Tasmania.</em><strong><em> </em></strong>Photo: Stuart Gibson</figcaption></figure><p><strong>Intro</strong></p><p>Abalone is a type of marine snail with high nutrition values and economic values, almost whole abalone, including viscera and shell can be processed and serving as sources of income for fishing industry. High market demand for abalones has led to overexploitation, raising public’s concerns on environmental issues. Governments enforce strict law and regulations on abalones harvesting to ensure sustainability of abalones. Analyzing data to find relationship between multiples variables in data collected to aid innovation ideas in designing equipment as solution to both the profitability and sustainability through instant result provided underwater.</p><p><strong>Exploratory Analysis</strong></p><p>Dataset adopted here is modified data from research on population biology of abalones (1994), retrieving from UCI Machine Learning Respiratory. There are 4177 records, 9 variables and no missing value. Information on variables is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*XyZmhtBqPyRAnMTNC3LboA.png" /><figcaption>Table 1: Variables information.</figcaption></figure><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*Kg7xxpVIxKpPB9zIB_5H-w.png" /></figure><p>In the dataset, abalones are classified into three categories, F-female, M-male and I-Infant, such that “I” is prohibiting to be harvested to ensure sustainability of abalones population, while “F” and “M” bring has different economic values depending on the market trend. Descriptive statistics summary for numerical variables is presented below in Table 2 to give us the rough idea how the data look like.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiGMiCeVmuChvOxnxM8f1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*YM7tpPQel-GEINQD3CoGDQ.png" /><figcaption>Table 2: Statistics Summary for Numerical Variables.</figcaption></figure><p>“Height” of 0.0 is doubtful on reporting correctness. The ranges are varying a lot across data frame, minimum of 28.0 for “Rings” and maximum of 226.0 for “Whole weight”. The wide ranges are worth for attention as it may introduce bias to distance-based analysis result and modeling process. These two variables have the minimum and maximum standard deviation as well, implying spreading width of datapoints around their respective mean value. Difference between median and mean for all variables are within 6. It is noticeable that median is smaller than mean for “Length”, “Diameter” and “Height”. While for the rest, their mean is larger than median. This induces possibility of right skewness for the former and left skewness for the latter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*Jg5bEnLZrjKqBara9V3Eug.png" /><figcaption>Figure 1: Pairplots of All Variables for Different Sex Groups.</figcaption></figure><p>Figure 1, there are outliers seen on boxplots on first row for numerical variables from second columns onwards. Apparently, density plots for categories “F” and “M” appear overlapping over a large area. “I” can be better differentiated from the remaining two categories observing some characteristics as we can see some part of green area covered are apart from another two groups. Plots on diagonal are giving an initial idea of it might be challenging to differentiating “M” and “F” with very limiting dissimilarities on appearance features. “Height” has rather symmetric curves with long tails towards right, mainly due to present of outliers as shown in boxplots. Other variables distributions are skewed, first three numeric variables are exhibiting negative skewness, last five variables are positively skewed. The variables are highly but not perfectly correlated with correlation coefficient of more than 0.5, except pair of “Shucked weight” and “Rings”. Positive correlation implies that two variables values will move in the same direction. When one increases, another one increases, and vice-versa. Generally, “I” group samples are majority having smaller values for all variables available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*nTjXhWusKlxP9uCszQVmGA.png" /><figcaption>Figure 2: Countplot of “Sex”.</figcaption></figure><p>For categorical variable, “Sex”, number of samples of each category do not differ much, with maximum difference of 221 between “F” and “M”. Evaluation of metrics will not induce severe bias in judging model performance. But its appropriateness is questionable in some scenario, for example, if transforming it into to a binary problem, such as “I” or “Not I”. Thoroughly consideration required on deciding evaluation metrics and the cost associated with misclassification.</p><p>Data dimensions are expected not to be a challenge in this analysis, no dimension reduction approach will be applied, avoiding losing any useful information. Results in this section assist a quicker and more efficient decision on transformation required on subsets of data applied in constructing resolution to relevant problem.</p><p><strong>Discussion and Results</strong></p><p>Harvesting an infant abalone may cause endangered crisis to the population. Abalone of different sex has different body composition with distinct economic values. Discussion below will be fundamental idea supporting logic behind the equipment development.</p><p><strong>Part 1:</strong></p><p>This part aims to build model predicting “Sex” of abalones by measurement of their physical features, “Length”, Diameter” and “Height”. “Sex” is high influential to sustainability and profitability. Obviously, this is a classification problem, and it will be addressed with different methods, including multiclass classification and one-vs-all which transform a multiclass problem into multiple binary class problem. Linear discriminant analysis (LDA), quadratic discriminant analysis (QDA) and support vector machines (SVM) are proposed as solution to either type of classification problem.</p><p><strong>Data Transformation and Scaling</strong></p><p>Preprocess procedure, scaling and outlier eliminating is crucial especially for SVM as its distance-based model, to ensure consistent range of values and reduce impact of abnormal datapoints for all variables involved. The separating boundaries determine suitability of type of discriminant analysis to be adopted.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fmrt3PPk9JUyTADxE3GePQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz3hKApLs8C-wQsRVALNTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*60hC8Po0DhWiV4ExaEyAxg.png" /><figcaption>Figure 3: Pairplots of Transformed and Scaled Data.</figcaption></figure><p>Note the reduced outliers and skewness on transformed data. “Height” remains unchanged, as the curves are symmetric with few outliers lying far towards the right tail, expected the skewness is due to outliers. The ‘box’ of boxplots (1st quartile to 3rd quartile) for infant group (Green) lying near the edge of another two groups, without overlapping, this can be possible boundary identifying “I”. “I” samples with abnormally large variables values might be confusing on their “Sex”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*jylby6iEQ5NLzacVrMvaew.png" /><figcaption>Table 3: Statistics Summary for Transformed and Scaled Data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*eL9CgL-H6ojfq2HHyiRoPA.png" /><figcaption>Figure 4: Pairplots of Transformed, Scaled and Outliers Eliminated Data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*5cQea3b7I-U9zKqlqE0MbQ.png" /><figcaption>Figure 5: 3D Scatter Plot of Transformed Data with Different Group Combinations to Visualize Linearity of Boundaries (RMarkdown output should provide rotatable plots).</figcaption></figure><p>Decomposing 3D visualization of datapoints in Figure 5 show that “I” is separable from “F” and “M” to certain degree. “I” samples (Orange dots) appears mixing in samples of other groups at larger values, on non-diagonal plots. The first plot gives overview that “F” and “M” samples boundary linearity is doubtable. Hence, QDA might work better for distinguishing “F” and “M” than LDA.</p><p><strong>1.1</strong> <strong>Multiclass Classification</strong></p><p><strong>1.1</strong> <strong>Linear Discriminant Analysis (LDA)</strong></p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQN0T31NSguhEwXgwmtdZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*GNYRTsFumctDP9aBT19tPw.png" /><figcaption>Table 4: Confusion Matrix for LDA Classifier Built with Original Untransformed Data.</figcaption></figure><p>Original set of data (Sex ~ Length + Height + Diameter) achieved an accuracy of 0.5188 with LDA classification. This result will be used as benchmark for accessing models in this sub-section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*yiMjMNtOaGpJ7Tyw_-VAnQ.png" /><figcaption>Table 5: Confusion Matrix for LDA Classifier Built with Transformed Data.</figcaption></figure><p>It is observable that LDA with transformed data attained a slightly higher accuracy of 0.5250. This improvement in accuracy mainly due to more correctly classification and reduced misclassification for group “I”. There is still not much difference seen on classification performance for groups “F” and “M”.</p><p>There is a number of important assumptions to be met to validate application of model on the data:</p><p>· Multivariate normality</p><p>· Covariance equality</p><p>· Linearly separable Groups</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MPlgfpHe-UQLwXGSxjOyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*xcODwi2KZvvf9ZFhrv_W2A.png" /><figcaption>Table 6: LDA Assumptions Testing.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*lmGxZA4dbvKTaCwRZysu9A.png" /><figcaption>Table 7: Skewness and Kurtosis of Transformed Data.</figcaption></figure><p>Some skewness and kurtosis are not close to zero, all the statistics tests results are significant. None of the assumptions is fulfilled, LDA is not a good model. Due to the non-linearity concluded, next model proposed is QDA without strict assumptions.</p><p><strong>1.1.2</strong> <strong>Quadratic Discriminant Analysis (QDA)</strong></p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hv5rQ7SMoeQrzO3TtYlfHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*RKMY6XxXyyGauUgCzKei0A.png" /><figcaption>Table 8: Confusion Matrix for QDA Classifier Built with Transformed Data.</figcaption></figure><p>Significant increasing misclassification for “M” has deteriorated the overall accuracy to 0.519 which is lower than LDA. Nevertheless, both LDA and QDA accuracies level around 0.52 is less satisfying and they do not differ much.</p><p><strong>1.1.3</strong> <strong>Support Vector Machine (SVM)</strong></p><p>This is a distance-based model, not parametric model as LDA and QDA. There is no assumption on variable distribution, but it emphasizes on measurement scales. SVM recorded cross-validated accuracy of 0.5291, which is currently the highest. The increment is remained insignificant. Challenge in classifiying “F” and “M” might be main contributor to poor performance as we see earlier, this can be further proven by breaking down to binary scenario in next section. To current extend, SVM is the best model for multiclass classification.</p><p>Binary classification task will encounter imbalance class problem. Since there is no assumption made on cost associated with misclassification of each group, assuming it is equally important. F1 score finds the balance between precision and recall, it is adopted as metrics.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8On6eT-3CEatQX1DmKjuhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*LRGjnem5oJ7WAC3xS8Bj4w.png" /><figcaption>Table 9: Performance Evaluation for Binary Classification (“I” or “Not I”).</figcaption></figure><p><strong>1.2</strong> <strong>Binary Classification for “I”</strong></p><p>LDA assumptions are proven to be violated, hence we are not experimenting LDA on binary classification, “I” or “Not I”.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuz2mM1UXCRQprEpqXU5lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*vu91mXKe4WNix1WwIvuOzQ.png" /><figcaption>Table 9: Performance Evaluation for Binary Classification (“I” or “Not I”).</figcaption></figure><p>Logistic regression has the lowest accuracy but higher F1 score than QDA. SVM has the highest score for both accuracy and F1 score. Therefore, it is reasonable to justify that SVM is the model most capable in discriminating “I” out of all samples.</p><p><strong>1.3</strong> <strong>Binary Classification for “F”</strong></p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpLuSPgH5ms5LYUMFlw3JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*zWp-bkERlbDQFytnJ6mLmw.png" /><figcaption>Table 10: Performance Evaluation for Binary Classification (“F” or “Not F”).</figcaption></figure><p>Terrible performance on F1-score attaining maximum of 0.3 only. Among classifier experimented here, SVM has the worst F1 score, it is rejected and QDA with moderate accuracy and highest 0.33 is chosen. However, this is a poor result that is attainable by chance. It does not showcase predictive power of classifier.</p><p><strong>1.4 Binary Classification for “M”</strong></p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7FgVLepHjlk35gQlIMcWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd8iE1OGQI3tiF--4JVLWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*jQyeX5DVNHcYd59t0n8UWA.png" /><figcaption>Table 11: Performance Evaluation for Binary Classification (“M” or “Not M”).</figcaption></figure><p>SVM has lower accuracy but higher F1-score than logistics regression. Emphasizing F1-score due to imbalanced group data size and there is only 0.0017 difference in accuracy which is very minimal. SVM is chosen as best estimator.</p><p><strong>Result Summary:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*1BUSlsef57hmboSbzmrxaw.png" /></figure><p><strong>Part 2:</strong></p><p>This part focuses on profitability analysis based on its “Shucked weight” and “Viscera weight” which is regression problem. The company is seeking for solution to estimate abalone potential economic value from physical size “Length”, “Diameter” and “Height”. A model should be first built to predict “Shucked weight” and “Viscera weight”, and then forecasting economic value with application of linear combination of weights estimation and fluctuating prices.</p><p>Predictors: {Length, Diameter, Height}</p><p>Dependent Variables: {Shucked weight, Viscera weight}</p><p><strong>2.1</strong> <strong>Predicting “Shucked weight” and “Viscera weight” From “Length”, “Diameter” and “Height”</strong></p><p><strong>Data Transformation and Scaling</strong></p><p>Statistics summary for variables involved are summarized in Table2. Although “Sex” is not taking into consideration in this part, pair plots of data without distinguishing groups are similar to Figure 1, including skewness, correlation and outliers, observable in Figure 6. There are non-linear relationships spotted between dependent variables and predictors. Some transformations will be required to fit a good linear model on data, transformed result is attached in Figure 7.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIzhQLewpviObjZEpdpqqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*kg8aPJUPNsLmA7c71bZqew.png" /><figcaption>Figure 6: Pair plot of Original Data without Differentiating by “Sex” Class.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*CgDjeUbL3BqojCxinG-6jg.png" /><figcaption>Figure 7: Pair plots with Transformed and Outlier Removed Data.</figcaption></figure><p><strong>Multivariate Normality Tests</strong></p><p>Although transformed data fails all both multivariate and univariate normality tests, but more symmetric more normal-like shaped curves for transformed predictors than original dataset are seen on Figure 7. Despite of failing normality hypothesis testing, multivariate normality assumption for predictors is accepted by inspecting their distribution plots on diagonal.</p><p><strong>Multivariate Linear Regression Model Fitting</strong></p><p>Considering linear model for each dependent variable separately, all predictors are significant for both dependent variables. Each univariate linear model is explaining around 88% of variation in dependent variable. MANOVA result which analyzes multivariate linear model gives statistically significant result, highlighting importance of all predictors to be included.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMd6z4n46nzLpXu52izbmQ.png" /></figure><p><strong>Residual Diagnostics on MLR</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*K-epyl-NH9v2xB2KW220EA.png" /><figcaption>Figure 8: Decorrelated Residual Pairplot.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*BsaNJbIj4Dc2k3c4hYvaug.png" /><figcaption>Figure 9: Residual Plots</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*gsryUnEcnetQY7ZBpBX_cg.png" /><figcaption>Table 12: MLR Assumptions Testing.</figcaption></figure><p>Figure 9, red lines show small degree of curvature, there is a trend of how residuals are scattered. The MLR model residuals failed normality tests and has non-zero skewness and kurtosis, violating normality assumption on residuals. Nonetheless, residual density plots on Figure 8 show that the curves are rather symmetric with long tails towards both ends. Numerous outliers as marked in Figure 9.</p><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pr1vYO-74_h_tbo8CejmrQ.png" /></figure><p>Next model is built with those residual outliers removed to test their influential on model performance. Variation explained by each univariate linear model improves to 0.913 and 0.886 for “Shucked weight” and “Viscera weight” respectively. MANOVA gives significant result where all the estimates coefficient in linear model are non-zero. Residual diagnostics for this new model failed normality hypothesis tests as well, but with lower skewness and kurtosis achieved. Outlier is bringing negative impact to the previous model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*U6DMFB1oezWBE7pr9b7Hwg.png" /><figcaption>Figure 10: Residual Plots with Residuals Outliers for First Model Is Removed.</figcaption></figure><p>Although the model explains more variability in dependent variables, there is a higher degree curvature trend for residuals plots. Further removal of residual outliers has worsened the model, residual normality is still violated.</p><p>Consequently, due to constraints of limited extent of this analysis, combining experimental results above, outliers are the main reason of residual normality violation. The spread of symmetric curve with normal-like shape than untransformed predictors, around the peak is pretty similar on Figure 8. We accept residual assumption for multivariate linear model. The first multivariate linear model is adopted for forecasting weights, X. As stated earlier in data transformation section, we are assuming normal distributed transformed predictors. Therefore, given the transformed predictors, dependent variables are jointly normally distributed by applying property of multivariate normality.</p><p>Assuming sample size is large enough, sample mean vector and sample covariance matrix are good estimates of parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*HEcxdauSILc6zi62OC0DWA.png" /></figure><p><strong>2.2</strong> <strong>Profitability Index, S</strong></p><p>Adopting joint probability model for dependent variables, <strong>X</strong>, in previous section, <em>S</em> is modelled as univariate normal distribution by applying property of multivariate normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*JFtwsEERIsXO25J8mJmHqg.png" /></figure><p><em>R code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-52O-HJZS5wp0g8fh-yZw.png" /></figure><p><strong>Conclusion</strong></p><p>When the multiclass problem is transformed to several one-versus-all binary classifications, there is obvious difference between sample size for each category. It induces great amount of bias in modeling objective function. In this case, environmental sustainability should be emphasized for the cases to distinguish “F” and “I” out of the samples. It is suggested to include higher cost on misclassification for cases related to sustainability, as destroyed environment cannot be restored. Performance of classifiers built in this report are not too satisfying. Additional features including appearances characteristics, may be included to get a clearer boundary between “F” and “M”.</p><p>As for profitability analysis, the joint probability model for “Shucked weight” and “Viscera weight” follows normal distribution by assuming transformed predictors are normally distributed, despite of violation of a series of normality tests. As sample size is large, a number of outliers that cause slight departure from normality at the tails might distort the distribution and fail the tests. Further analysis on outliers is desired for better modeling or Copula method can be considered.</p><p>Discussions above are for learning and exploring purpose. A more proper workflow shall be planned and conducted to build and assess a valid model. Overall process may be modified, such as splitting dataset up into training, validating and testing sets or applying cross validation for estimating more accurate and convincing performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b72526d5326" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/abalone-sex-classification-via-physical-measurements-r-3b72526d5326">Abalone Sex Classification via Physical Measurements — R</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Define ‘Churned’ in Unsupervised Dataset?]]></title>
            <link>https://ai.plainenglish.io/how-to-define-churned-in-unsupervised-dataset-f621ef8f118e?source=rss-3f53bf89d0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f621ef8f118e</guid>
            <category><![CDATA[churn-definition]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[non-contractual-business]]></category>
            <dc:creator><![CDATA[Hshan.T]]></dc:creator>
            <pubDate>Sat, 16 Jan 2021 09:05:26 GMT</pubDate>
            <atom:updated>2021-03-03T07:09:09.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Define ‘Churned’ in Unsupervised Dataset for Retail Store and Non-Contractual Business?</h3><h4>How do we define ‘churned customer’? How to initialize a churn model building process when you have unlabeled or unsupervised data? Defining ‘Churned’ for Unlabeled Dataset might be more challenging than building a supervised predicting model with acceptable accuracy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*nvuLQkWET7pKnQum.jpg" /></figure><p>Often, when we try to build a machine learning model for churn prediction, we are provided with supervised dataset where ‘churn customer’ are identified and labelled. Why does business implement subscription, membership and contract based business model? Besides information collection including personal details and transaction details, customers management and spending behavioral analysis, they can identify leaving customers with certainty and apply the dataset in future to figure out factors affecting customers’ propensity to terminate services. Unrenewed membership, terminated subscription and contracts are the best churn indicators. Nonetheless, there are cases where data available is below our expectation. We do not have exact and complete information to label data, especially for retail business, non-subscription based, low purchasing frequency goods like furniture, etc.</p><p>Generally, a customer is said to be churned if it has been a while since his last purchase. The question is how do we defined the lapsed period? We do not expect a customer to return in short duration for low purchase frequency items. Hence, it is determined case-by-case and will be different for every analyst. Nevertheless, a subjective judgement on the length of time until he is said to be churned,<em> t, </em>will definitely leads to unfairness or inaccuracy in analysis.</p><p><em>t =analysis date, T — last purchase, l</em></p><p>It is especially crucial to be identify in a more scientific or analytic way to get a more trustable and convincing result. Instead of pre-defined <em>t</em>, an analyst might not be too particular about a fixed value, he may opt for computing the range of values where those with t beyond lower boundary will be classified as churned. This is application of percentile concept, since our goal is to find churned customers, we are looking at upper tail of the distribution of duration since last purchase. The problem with this alternative is, at what level should be the percentile? 95%? 97%? 99%? The solution to find the range is pretty straight forward if interval computation is done based on empirical distribution of t. However, diagnostic tests and judgement are required if distribution assumption about t is made. Other than challenge in determining the benchmark, such traditional way of churn analysis may take longer time. You might be missing the chance to retain customers.</p><p>Let’s look at approach that resolve some of the problem mentioned above. It has taken care of the situation where the product is low purchasing frequency item since we are considering distribution of all the lapsed period.</p><p><em>L = duration of time between two consecutive purchases</em></p><p>Next, compute <em>t</em> for each sample<em>, </em>and hence work to find maximum lapsed period, <em>D</em>, until it is so called churned.<strong> If t&gt;D, churned (c=1). If t&lt;D, not churned (c=0).</strong> Hence, extracting subset of samples with transactions done before <em>S=T-D, </em>so that there is mixed of samples with<em> c=0 </em>and <em>c=1.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*CdtZ2NM47uSqxHo8QPhlGg.png" /></figure><p>Recall conditional probability and, Type I and Type II error as we come across in statistics, we shall apply the concept here. We define errors as below:</p><p><strong>Null hypothesis</strong>: Sample is non churned.</p><p><strong>Alternative hypothesis</strong>: Sample is churned.</p><p><strong>Type I error</strong>: Reject null hypothesis when it is true.</p><p><strong>Type II error</strong>: Failed to reject null hypothesis when alternative hypothesis is true.</p><p><strong>e1</strong>= Probability classify non-churned as churned (False positive)</p><p><strong>e2</strong> = Probability classify churned as non churned (False negative)</p><p><strong><em>m = S - l</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*x0fQsXDBQJFEy8QXtTL6Ew.png" /><figcaption>Empirical conditional probability.</figcaption></figure><p><strong><em>d</em></strong><em> </em>is range of values where we are going to test. <strong>d = {0, 1, 2, …, H}</strong></p><p>Regardless whether there is transaction after S, we are looking at the reduced dataset and take the last transaction before S for each sample as <em>ls.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*PflpQwO7-FZ5-57mMKgQnQ.png" /><figcaption>Consider only reduced dataset with transactions before S.</figcaption></figure><p>Note that there is trade off between them. An effort to reduce type I error will cause an increment in type II error. We try to figure out the sweet point, Z, such that both the errors are minimized. This is also the point where total probability of errors is minimized. It should be the turning point on the error plot where it reached the bottom and revert back. Looking back at <a href="https://medium.com/swlh/telecommunication-churn-prediction-with-decision-tree-using-python-8106dddd0ded">this</a>, we mentioned in supervised learning about churned prediction, there is costs associated with misclassification which will impact the performance evaluation. Similar idea here, we do no have access to true labels but we can implement cost/weight associating each type of error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*MOI5b8Ekvzeg1b-d479x2Q.png" /><figcaption>minimization equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*RKNOZNPq66N_t9bzxavprg.png" /><figcaption>Plot of total weighted probability of errors against d. Expecting a curve with minimum point and reverse upwards beyond the point. The turning point is where we apply the value of d to define churned.</figcaption></figure><p><strong>Summarizing steps:</strong></p><ol><li>Generate data of lapsed periods between consecutive transactions. Identify the percentile of lapsed period, <em>D</em>.</li><li>Label the samples as churned if <em>T-l&gt;D</em> and non-churned if <em>T-l&lt;D. </em>Extract subset of samples with transaction(s) done before <em>S=T-D.</em></li><li>Select a domain of <em>d</em>, and compute the total probability of errors.</li><li>Plot total weighted probability of errors against <em>d</em>. Identify value of d where the curve attained lowest point. It is the lapsed period that defined churn.</li></ol><p><strong>Note:</strong> Domain of <em>d</em> can be adjusted according until we are able to identify the minimum point on the point. We will get different result by choosing different percentile level to get <em>D</em>. Analysis can be done to inspect whether d selected make sense or reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f621ef8f118e" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-to-define-churned-in-unsupervised-dataset-f621ef8f118e">How To Define ‘Churned’ in Unsupervised Dataset?</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>