<?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 Displayr on Medium]]></title>
        <description><![CDATA[Stories by Displayr on Medium]]></description>
        <link>https://medium.com/@displayr?source=rss-9a809f30fb0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SW5w_ouZ_wYiuAWrQn-Viw.jpeg</url>
            <title>Stories by Displayr on Medium</title>
            <link>https://medium.com/@displayr?source=rss-9a809f30fb0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:52:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@displayr/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[The Best Data Visualizations for Conjoint Analysis]]></title>
            <link>https://medium.com/@displayr/the-best-data-visualizations-for-conjoint-analysis-5836a3ef9166?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5836a3ef9166</guid>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Wed, 29 May 2019 03:47:33 GMT</pubDate>
            <atom:updated>2019-05-29T03:47:33.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you know what they are?</p><p>While choice-based conjoint analysis represents one of the more sophisticated techniques used in market research, presentation of its results commonly consists only of a simulator, and a few pie or bar charts. This leaves its users with only a limited understanding of the key patterns in the data. In this post I show key data visualizations that can be used to extract insight from conjoint studies: utilities plots, small multiples of histograms, correlation heatmaps, substitution maps, and indifference curves.</p><h3>Utilities (partworths) plots</h3><p><em>Utilities plots </em>are the oldest data visualization developed for conjoint analysis. They first appeared in the work of early leading light Paul Green, who referred to them as <em>plots of part-worth.</em> The plot has a number of nice features. First, it allows us to easily see the relative <em>importance </em>of the different attributes, which is defined as the difference between the utility of the highest and lowest levels of each attribute. Second, it makes it easy to see the relative appeal of different attribute levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*QowbQZ1shglcmwp8kr_MkQ.png" /></figure><p>Back in the 1970s and 1980s, charts like the one above were drawn by hand. However, they have fallen from popularity in the computer age, as the labels tend to obscure each other for studies with more than a few attributes. Today, they are typically drawn as bar charts, like in the example from the home delivery market shown below. Today, the utilities are typically shown as averaging 0 with an average importance of 100 (although it is unclear whether this is actually more advantageous).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*lmqBw4PdoSamwoOnGFrMZA.png" /></figure><h3>Small multiples of histograms</h3><p>While the utilities plots are a great way of seeing averages, most conjoint studies tend to focus on understanding opportunities relating to differences between consumers utilities. This is not shown on utilities plots. A better visualization is to show histograms of the distributions of utilities for each of the attribute levels, as is shown below. This example, which is from the same data as the earlier chocolate utilities, shows a number of features not evident in the utilities plot. For example, the utilities plot at the beginning of the post showed that Origin and Nuts are approximately equal in terms of average importance. However, the histograms below show that there is substantially more variation in terms of utilities for Nuts. This indicates that Nuts represent a strong opportunity for product ranging — brands should sell chocolates with nuts and without nuts — whereas Origin is more of a way of increasing overall appeal than an opportunity for segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*1plcSvlBA2TVNyO6v24Aig.png" /></figure><p>Keep in mind when viewing histograms like this that the variation in each attribute level is relative to the first level. For example, in the case of Nuts, it shows that there is no variation for Almonds, but this is because Almonds are set at 0 for all people, and the other levels are relative to Almonds. Thus, we can see in the case of Hazelnuts that people differ in their relative preference of Hazelnuts versus Almonds, but on average they prefer Almonds (as most of the distribution for Hazelnuts is to the left of Almonds). It can be useful to rearrange attribute levels (e.g., set No Nuts as the baseline level).</p><h3>Correlation heatmaps</h3><p>The histograms above are nice for showing the variation within an attribute, but correlation heatmaps are better for showing correlations between utilities. For example, looking at the top-left section, we can see that utilities for Godiva and Lindt are strongly correlated. Reading down the Godiva column (the second column), we can also see that people who prefer Godiva are less interested in sugar free and USA-origin chocolate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*JDNee8Q1122JI-H5zENa6Q.png" /></figure><h3>Substitution maps</h3><p>A practical problem with correlation heatmaps is that the attribute level that is fixed at 0 is not correlated with anything (as a variable with no variation cannot have any correlation). A simple hack that seems to solve this problem, but doesn’t, is to scale all the utilities to have a mean of 0 (as done in the bar chart utility plot). You do get correlations when you do this, but the correlations themselves largely reflect the mathematics of the scaling rather than the differences between people. A more principled approach is to use a simulator to change the appeal of a different alternative in such a way as to reveal patterns of substitution. From here, you can create a map like the one below. In this <a href="https://www.displayr.com/substitution-maps-understand-preferences-conjoint-analysis"><em>substitution map</em></a><em> </em>of the market for home delivered goods:</p><ul><li>The size of each circle indicates the <em>magnetism</em> of the different cuisines. So, all else being equal, people are most likely to switch to Pizza, followed by Chinese.</li><li>The closeness of different cuisines shows the relative degrees of switching between them, assuming equal magnetism. So, Indian is closest to Thai, and Thai is close to both Chinese and Indian.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Gm5IZ0e1ICwvp7oouLfYyQ.png" /></figure><h3>Indifference curves</h3><p><a href="https://www.displayr.com/indifference-curves-tradeoffs-conjoint-analysis">Indifference curves</a> show the trade-offs between two levels of ordered attributes. In the example below, the indifference curves show how people trade price per diner versus food quality when ordering home delivered food. Tracing the line from the bottom-right corner, which shows a rating of 3/5 for food quality and $10 for the meal, we can see that this has the same level of appeal as a rating of 4/5 at $15, and of a rating of 4.7/5 at $20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*jIsCPD7t6WhxzSOEgCLBrw.png" /></figure><p>Visualizations like these do a great job at summarizing all the patterns hidden in a simulator, allowing users of conjoint analysis to gain insight into the key ways that preferences in a market vary.</p><p><a href="https://www.qresearchsoftware.com/data-visualization-for-conjoint-analysis"><strong>Click here for all the interactive versions of these visualizations!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5836a3ef9166" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to Quickly Sift Through 3,050 Crosstabs and Find the Magic One]]></title>
            <link>https://medium.com/@displayr/3-ways-to-quickly-sift-through-3-050-crosstabs-and-find-the-magic-one-2dd4dab82207?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dd4dab82207</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[market-research]]></category>
            <category><![CDATA[crosstab]]></category>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Wed, 29 May 2019 00:53:27 GMT</pubDate>
            <atom:updated>2019-05-29T00:53:27.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Forget about the old-school highlighter and ruler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*nRLcCfXSJIVQKrpoo0-DZQ.png" /></figure><p>Most market researchers know the pain of having to hunt through huge numbers of crosstabs to find the interesting ones. In my younger days (shhh…), you would have to print out your crosstabs, read through them and using a pencil — or if you were more modern, a yellow highlighter and post-it-note(!) — to mark any interesting results. Believe it or not, some industry professionals still do this, but in Excel! If you’re one of these market researchers, don’t stress — this post will show you three ways you can save an enormous amount of time by automating the whole process.</p><p>The three approaches are: automatically deleting uninteresting crosstabs, creating a heatmap that summarizes lots of data, and a technique that we call <em>smart tables</em>. I know you’re raring to go but before diving into these approaches, we need to review some light “theory”, and explore the question of what makes a table interesting.</p><h3>What makes a table interesting?</h3><p>Two crosstabs are shown below. <strong>Which of these is interesting?</strong> If we are going to automate the process of sifting through crosstabs we need to decide what makes a table interesting. The simplest way to do this is to see if there are meaningful differences between the percentages, reading across the rows. But instead of manually having to read them all, you can automate the process using tests of statistical significance. In our example below, I’ve used colors to denote significant results. This can also be accomplished in different ways like having letters indicate which columns are different to which others. Looking at these tables, only one of them jumps out as “interesting” and I bet you picked it right away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*04Tq7f42tqZ8B2so.png" /></figure><h3>Approach 1: Automatically delete tables that have no significant results</h3><p>This approach is for those that love deleting things (and efficiency!). All you have to do is have your software automatically scan through all your tables and delete any that do not contain significant results — leaving you with only important ones. I’ve got 3,050 crosstabs. By deleting three-quarters of these, I’m saving myself heaps of time and energy. While this is a great way to quickly narrow down your results, you’ll need to be proficient at writing code to script this in R and SPSS. If the thought of writing code makes you wince, use Q or Displayr. They both automate this — meaning it’s a click away.</p><h3>Approach 2: Use a heatmap to summarize thousands of crosstabs</h3><p>While the first approach wins points for effectiveness and ease, it loses points for being binary. In this approach, tables are either black or white, significant or insignificant. There’s no allowance for shades of grey. Luckily, we can enter a technicolor world with an even more powerful approach. Introducing using heatmaps to summarize thousands of crosstabs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*paUQt1B1__wD0tigwY0CNg.png" /><figcaption><a href="https://www.qresearchsoftware.com/3-ways-to-quickly-sift-through-3050-crosstabs-and-find-the-magic-one">Click here for the full, interactive version.</a></figcaption></figure><p>The <em>heatmap </em>below summarizes 3,050 crosstabs. Each colored box shows the <em>degree </em>of statistical significance, where the degree in this case is something called a <em>z-</em>Statistic. Below, I describe a bit more about what the <em>z-</em>Statistic is, but for now, all we need to know is that the darker the box is shaded, the more the underlying table is significant. What can we gleam from this? For example:</p><ul><li>The first column shows how other questions in the study were related to agreeing with <em>Allows to keep in touch.</em> Reading down this column we can quickly see that agreement with this attitude can be predicted by <em>Work status, Occupation, </em>and <em>Age.</em> Reading across the rows we can see that there is no other attitude that is related to these three.</li><li>If we scroll down further (click on the image to see an interactive version) you will see a white diagonal line of boxes. This is showing the crosstabs of each attitude with each other. Putting aside the white, note how there are a lot more dark cells here. This tells us that the attitudes are highly correlated with each other. Also note however that there is a lot of variation. Some of the cells are much darker than others, telling us that we can likely group together similar attitudes (e.g., using PCA or cluster analysis).</li><li>Scrolling even further down, you will see that the blue gets very, very, pale for most, but not all, of the variables relating to behavior. We can see two things here. First, the attitudes and behavior in these examples are not closely related. Second, there are a small number of stronger relationships meriting more exploration (i.e., the very dark cells).</li></ul><h3>Why does the heatmap use z-Statistics?</h3><p>There are a few issues with the traditional approach of deleting tables that exceed the p-value cutoff for significance (0.05). One of the main issues is that, as they get smaller and closer to 0, it becomes difficult to compare them without having to squint at a lot of decimal places. In the table below, you can see the <em>p-</em>values in the third row of numbers. If you zoom in on the Strongly disagree column, the <em>p</em>-values could be a whole range of number like 0.003, or 0.000000001 — it’s simply impossible to tell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*cDju4oMDvcTvrDEU.png" /></figure><p>But wait, there’s a solution! The z-Statistics contain the same information as the <em>p-</em>value, except re-scaled to make comparison easier. Check the table below for a handy guide to converting<em> p</em>-Value to z-Statistic. The key value here is that difference between <em>p</em>-values of 0.0001 and 0.0000001 is much bigger when viewed as a z-Statistic making it much easier to understand practical differences the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*zo7qTSpic3CuFXQf.png" /></figure><h3>Approach 3: Smart Tables</h3><p>The third approach kind of combines the two approaches from above for the best of both. This bit of magic works as follows:</p><ul><li>First, you identify a specific question of interest. For example, if you are wanting to profile a segmentation, then you select the variable that indicates which person is in which segment.</li><li>Select any questions that may be of interest as crosstabs with the question of interest. If you aren’t sure, you just select all the variables.</li><li>Compute statistical significance for each of the crosstabs.</li><li>Delete all the tables that aren’t statistically significant.</li><li>Rank the tables according to statistical significance.</li></ul><p>An example of such an output, from Q, is shown below. Like with the heatmap, we end up with an output allows us to quickly identify the crosstabs of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qH9NmmT8y2-n2Utj.png" /></figure><p>We’ve written two related posts that tell you which buttons to click to run these analyses in Q and Displayr:</p><ul><li><a href="https://www.qresearchsoftware.com/3-approaches-to-quickly-sifting-through-3050-crosstabs-and-finding-the-important-ones-in-q">3 Approaches to Quickly Sifting through 3,050 Crosstabs in Q.</a></li><li><a href="https://www.displayr.com/2-approaches-to-quickly-narrowing-down-3050-crosstabs-and-spotting-the-important-ones-in-displayr">2 Approaches to Quickly Sifting through 3,050 Crosstabs in Displayr.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dd4dab82207" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get your Data Sparkling Clean — Fast!]]></title>
            <link>https://medium.com/@displayr/how-to-get-your-data-sparkling-clean-fast-e6e82f4c125e?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e82f4c125e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[survey-data]]></category>
            <category><![CDATA[data-scrubbing]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[market-research]]></category>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Wed, 29 May 2019 00:40:58 GMT</pubDate>
            <atom:updated>2019-05-29T00:40:58.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Get your Data Sparkling Clean — Fast!</h3><p>Ready to get your Marie Kondo on?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*empRV0djrGIXWzdmIub0tQ.gif" /></figure><p>Do you despise data cleaning? You’re not alone. Too many researchers find data cleaning to be time-consuming, tedious, and tiring. However, starting your analysis with a clean dataset that has rich metadata can make a world of difference. After all, you don’t want to be that researcher that finds out that their conclusions and insights were almost entirely based on errors during the data cleaning process, do you? Yikes.</p><p>We’re here to help — here is your guide to cleaning data! We’re going to cover:</p><ul><li>identifying problems and bad data by checking sample sizes, screening criteria, routing and filtering instructions, duplicates</li><li>cleaning your data from recording and rebasing values to fixing metadata to deleting dodgy respondents and more!</li></ul><p>So, let’s channel the queen of keeping things tidy, Marie Kondo, and get started. We might even spark some joy along the way.</p><h3>It all starts with a high-quality data file</h3><p>What do we mean when we say we want a high-quality data file? It sounds obvious, right?! Well, you might be surprised by the number of researchers working with unstructured files, or more frequently, metadata-poor datafiles (shudder).</p><p>Some common culprits of being metadata-poor are fixed column text files, comma-delimited text files, Excel files, CSV files, SQL databases, XML files, JSON text files, and HTML. Did you catch yourself using any of these files?</p><p>Then you’ll definitely want to consider switching to using metadata-rich data files. Rewind the clock and gain back your time by having variable metadata in your datafiles. After all, imagine all the time you’ll save not having to look-up and cross-reference information. The best metadata-rich files to use are SPSS .sav files and Q packs.</p><h3>Then we need to inspect the data</h3><p>It’s time to don our detective caps. Like all good detectives, we need to check a lot of our information and sources.</p><p><strong>Sample sizes</strong></p><p>Step one is to check our sample size. If your sample size is bigger than expected, then you probably have respondents with incomplete data polluting your survey.</p><p><strong>Screening criteria</strong></p><p>The next is to check your screening criteria worked as intended, and the fastest way to do so is with a Sankey Diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*_VIcvYLx5IO09NgXRkegmg.png" /><figcaption>Sankey Diagram for data checking</figcaption></figure><p>This Sankey Diagram lets us quickly distinguish between respondents who have been flagged as excluded from the quota and those that are complete and in quota — meaning that they were aged over 18, had a known gender, and consumed cola at least once a month. Now you could do the same thing with code or manually looking through crosstabs, but the Sankey diagram will save you a heap of time.</p><p><strong>Data quality</strong></p><p>What about the data quality for each question and variable? Here are some things to check for: poor-metadata, unusual sample sizes, outliers and other funky values, too small categories, incorrect variable types, and incorrect variable sets. <a href="https://www.qresearchsoftware.com/clean-survey-data"><strong>Check out the free eBook for more detail.</strong></a></p><p><strong>Routing and filtering instructions</strong></p><p>You’ll also want to check your routing and filtering instructions. You could scan through your raw data, but it’s time-consuming and easy to miss exceptions — especially if you have a large dataset. Here’s where the Sankey diagram comes in handy again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*LuwpR_m1DCWF9QMmcJgDaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bC5jryd0SuQe3crywehITA.png" /></figure><p>Our table shows that those of a full-time work status were asked for their occupation. However, our Sankey diagram immediately clues us into the fact that some students and part-time workers were also asked for their occupation — indicating a problem with our survey routing.</p><p><strong>Missing data patterns</strong></p><p>All right, are we finally done with checking things? Not quite, but don’t worry, the bulk of our data cleaning has already been done. Now we’ve got to check for missing data patterns. The best way to do this is –surprise, surprise — visually. We’re going to create a heatmap or line chart that shows the missing values for each observation, with each ‘column’ representing a different variable and lines representing missing values — and if we’re lucky it’s not going to resemble a Jackson Pollock painting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*EN9CScVFDB4I1MRT2R8htg.png" /><figcaption>Plot your Missing Values by Case ID</figcaption></figure><p>Different lines or clusters of lines indicate different problems with missing data. For example, long horizontal lines (highlighted on the left) can indicate observations with severe missing data issues. <a href="https://www.qresearchsoftware.com/clean-survey-data"><strong>See the eBook for more details.</strong></a></p><p><strong>Duplicates</strong></p><p>Duplicates can be a serious problem. Sometimes you can find them just by analyzing the ID variables. Other times you’ll need to jointly analyze sets of variables.</p><p><strong>Unit tests</strong></p><p>It’s also super useful to set up some unit tests to automate the process of checking for errors. This is an especially good investment when it comes to longitudinal or tracking projects as unit tests can automatically check key things whenever new data is uploaded. Some common things to test for in unit tests include: out of range errors, flow errors, variable non-response, variable consistency errors, lie tests, and sum constraint errors.</p><h3>And finally — clean the data!</h3><p>We’ve now spent a bit of time looking for problems. Now it’s time to get our Marie Kondo on and finally fix them up. On an individual level, we can edit problematic values. By changing all occurrences of specific values to other values, we can recode or rebase our data.</p><p><strong>Recoding and rebasing</strong></p><p>Often you may want to set inconsequentially small values of “don’t know” to be missing values. This tells your analysis software to automatically filter the table and recompute the values with the “don’t knows” excluded. This is also known as rebasing. Other common ways of recoding values include capping and re-aligning values with your labels.</p><p><strong>Merging categories</strong></p><p>You can also merge small categories. In some software, this is regarded as another example of recoding. In Q or Displayr, merging is considered a separate process, since merging does not affect the underlying values of data.</p><p><strong>Fixing metadata</strong></p><p>Typically, you can fix metadata by adding or correcting labels.</p><p><strong>Deleting respondents</strong></p><p>When a respondent’s data is deemed non-useful (whether it’s because they flat lined or had too many missing values etc.) we delete that row of the data file. The most useful way to do so it via filters.</p><p>Nice work, your data should be in tip-top, sparkling clean shape now! <a href="https://www.qresearchsoftware.com/clean-survey-data"><strong>Download our free eBook for loads more detailed information and specific steps for how to do this in Q, Displayr, R and SPSS.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e82f4c125e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Trees Are Usually Better Than Logistic Regression]]></title>
            <link>https://medium.com/@displayr/decision-trees-are-usually-better-than-logistic-regression-474f2ab8f943?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/474f2ab8f943</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 17:00:53 GMT</pubDate>
            <atom:updated>2018-10-25T22:25:18.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*VmF-1JFYz3x5hTFM.png" /></figure><p><strong>If you’ve studied a bit of statistics or machine learning, there is a good chance you have come across <em>logistic regression</em> (aka <em>binary logit</em>). It is the old-school standard approach to building a model where the goal is to predict an outcome with two categories (e.g., Buy vs Not Buy). If you are a good statistician with a lot of time on your hands it is a great technique. But for everybody else, it has been superseded by various machine learning techniques, with great names like </strong><a href="https://www.displayr.com/what-is-a-random-forest/"><strong>random forest</strong></a><strong>, </strong><a href="https://www.displayr.com/gradient-boosting-the-coolest-kid-on-the-machine-learning-block/"><strong>gradient boosting</strong></a><strong>, and </strong><a href="https://www.displayr.com/what-is-deep-learning/"><strong>deep learning</strong></a><strong>, to name a few. In this post I focus on the simplest of the machine learning algorithms — decision trees — and explain why they are generally superior to logistic regression. I will illustrate using CART, the simplest of the decision trees, but the basic argument applies to all of the widely used decision tree algorithms.</strong></p><p><a href="https://app.displayr.com/creator/machine%20learning/classification%20and%20regression%20trees%20(CART)"><strong>Create your own CART decision tree</strong></a></p><h4>Logistic regression’s big problem: difficulty of interpretation</h4><p>The main challenge of logistic regression is that <a href="https://www.displayr.com/?p=9828&amp;preview=true">it is difficult to correctly interpret the results</a>. In this post I describe why decision trees are often superior to logistic regression, but I should stress that I am not saying they are necessarily statistically superior. All I am saying is that they are better because they are easier and safer to use. Even the most experienced statistician cannot look at the table of outputs shown below and quickly make precise predictions about what causes churn. By contrast, a decision tree is much easier to interpret.</p><p><a href="https://embedded.azureedge.net/75668/295893/06c22408-5116-44a6-ab1f-24306dc55bde.html?v=32413;-d3b24494c8;;-949569144">https://embedded.azureedge.net/75668/295893/06c22408-5116-44a6-ab1f-24306dc55bde.html?v=32413;-d3b24494c8;;-949569144</a></p><h4>Decision trees: the easier-to-interpret alternative</h4><p>The decision tree below is based on an <a href="https://community.watsonanalytics.com/wp-content/uploads/2015/03/WA_Fn-UseC_-Telco-Customer-Churn.csv">IBM data set</a> which contains data on whether or not telco customers <em>churned </em>(canceled their subscriptions), and a host of other data about those customers. The decision tree shows how the other data predicts whether or not customers churned. This is an interactive visualization that allows you to hover, zoom, and collapse things by clicking on them (best viewed on a desktop).</p><p><a href="https://embedded.azureedge.net/75668/295893/1258306b-b4b9-4c7f-988f-55846aa32f2d.html?v=32413;-d3b24494c8;;-1155606871">https://embedded.azureedge.net/75668/295893/1258306b-b4b9-4c7f-988f-55846aa32f2d.html?v=32413;-d3b24494c8;;-1155606871</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*ZvKMiudgx0EmZmpo.png" /></figure><ul><li>The single best predictor of churn is contract length. We know this because it appears on the far left.</li><li>People with a month-to-month contract are different from those with a one or two year contract. The type of decision tree I have used (CART) always splits into two categories. Because one and two years have been combined we know that the difference between these two groups is less than their difference to month-to-month. It does not necessarily mean that there is no difference between one and two year contract people in terms of their propensity to churn. The decision tree could, if the data warranted, split people further on in terms of one and two year contracts.</li><li>People with a one or two year contract are less likely to churn than those with a month-to-month contract. We can see this by the color shading, where bluer means more likely to churn and redder means less likely to churn. If you hover your mouse over the <em>nodes, </em>which are the grey vertical rectangles, you can see the underlying data, as shown to the right, which tells us that people on a one or two year contract have only a 7% chance of churning.</li><li>There are more people on a month-to-month contract than are on a one or two year contract. We know this because the corresponding “branch” of the tree is thicker. We can also see the number of people by hovering over the node.</li><li>If we know somebody is on a one or two year contract, that is all we need to know. The predictions of the model do not require splitting this branch further.</li><li>Among the people on a one month contract, the best predictor is their internet service, with people on a fiber optic service being much more likely to churn (again, we can see this both by the blueness of the branch, and if we hover over the node).</li><li>Among people with a month-to-month contract who have a fiber optic connection, if their tenure is 15 months or less, they are likely to churn (69%), whereas those on the fiber optic plan with a longer tenure are less likely to churn.</li></ul><p>In this manner we can continue explaining each branch of the tree.</p><h4>Decision trees are safer</h4><p>The problem of logistic regression being hard to interpret is much more serious than it first appears. As most people are not able to interpret it correctly, they end up not even noticing when they have stuffed it up, leading to a double boo-boo, whereby they inadvertently create a model that is rubbish, which they then go on to misinterpret. Am I talking about you? Are you using <a href="https://www.displayr.com/what-is-feature-engineering/">feature engineering</a> to ensure that the linear model isn’t a problem? Did you use an appropriate form of imputation to address missing data? Are you controlling your family-wise error rate or using regularization to address forking paths? How are you detecting outliers? Are you looking at your G-VIFs to investigate multicollinearity? If you are reading this and thinking “what?”, then the options are to go back to graduate school and invest in some stats learning, or say goodbye to logistic regression and replace them with decision trees.</p><p>The great thing about decision trees is that they are as simple as they appear. No advanced statistical knowledge is required in order to use them or interpret them correctly. Yes, sure, there are ways you can improve them if you are an expert, but all that is really required to be successful when you use them is common sense.</p><h4>Decision trees predict well</h4><p>With the data set used in this example I performed a test of predictive accuracy of a standard logistic regression (without taking the time to optimize it by feature engineering) versus the decision tree. When I performed the test I used a sample of 4,930 observations to create the two models, saving a further 2,113 observations to check the accuracy of the models. The models predicted essentially identically (the logistic regression was 80.65% and the decision tree was 80.63%). My experience is that this is the norm. Yes, some data sets do better with one and some with the other, so you always have the option of comparing the two models. However, given that the decision tree is safe and easy to understand, this means that, to my mind, it is always the safer alternative.</p><p>However, if your focus is solely on predictive accuracy, you are better off using a more sophisticated machine learning technique, such as random forests or deep learning.</p><h4>So why, then, are logistic regressions better known than decision trees?</h4><p>In addition to the benefit of being a lot older, logistic regression is, if you have a lot of time and expertise, pretty cool and does some things a lot better than a decision tree. Consider, for example, the role of tenure shown below. The decision tree tells us that if somebody is on a month-to-month contract, with DSL or no internet service, the next best predictor is tenure, with people with a tenure of 6 months or more having an 18% chance of churning, compared to a 42% chance for people with a tenure of less than 6 months. As far as predictions go, this is a bit blunt. It seems unlikely that 6 months is the magical cutoff. A more likely explanation is that the real situation is that the likelihood of churn drops a little for every additional month of tenure. Decision trees simplify such relationships. A logistic regression can, with appropriate <a href="https://www.displayr.com/feature-engineering-for-numeric-variables">feature engineering</a>, better account for such a relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*ah0NQ5pYmmQTW0oe.png" /></figure><p>A second limitation of a decision tree is that it is very expensive in terms of sample size. Each time it splits the data using a predictor, the remaining sample size reduces, and eventually gets to a stage where there is not enough data to identify further predictors. However, it is likely that some of these further predictors are still relevant. By contrast, logistic regression looks at the simultaneous effects of all the predictors, so can perform much better with a small sample size. The flip side of this is that often effects are sequential rather than simultaneous, in which case decision trees are much better. The decision tree shown in this post is a good example of a case where such a sequential relationship likely does make more sense; if somebody is on a contract they are locked in and other predictors are likely not relevant (and would incorrectly be assumed to be relevant if applying typical logistic regression).</p><p>Another weakness of decision trees is that they have their own potential for misinterpretation, with many people incorrectly assuming that the order with which predictors appear in a tree tells you something about their importance. Unfortunately, this is often not the case. For example, if you have two highly correlated predictors, only one of them may appear in the tree and which one it is will be a bit of a fluke.</p><p>The consequence of all of these strengths of logistic regression is that if you are doing an academic study and wanting to make conclusions about what causes what, logistic regression is often much better than a decision tree. However, if instead the goal is to either make a prediction, or describe the data, then logistic regression is often a poor choice.</p><p><a href="https://app.displayr.com/creator/machine%20learning/classification%20and%20regression%20trees%20(CART)"><strong>Create your own CART decision tree</strong></a></p><h4>Technical details</h4><p>There are lots different algorithms for creating decision trees. In this post I have used a classification tree, created in Displayr using <strong>Insert &gt; Machine Learning &gt; Classification And Regression Trees (CART)</strong>. There are also a number of different ways of showing decision trees; in this post I am showing the decision tree as a <em>sankey diagram, </em>which is I think the best way (but is not the most common way) of showing decision trees.</p><p>When creating a regression tree a decision needs to be made about how big the tree should be. If the goal of the logistic regression is predictive accuracy, it is usually advisable to create the tree that maximizes predictive accuracy based on cross-validation. In Displayr, this is is achieved by setting <strong>Pruning </strong>to <strong>Minimum error</strong> (which is the default).</p><p>If the goal when creating a decision tree is to describe the data, focusing more on what has happened in the past than on predicting what will happen in the future, it can be useful to either:</p><ul><li>Create a smaller tree, if the one that maximizes predictive accuracy is too big. One way to do this is set <strong>Pruning </strong>to <strong>Smallest tree</strong>, which finds a relatively small tree with relatively good predictive accuracy</li><li>Create a bigger tree, if the one that maximizes predictive accuracy is too small. This can be done by setting <strong>Pruning </strong>to <strong>None</strong>. Keep in mind if selecting this option that there is a good chance that some of the relationships that appear in the smaller branches will be flukes.</li></ul><p><strong>Have we convinced you? Create your own decision tree </strong><a href="https://app.displayr.com/creator/machine%20learning/classification%20and%20regression%20trees%20(CART)"><strong>here</strong></a><strong>!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/decision-trees-are-usually-better-than-logistic-regression/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474f2ab8f943" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering for Categorical Variables]]></title>
            <link>https://medium.com/@displayr/feature-engineering-for-categorical-variables-e11f05a1d560?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e11f05a1d560</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 17:00:38 GMT</pubDate>
            <atom:updated>2018-10-26T04:01:43.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*t2bHjDoID2WyTrnn.jpeg" /></figure><p><strong>When creating a predictive model, there are two types of predictors (features): <em>numeric variables</em>, such as height and weight, and <em>categorical variables</em>, such as occupation and country. In this post I go through the main ways of transforming categorical variables when creating a predictive model (i.e., <em>feature engineering </em>categorical variables). For more information, also check out </strong><a href="https://www.displayr.com/feature-engineering-for-numeric-variables"><strong>Feature Engineering for Numeric Variables</strong></a><strong>.</strong></p><p>In this post I work my way through a simple example, where the outcome variable is the amount of gross profit that a telco makes from each of a sample of 917 of its customers, and there are two predictors: industry and the turnover of the company. The goal of the predictive model is to identify which industries and company sizes to focus its efforts on. Tables showing the proportion of customers in each of the categories for the two features (aka <em>predictor variables</em>) are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*ePcs6Z_HtFhanPZ3.png" /></figure><h4>Using the predictive model’s in-built tools for categorical variables</h4><p>The simplest approach to analyzing such data is to just select the predictor variables in whatever software you are using and let the software decide to automatically treat the data how it wants. If you are using well-written software this will often be an OK option, and will likely use <em>one-hot encoding</em> in the background.</p><p>The table below shows the r-squared statistics for both a <em>linear regression</em> and a <em>random forest</em>. The random forest does a much better job at predicting profit with the data used to fit the models (this is shown in the <strong>In-sample R2</strong> column). This is not surprising, as this model is much more flexible, so can typically fit a specific data set better than a standard linear regression. However, in data not used to fit the model, this result reverses, with the regression performing better. In both cases the out-of-sample accuracy is much, much, worse. (See <a href="https://www.displayr.com/how-to-do-logistic-regression-in-displayr/">How to do Logistic Regression in Displayr</a> for a discussion regarding the need for saving data for use in checking a model). This is a general issue with categorical predictors: the more categories, the more likely the models will over-fit (produce much better in-sample than out-of-sample fits).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*XRic455FKg6GCldF.png" /></figure><h4>Treating the predictors as numeric variables</h4><p>An alternative to treating the data as categorical is to treat it as numeric. This entails assigning a value of 1 to the first category, 2 to the second category, and so on (e.g., 1 to Accommodation, Cafes &amp; Restaurants, a 2 to Agriculture, Forestry &amp; Fishing, etc.). The bottom two lines of the table below show the results of the models when the variables are treated as numeric. After this feature engineering, the linear regression essentially fails, with an r-squared of 0 in the data used to estimate the model and an error when computing the out-of-sample fit (the model produced worse-than-random predictions). The random forest does better, but the out-of-sample fit is substantially worse. We can learn from this that it is important to avoid unintentionally treating categorical predictors as numeric variables when creating predictive models (this may sound obvious, but it can be easy to do this inadvertently if you do not know to avoid the problem).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*nzablIoecYXd_ol3.png" /></figure><h4>Judgmental encodings</h4><p>There is an obvious ordering to the turnover categories below. An alternative way of analyzing the turnover data is to treat it as numeric, but use judgment to assign values to the data. For example, we could use consecutive integers, assigning a 1 to the lowest category, a 2 to the next lowest, and so on. Alternatively, we could assign midpoints or some other value. In the two tables below I have assigned values to each of the two predictor variables. In the case of the turnover data, the judgments seem reasonably sound to me (other than for <strong>Missing data</strong>), but for the industry data the encoding has little more than guesswork to justify it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*ZCjiSB3Jqx6M8-cW.png" /></figure><p>When coming up with your own encodings, there are a few rules:</p><ul><li>The results of predictive models are not super-sensitive to the choices. For example, we could assign a value of 0, .05, or 1 to the <strong>Less than $100,000 </strong>category and it will make no difference, and even with the <strong>Over $10 million </strong>category, any of 10, 15, or 20 will likely not make a huge impact.</li><li>You should <em>not </em>look at relationship between the predictor variable and the outcome variable when forming the encoding. If you do, you will overfit your model (create a model that looks good initially but predicts poorly).</li></ul><p>The results of the models with the judgmental encoding are shown below. Each of these models are relatively poor in-sample. This is to be expected, as the models with numeric predictor variables are less flexible. However, the out-of-sample performance of these two models is the best we have seen. It is pretty common to find this type of result: incorporating judgment into modeling tends to lead to better models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*fdxixAoQx2d7M_CS.png" /></figure><h4>Mixed judgment and categorical</h4><p>The judgments regarding the encoding of turnover are relatively easy to defend. The ones made about industry are not. This suggests we should consider treating industry as a categorical variable, but use turnover with its judgmental encoding. The resulting two models are shown at the bottom of the table below. Looking at the in-sample r-squareds, we can see that the random forest has improved markedly on the training data, as now it can explore all possible combinations of industry and how they interact with turnover. However, its out-of-sample performance has become abysmal. By contrast, the best of the models is now our regression model, with the categorical industry and judgmentally-encoded turnover. This highlights an important practical issue with feature engineering: its effect varies depending on which predictive algorithm we use.</p><p>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*hBITubLGnTm344UH.png" /></figure><h4>Merging categories</h4><p>The massive degree of overfitting we are seeing with the random forest is because we have so many categories of industry, which leads to too many possible ways of combining industry together. We can limit the number of possible combinations by using judgment to merge some of the categories. I’ve used my own judgment to merge the categories as shown in the table below. For the same reasons described in the earlier section on judgmental encodings, it is important <em>not </em>to look at the outcome variable when working out which categories should be merged. By contrast, it is appropriate to look at the sizes of the categories, as categories with small samples tend to be unreliable and often benefit from being merged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*K23DeIkEU84Wo591.png" /></figure><p>The in-sample r-squared of both the regression and the random forest declines. This is to be expected. By merging the categories we have guaranteed that the in-sample fit will decline. In the case of the random forest, the out-of-sample r-squared is better than the previous model, suggesting that the merging of the categories was not completely hopeless. However, the best model remains the regression model with all the industry categories and the judgmentally-encoded turnover variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*tIVlwyt8UbTQ9fi8.png" /></figure><h4>Interactions</h4><p>An <em>interaction </em>is a new variable, or set of variables, created by multiplying together predictor variables. To explain how they work with categorical variables it is necessary to delve a little into the detail of how predictive models deal with categorical variables.</p><p>The industry variable has 16 categories and the turnover variable has nine. When most (but not all) machine learning and statistical methods analyze a categorical variable they perform <em>one-hot coding </em>in the background. In the case of our 16 categories for industry, what this means is that 15 numeric variables are created and included in the model, one for all but the first of the categories. These are given a value of 1 when the data contains that category and a value of 0 otherwise. (Such variables are also known as <a href="https://www.displayr.com/what-are-dummy-variables/"><em>dummy variables</em></a><em>.</em>) So, when we are estimating our model with industry and turnover, we are estimating 15 and 8 variables in the background to represent these two categorical variables.</p><p>A standard interaction of industry by age would create 16 * 8 = 128 variables in the background (it’s actually a bit more complicated than this, but hopefully you get the idea). This considerably improves the in-sample fit, but tends to raise lots of problems in the out-of-sample predictive accuracy, as often combinations of categories that exist in the data used to estimate the model do not exist in the data set used to validate the model, and vice versa. The solution, then, when you have categorical variables with large numbers of categories and wish to create interactions, is to use merged variables when creating interactions and/or numerically encoded variables.</p><p>While you can create the interactions by hand, most predictive modeling software has automatic tools to make this easy. In Displayr, we do this by editing the R code (<a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector</a> &gt; <strong>Properties &gt; R CODE</strong>), and adding a * or a : to the formula, as can be seen in the screenshot below (see <a href="https://www.displayr.com/feature-engineering-for-numeric-variables">Feature Engineering for Numeric Variables</a> for the distinction between : and *).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XT8DcmlsUyVPHamc.png" /></figure><p>The resulting model, shown at the bottom of the table has the best out-of-sample r-squared of all of the models considered so far. The out-of-sample r-squared is as good as the in-sample r-squared, but this is just good luck and is not the norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*RC6CijxMf1lhB83_.png" /></figure><p>This post has provided a tour of some of the options for engineering categorical variables (features) when creating predictive models. The interesting thing to note is the substantial impact that can be achieved by judiciously transforming categorical variables, with the resulting model substantially better than the default models that can be obtained without transforming the data.</p><p><a href="https://app.displayr.com/try/Feature%20Engineering%20Categorical"><strong>Explore the original dashboard</strong></a></p><p>If you want to look at the various analyses discussed in this post in more detail (e.g., looking at the coefficients of all the models), <a href="https://app.displayr.com/try/Feature%20Engineering%20Categorical">click here</a> to view the Displayr document that contains all the work. If you want to reproduce these analyses yourself, either with this data or some other data, please check out:</p><ul><li><a href="https://www.displayr.com/how-to-do-logistic-regression-in-displayr/">How to do Logistic Regression in Displayr</a></li><li><a href="https://www.displayr.com/feature-engineering-in-displayr/">Feature Engineering in Displayr</a></li><li><a href="https://www.displayr.com/feature-engineering-for-numeric-variables">Feature Engineering for Numeric Variables</a></li></ul><p><strong>Click the button above to edit and explore the original analyses!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/feature-engineering-for-categorical-variables/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e11f05a1d560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do Logistic Regression in Displayr]]></title>
            <link>https://medium.com/@displayr/how-to-do-logistic-regression-in-displayr-338340750ee5?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/338340750ee5</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 17:00:34 GMT</pubDate>
            <atom:updated>2018-10-26T04:01:36.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*DWH038jyu3Wro40e.png" /></figure><p>This is a practical guide to logistic regression. To get the most out of this post, I recommend you follow along with my instructions and do your own logistic regression. If you’re new to Displayr, click the button below and add a new document!</p><p><a href="https://app.displayr.com/SignUp?plan_id=0">Get started!</a></p><h4>Step 1: Importing the data</h4><p>We start by clicking the + Add a data set button in the the bottom-left of the screen in Displayr and choosing our data source. In this example I am using a data set available on IBM’s website, so we need to:</p><ul><li>Select the <strong>URL</strong> option.</li><li>Paste in the following as the URL (web address): <a href="https://community.watsonanalytics.com/wp-content/uploads/2015/03/WA_Fn-UseC_-Telco-Customer-Churn.csv">https://community.watsonanalytics.com/wp-content/uploads/2015/03/WA_Fn-UseC_-Telco-Customer-Churn.csv</a></li><li>Set the automatic refresh to 999999 (to stop the data being re-imported and the model being automatically revised).</li></ul><h4>Step 2: Preliminary data checking</h4><p>In order to build a logistic regression we need to decide which <em>predictor variables</em> (aka <em>features</em>) we wish to use in the model. This is a whole topic in itself, which I am going to side step in this post, by asserting that the predictors we want to use are the ones called <strong>SeniorCitizen</strong>, <strong>tenure</strong>, <strong>InternetService</strong>, <strong>Contract</strong>, and <strong>MonthlyCharge</strong>. The <em>outcome variable </em>to be predicted is called <strong>Churn</strong>. To perform a preliminary check of this data, hold down the control key and click on each of these variables (you should see them in the Data Sets, at the bottom-left of the screen — see below). Once they are selected, drag them (as a group) onto the page. Your screen should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F-a6-y37SqqKvFH8.png" /></figure><p>The specifics of how to perform a preliminary check of the data depend very much on the data set and problem being studied. In this section I am going to list what I have done for this case study and make some general comments, but please keep in mind that different steps may be required for your own data set. If you have any specific things you aren’t sure about, please <a href="https://www.displayr.com/contact-us/">reach out to me</a> and I will do what I can.</p><ul><li>The outcome variable, shown at the bottom-right, contains two categories, No and Yes. As (binary) logistic regression is appropriate with two categories, all is in order with this variable.</li><li>Looking at the footer of the table, if you squint you will see that it shows a sample size of 7,043. Further, it mentions nothing about missing data (if there was missing data, it would be indicated in this footer). Looking at the other five tables, we can see that none have missing data, so all is good. If we had missing data we would have to make some enquiries as to its cause.</li><li>The first of the tables, for the SeniorCitizen variable, shows values of 0 and 1 as the row names. In this case a 1 means the person is a senior citizen, and a 0 means that they are not. To make the resulting analysis a bit neater I:</li><li>Clicked on the SeniorCitizen variable in the Data Sets tree.</li><li>Changed its label to Senior Citizen (i.e., added a space) under <strong>GENERAL &gt; Label </strong>in the <a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector.</a></li><li>Pressed the <strong>DATA VALUES &gt; Labels button </strong>in the <a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector</a> and changed the 0 to No and the 1 to Yes in the <strong>Label </strong>column and pressed <strong>OK</strong>. The table will automatically update to show the changes we have made to the the underlying data.</li><li>Clicked on the variable table showing <strong>tenure</strong> and changed the variable’s label to Tenure (i.e., making the capitalization consistent with the rest of the variables, so that the resulting outputs are neat enough to be shared with stakeholders).</li><li>Changed <strong>MonthlyCharges </strong>to <strong>Monthly Charges</strong>.</li><li>Changed <strong>InternetService </strong>to <strong>Internet Service</strong>.</li><li>Clicked on the <strong>No </strong>category in the Internet Service table and clicked on the three grey lines that appear to its right (if you don’t see them, click again), and dragged this category to be above <strong>DSL</strong>. If you accidentally merge the categories, just click the Undo arrow at the top-left of the screen. (Making sure that the categories are ordered sensibly makes interpretation easier.)</li><li>Selected the Tenure and Monthly Charges tables, and then, in the <a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector,</a> clicked <strong>Statistics &gt; Cells </strong>and clicked on <strong>Maximum </strong>and then <strong>Minimum</strong>, which adds these statistics to the table. In order to read them, click on the two tables that are on top, and drag them to the right so that they do not overlap. The good thing to note about both of these tables is that the averages, minimum, and maximum all look sensible, so there is no need to do any further data checking or cleaning.</li></ul><p>If all has gone well, your screen should show the following tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sQTXPnzwdpbt_aA8.png" /></figure><h4>Step 3: Creating an estimation, validation, and testing samples</h4><p>What is described in this stage is best practice. If you have a small sample (e.g., less than 200 cases) or are doing your work in an area where model quality is not a key concern, you can perhaps skip this step. However, before doing so, please read <a href="https://www.displayr.com/feature-engineering-for-categorical-variables">Feature Engineering for Categorical Variables</a>, as it contains some good examples illustrating the importance of using a validation sample.</p><p>In order to check our model we want to split the sample into three groups. One group will be used for estimating our model. This group of data is referred to as the <em>estimation</em> or <em>training sample.</em> A second group is used when comparing different models, which is called the <em>validation sample. </em>A third group is used for a final assessment of the quality of the model. This is called the <em>test </em>or <em>testing sample. </em>Why do we need these three groups? A basic problem when building predictive models is <em>overfitting, </em>whereby we inadvertently create a model that is really good at making predictions in the data set used to create the model, but which performs poorly in other contexts. By splitting the data into these three groups we can partly avoid overfitting, as well as assess the extent to which we have overfit our model.</p><p>In Displayr, we can automatically create filters for these three groups using <strong>Insert &gt; Utilities (More) &gt; Filtering &gt; Create Train-Validation-Test Split</strong>, which adds three new variables to the top of the data set, each of which has been tagged as <strong>Usable as a filter</strong>. The first of the filters is a random selection of 50% of the sample and the next two have 25% each. You can modify the proportions by clicking on the variables and changing the value in the first line of the <strong>R CODE </strong>for the variable.</p><h4>Step 4: Creating a preliminary model</h4><p>Now we are ready to build the logistic regression:</p><ul><li><strong>Insert &gt; Regression &gt; Binary Logit</strong> (<em>binary logit </em>is another name for logistic regression).</li><li>In <strong>Outcome </strong>select <strong>Churn</strong>.</li><li>In <strong>Predictor(s) </strong>select <strong>Senior Citizen</strong>, <strong>Tenure</strong>, <strong>Internet Service</strong>, <strong>Contract</strong>, and <strong>Monthly Charge</strong>. The fastest way to do this is to select them all in the data tree and drag them into the <strong>Predictor(s)</strong> box.</li><li>Scroll down to the bottom of the <strong>Inputs </strong>tab in the <a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector</a> and set <strong>FILTERS &amp; WEIGHTS &gt; Filter(s) </strong>to <strong>Training sample</strong>.</li><li>Press <strong>Automatic, </strong>which ensures that your model updates whenever you modify any of the inputs. If all has gone to plan, your output will look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W39EF4L6qm9NvTmV.png" /></figure><h4>Step 5: Compute the prediction accuracy tables</h4><ul><li>In Displayr, click on the model output (which should look like the table above).</li><li><strong>Insert &gt; Regression &gt; Diagnostic &gt; Prediction-Accuracy Table</strong>.</li><li>Move this below the table of coefficients and resize it to fit half the width of the screen (alternatively, add a new page and drag it to this page).</li><li>Making sure you still have the prediction-accuracy table selected, click on <a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector</a> &gt; <strong>Inputs &gt; Filter(s) </strong>and set it to <strong>Training sample</strong>, which causes the calculation only to be based on the training sample. The accuracy (shown in the footer) should be 79.05% as in the table above.</li><li>Press <strong>Home &gt; Duplicate (Selection)</strong>, drag the new copy of the table to the right, and change the filter to <strong>Validation sample</strong>. This new table shows the predictive accuracy based on the validation sample (i.e., the <em>out-of-sample prediction accuracy</em>). The result is almost the same, 79.1%.</li></ul><h4>Step 6: Interpretation</h4><p>Nice work! You have created all the key outputs required for logistic regression. For details on how to read them, please see <a href="https://www.displayr.com/how-to-interpret-logistic-regression-coefficients">How to Interpret Logistic Regression Coefficients</a> and <a href="https://www.displayr.com/how-to-interpret-logistic-regression-outputs">How to Interpret Logistic Regression Outputs</a>.</p><h4>Step 7: Modeling checking, feature selection, and feature engineering</h4><p>The next step is to tweak the model, by following up on any warnings that are shown, and by adding, removing, and modifying the predictor variables. See <a href="https://www.displayr.com/feature-engineering-in-displayr/">Feature Engineering in Displayr</a> and <a href="https://www.displayr.com/feature-engineering-in-displayr/">Feature Engineering in Displayr</a> for more information.</p><p>If you want to look at the various analyses discussed in this post in more detail, <a href="https://app.displayr.com/try/Interpreting%20Logistic%20Regression">click here</a> to get a copy of the Displayr document that contains all the work. Alternatively, reproduce the analyses yourself (downloading the data in Step 1) or use your own data.</p><p><strong>Do your own logistic regression in </strong><a href="https://app.displayr.com/SignUp?plan_id=0"><strong>Displayr</strong></a><strong>!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/how-to-do-logistic-regression-in-displayr/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338340750ee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering for Numeric Variables]]></title>
            <link>https://medium.com/@displayr/feature-engineering-for-numeric-variables-98ff430408b4?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ff430408b4</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 17:00:33 GMT</pubDate>
            <atom:updated>2018-10-26T04:01:30.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*vUV60H3_CSR-g-sO.jpeg" /></figure><p><strong>When building a predictive model, it is often practical to improve predictive performance by modifying the numeric variables in some way. In statistics, this is usually referred to as <em>variable transformation</em>. In this post I discuss some of the more common transformations of a single numeric variable: ranks, normalizing/standardizing, logs, trimming, capping, winsorizing, polynomials, splines, categorization (aka bucketing, binning), interactions, and nonlinear models.</strong></p><p>The goal of feature engineering for a numeric variable is to find a better way of representing the numeric variable in the model, where “better” connotes greater validity, better predictive power, and improved interpretation. In this post I am going to use two numeric variables, Tenure and Monthly Cost, from a logistic regression predicting churn for a telecommunications company (see <a href="https://www.displayr.com/how-to-interpret-logistic-regression-outputs">How to Interpret Logistic Regression Outputs</a> for more detail about this example). The basic ideas in this post are applicable to all predictive models, although some of these transformations have little effect on decision tree models (such as CART or CHAID), as these models only use orders, rather than the values, of numeric the predictor variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JZ2dFHNrrlvtJ8A8.png" /></figure><h4>Ranks</h4><p>The simplest way of transforming a numeric variable is to replace its input variables with their ranks (e.g., replacing 1.32, 1.34, 1.22 with 2, 3, 1). The rationale for doing this is to limit the effect of outliers in the analysis. If using R, Q, or Displayr, the code for transformation is rank(x), where x is the name of the original variable. The output below shows a revised model where Tenure has been replaced by Rank Tenure. If we look at the AIC for the new model it is 3,027.4, which is lower (which means better) than for the original model, telling us that the rank variable is a better variable. However, we have a practical problem which is that the estimated coefficient is 0.00. This is a rounding problem, so one solution is to look at more decimal places. However, a better solution is to transform the predictor so that it does not provide such a small estimate (this is desirable because computers can make rounding errors when working with numbers very close to 0, as can humans when looking at such numbers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hMZKv6VkkSMTeQw0.png" /></figure><h4>Standardizing/Normalizing</h4><p>Standardizing — which is usually (but not always) the same thing as normalizing — means transforming a variable so that it has a mean of 0 and standard deviation of 1. This is done by subtracting the mean from each value of a variable and then dividing by its standard deviation. For example, 0, 2, 4 is replaced by -1, 0, and 1. In R, we can use scale(x) as a shortcut. The output below replaces Rank Tenure with its standardized form. There are three important things to note about the effect of standardizing. First, the estimate for (Intercept) changes. This is not important. Second, the estimate for the variable changes. In our case, it is now clearly distinct from 0. Third, the other predictors are not changed, unless they too are modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ftjdE54DNvbmFTWC.png" /></figure><p>If all the variables are standardized it makes it easier to compare their relative effects, but harder to interpret the true meaning of the coefficients, as it requires you to always remember the details of the transformation (what the standard deviation was prior to the transformation).</p><h4>Logs</h4><p>In economics, physics, and biology, it is common to transform variables by taking their natural logarithm (in R: log(x)). For example, the values of 1, 3, and 4, are replaced by 0, 1.098612289, and 1.386294361.</p><p>The rationale for using the logarithm is that we expect a specific type of non-linear relationship. For example, economic theory tells us that we should expect that all else being equal, the higher the monthly charge, the more likely somebody will churn, but that this will have a diminishing effect (i.e., the difference between $100 and $101 should be smaller than the difference between $1 and $2). Using the the natural logarithm is consistent with such an assumption. Similarly, we would expect that the difference between a tenure of 1 versus 2 months is likely to be much bigger than the difference between 71 and 72 months.</p><p>The output below takes the logarithm of tenure. When compared to the previous models based on the AIC it is the best of the models. However, a closer examination reveals that something is amiss. The previous model has a sample size of 3,522, whereas the new model has a slightly smaller sample size. As sample size determines AIC, we have a problem: the AIC may be lower because the model is better or because of our missing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BZqXCVhtxZcbMzRJ.png" /></figure><p>The problem with taking logarithmic transformations is that they do not work with values of less than or equal to 0, and in our example five people have a tenure of 0. The fix for this is simple: we add 1 to all the numbers prior to taking the natural logarithm. Below the output shows the results for this modified model. This latest model has our best AIC yet at 3,002.40, which is consistent with a very general conclusion about feature engineering: using common sense and theory is often the best way to determine the appropriate transformations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoOvhDyChLPU45Lg.png" /></figure><h4>Trimming</h4><p><em>Trimming </em>is where you replace the highest and lowest values of a predictor with missing values (e.g., the top 5% and the bottom 5%). At first blush this feels like a smart idea, as it removes the outliers from the analysis. However, after spending more than 20 years toying with this approach, my general experience is that it is never useful. This is because when you replace the actual values with missing values, you end up needing to find a way of adequately dealing with the missing values in the model. This is a substantially harder problem than finding a good transformation, as all of the standard approaches to dealing with missing values are inapplicable when data is trimmed (to use the jargon, data that is trimmed is <em>nonignorable</em>).</p><h4>Winsorizing</h4><p><em>Winsorizing</em>, also known as <em>clipping, </em>involves replacing values below some threshold (e.g., the 5th percentile) with that percentile, and replacing values above some other threshold (e.g., the 95th percentile) with that value. With the tenure data, the 5th percentile is 1, and the 95th percentile is 72, so winsorizing involves recoding the values less than 1 as 1 and more than 72 as 72. In this example, 72 is also the maximum, so the only effect of winsorizing is to change the lowest values of 0 to 1. With the example being used in this post the winsorization had little effect, so the output is not shown. While in theory you can try different percentiles (e.g., 10th and 90th), this is a bit dangerous as there is no theory to guide such a decision, although using a histogram or density plot to identify extreme values can be useful. An alternative and often better approach is to use polynomials or splines (discussed later in this post). The following R code below winsorizes tenure.</p><h4>Capping</h4><p>Capping is the same basic idea as winsorizing, except that you only apply the recoding to the higher values. This can be particularly useful with data where the very highest values are likely to be extreme (e.g., as with income and house price data). The following code caps the tenure data at 30:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4BpWdrhyAIciQVgV.png" /></figure><p>The output from the model with tenure capped at 30 is shown above. The model is better than our initial model, but not as good as any of the more recent models. The reason why it performs better than the original model can be understood by looking at its coefficient of -0.06, which is twice the coefficient of the first model (-0.03), which tells us that the effect of tenure is comparatively greater for the lower values of tenure (as hypothesized in the discussion of logarithms).</p><h4>Polynomials</h4><p>When we take the logarithm we are asserting a specific non-linear relationship. In economics, where sample sizes are often very small, this is often a good thing to do. However, in our data set we have a much larger sample, so it makes sense to use a more general non-linear specification and try and extract the nature of the nonlinearity from the data. The simplest way to do this is to fit a <em>quadratic </em>model, which is done by both including the original numeric variable and a new variable that contains its square (in R: x²). The resulting model for tenure is shown below. This one is actually worse than our previous model. It is possible to also use cubics and higher order polynomials, but it is usually better practice to fit <em>splines</em>, discussed in the next section.</p><p>If you do wish to use polynomials, rather than manually computing them, it is usually better to use R’s in-built poly function. For example, in R, poly(x, 5) will create the first five polynomials. The cool thing about how this works is that it creates these polynomials so that they are orthogonal, which avoids many of the fitting problems that can occur with higher order polynomial calculated in the traditional way (e.g., x⁵) due to multicollinearity. If adding polynomials to a data set in Displayr, you will need to add them one by one (e.g., the fourth variable would be poly(x, 5)[, 4]. Use orthogonal polynomials with care when making predictions, as the poly function will give a different encoding for different samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vuEZVJDAua9-UJHB.png" /></figure><h4>Splines</h4><p>Where there is a numeric predictor and we wish to understand its nonlinear relationship to the outcome variable, best practice is usually to use a <em>regression spline, </em>which simultaneously fits the model and estimates the nature of the nonlinear relationship. This is a bit more complicated than any of the models used so far, and is usually done by writing code. Below I show the code and the main numerical output from fitting a <em>generalized additive logistic regression:</em></p><p>The key output for our analysis is a plot showing the the estimated nonlinear relationship, which is shown below.</p><p>The way that we read this is that the tenures are shown on the x-axis, and we can look up the coefficient (effect) for each of these. We can see, for example, that the coefficient is about 1.75 for a tenure of 0 months, but this drops quickly to around 0.4 after 10 months, after which the drop-off rate declines, and declines again at around 24 months. Although the spline is very cool and can detect things that have not been detected by any of the other models, the model’s resulting AIC is 3,012, which is not as good as the logarithmic model, suggesting that the various wiggles in the plot reflect over-fitting rather than insight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KaRB_tKkTLNwTDug.png" /></figure><h4>Bucketing/binning/categorization</h4><p>The last approach is to convert the numeric variable into a categorical variable. This can be done judgmentally or via percentiles. In the output below I show the results where I have split the data into deciles (cut(tenure, breaks = 10)) and set the variable as a categorical variable when estimating the model. The first decile is people with tenures from 0 to 7, and is defined as having an estimate of 0 (see <a href="https://www.displayr.com/how-to-interpret-logistic-regression-coefficients/">How to Interpret Logistic Regression Coefficients</a> for more info about how to interpret coefficients). We can see that the second decile, which is for tenures of 8 to 14, has a much lower coefficient, and then the next one is a lower again, but the overall trajectory is very similar to what we saw with the spline.</p><p>The bucketing is worse than the spline, and this is pretty much always the case. However, the great advantage of bucketing is that it is really simple to do and understand, making it practical to implement this with any predictive model. By contrast, splines are only practical if using advanced statistical models, and these can be tricky things to get working well if you haven’t spent years in grad school.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oX5a4Bh20GSFE-vm.png" /></figure><h4>Interactions</h4><p>An <em>interaction </em>is a new variable that is created by multiplying together two or more other variables. For example, we can interact tenure and monthly charges by creating a new numeric variable with the code Tenure * `Monthly Charges`. Note that in this example, <em>backticks </em>(which on an international keyboard is the key above the Tab key) surround monthly charges, which is the way to refer to variables in Displayr by their label rather than their name.</p><p>If specifying a lot of interactions it can be a bit painful to manually create a variable for each of them. An alternative is to edit the regression <em>formula </em>by going to the R code (<a href="https://docs.displayr.com/wiki/Object_Inspector">Object Inspector</a> &gt; <strong>Properties &gt; R CODE</strong>), and adding a * to the formula, as can be seen in the screenshot below. Note that when we do this, the regression will automatically estimate three coefficients: one for Monthly Charges, one for LogTenurePlus1, and one for their interaction. If we only wanted to create the interaction we would instead write MonthlyCharges:LogTenurePlus1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*ZjjyS26EixGNJQOF.png" /></figure><h4>Nonlinear models</h4><p>Splines are really a nonlinear model rather than a form of feature engineering, and this highlights that sometimes we can avoid the need for feature engineering by using explicit statistical and machine learning models that are designed to detect and adjust for nonlinearity, such as decision trees, splines, random forests, and deep learning. Although such methods can be highly useful, my experience is that even when using such methods it usually pays off to try the various types of transformations described in this post.</p><p><a href="https://app.displayr.com/try/Interpreting%20Logistic%20Regression"><strong>Explore the original dashboard</strong></a></p><p>If you want to look at the various analyses discussed in this post in more detail, <a href="https://app.displayr.com/try/Interpreting%20Logistic%20Regression">click here</a> to get a copy of the Displayr document that contains all the work. If you want to reproduce these analyses yourself, either with this data or some other data, please check out:</p><ul><li><a href="https://www.displayr.com/how-to-do-logistic-regression-in-displayr/">How to do Logistic Regression in Displayr</a></li><li><a href="https://www.displayr.com/feature-engineering-in-displayr/">Feature Engineering in Displayr</a></li><li><a href="https://www.displayr.com/feature-engineering-for-categorical-variables">Feature Engineering for Categorical Variables</a></li></ul><p><strong>Ready to get started? Click the button above to view and edit these models!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/feature-engineering-for-numeric-variables/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ff430408b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Interpret Logistic Regression Outputs]]></title>
            <link>https://medium.com/@displayr/how-to-interpret-logistic-regression-outputs-b6648a8b948d?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6648a8b948d</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 17:00:19 GMT</pubDate>
            <atom:updated>2018-10-26T04:01:24.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*eYKe1-ARk-hHwVhv.png" /></figure><p><strong>Logistic regression, also known as <em>binary logit </em>and <em>binary logistic regression, </em>is a particularly useful predictive modeling technique, beloved in both the machine learning and the statistics communities. It is used to predict outcomes involving two options (e.g., buy versus not buy).</strong></p><p>In this post I explain how to interpret the standard outputs from logistic regression, focusing on those that allow us to work out whether the model is good, and how it can be improved. These outputs are pretty standard and can be extracted from all the major data science and statistics tools (R, Python, Stata, SAS, SPSS, Displayr, Q). In this post I review prediction accuracy, pseudo r-squareds, AIC, the table of coefficients, and analysis of variance.</p><p><a href="https://app.displayr.com/creator/Regression/Binary%20Logit"><strong>Create your own Logistic Regression</strong></a></p><h4>Prediction accuracy</h4><p>The most basic diagnostic of a logistic regression is predictive accuracy. To understand this we need to look at the <em>prediction-accuracy table </em>(also known as the <em>classification table, hit-miss table, </em>and <em>confusion matrix</em>). The table below shows the <em>prediction-accuracy table </em>produced by <a href="https://www.displayr.com/how-to-do-logistic-regression-in-displayr">Displayr’s logistic regression</a>. At the base of the table you can see the percentage of correct predictions is 79.05%. This tells us that for the 3,522 observations (people) used in the model, the model correctly predicted whether or not somebody churned 79.05% of the time. Is this a good result? The answer depends a bit on context. In this case 79.05% is not quite as good as it might sound.</p><p><a href="https://embedded.azureedge.net/75668/296069/13ad0e48-2917-4b40-853c-6085d492c4ee.html?v=32306-f1c3ae1f88594394746">https://embedded.azureedge.net/75668/296069/13ad0e48-2917-4b40-853c-6085d492c4ee.html?v=32306-f1c3ae1f88594394746</a></p><p>Starting with the <strong>No </strong>row of the table, we can see that the there were 2,301 people who did not churn and were correctly predicted not to have churned, whereas only 274 people who did not churn were predicted to have churned. If you hover your mouse over each of the cells of the table you see additional information, which computes a percentage telling us that the model accurately predicted non-churn for 83% of those that did not churn. So far so good.</p><p>Now, look at the second row. It shows us that among people who did churn, the model was only marginally more likely to predict they churned than did not churn (i.e., 483 versus 464). So, among people who did churn, the model only correctly predicts that they churned 51% of the time.</p><p>If you sum up the totals of the first row, you can see that 2,575 people did not churn. However, if you sum up the first column, you can see that the model has predicted that 2,765 people did not churn. What’s going on here? As most people did not churn, the model is able to get some easy wins by defaulting to predicting that people do not churn. There is nothing wrong with the model doing this. It is the optimal thing to do. But, it is important to keep this in mind when evaluating the accuracy of any predictive model. If the groups being predicted are not of equal size, the model can get away with just predicting people are in the larger category, so it is always important to check the accuracy separately for each of the groups being predicted (i.e., in this case, churners and non-churners). It is for this reason that you need to be sceptical when people try and impress you with the accuracy of predictive models; when predicting a rare outcome it is easy to have a model that predicts accurately (by making it always predict against the rare outcome).</p><h4>Out-of-sample prediction accuracy</h4><p>The accuracy discussed above is computed based on the same data that is used to fit the model. A more thorough way of assessing prediction accuracy is to perform the calculation using data not used to create the model. This tests whether the accuracy of the model is likely to hold up when used in the “real world”. The table below shows the prediction accuracy of the model when applied to 1,761 observations that were not used when fitting the logistic regression. The good news here is that in this case the prediction accuracy has improved a smidge to 79.1%. This is a bit of a fluke. Typically we would expect to see a lower prediction accuracy when assessed out-of-sample — often substantially lower.</p><p><a href="https://embedded.azureedge.net/75668/296069/5088aabe-75da-4ace-a52f-31f9e3938570.html?v=32306-f1c3ae1f882120518118">https://embedded.azureedge.net/75668/296069/5088aabe-75da-4ace-a52f-31f9e3938570.html?v=32306-f1c3ae1f882120518118</a></p><h4>R-squared and pseudo-r-squared</h4><p>The footer of the table below shows that the r-squared for the model is 0.1898. This is interpreted in exactly the same way as with the r-squared in linear regression, and it tells us that this model only explains 19% of the variation in churning.</p><p>Although the r-squared is a valid computation for logistic regression, it is not widely used as there are a variety of situations where better models can have lower r-squared statistics. A variety of <em>pseudo r-squared </em>statistics are used instead. The footer for this table shows one of these, <em>McFadden’s rho-squared</em>. Like r-squared statistics, these statistics are guaranteed to take values from 0 to 1, where a higher value indicates a better model. The reason that they are preferred over traditional r-squared is that they are guaranteed to get higher as the fit of the model improves. The disadvantage of pseudo r-squared statistics is that they are only useful when compared to other models fit to the same data set (i.e., it is not possible to say if 0.2564 is a good value for McFadden’s rho-squared or not).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BMtkSJI8VUjb_sJl.png" /></figure><h4>AIC</h4><p>The <em>Akaike information criterion (AIC) </em>is a measure of the quality of the model and is shown at the bottom of the output above. This is one of the two best ways of comparing alternative logistic regressions (i.e., logistic regressions with different predictor variables). The way it is used is that all else being equal, the model with the lower AIC is superior. The AIC is generally better than pseudo r-squareds for comparing models, as it takes into account the complexity of the model (i.e., all else being equal, the AIC favors simpler models, whereas most pseudo r-squared statistics do not).</p><p>The AIC is also often better for comparing models than using out-of-sample predictive accuracy. Out-of-sample accuracy can be a quite insensitive and noisy metric. The AIC is less noisy because:</p><ul><li>There is no random component in it, whereas the out-of-sample predictive accuracy is sensitive to which data points were randomly selected for the estimation and validation (out-of-sample) data.</li><li>It takes into account all of the probabilities. That is, when using out-of-sample predictive accuracy, both a 51% prediction and a 99% prediction have the same weight in the final calculation. By contrast, with the AIC, the 99% prediction leads to a lower AIC than the 51% prediction (i.e., the AIC takes into account the probabilities, rather than just the Yes or No prediction of the outcome variable).</li></ul><p>The AIC is only useful for comparing relatively similar models. If comparing qualitatively different models, such as a logistic regression with a decision tree, or a very simple logistic regression with a complicated one, out-of-sample predictive accuracy is a better metric, as the AIC makes some strong assumptions regarding how to compare models, and the more different the models, the less robust these assumptions.</p><h4>The table of coefficients</h4><p>The table of coefficients from above has been repeated below. When making an initial check of a model it is usually most useful to look at the column called <strong><em>z</em></strong><em>, </em>which shows the <em>z-statistics</em>. The way we read this is that the further a value is from 0, the stronger its role as a predictor. So, in this case we can see that the Tenure variable is the strongest predictor. The negative sign tells us that as tenure increases, the probability of churning decreases. We can also see that Monthly Charges is the weakest predictor, as its <strong><em>z </em></strong>is closest to 0. Further, the <em>p-</em>value for monthly charges is greater than the traditional cutoff of 0.05 (i.e, it is not “statistically significant”, to use the common albeit dodgy jargon). All the other predictors are “significant”. To get a more detailed understanding of how to read this table, we need to focus on the <strong>Estimate </strong>column, which I’ve gone to town on in <a href="https://www.displayr.com/how-to-interpret-logistic-regression-coefficients">How to Interpret Logistic Regression Coefficients</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9lRgqAo5K3y5SDb.png" /></figure><h4>Analysis of Variance (ANOVA)</h4><p>With logistic regressions involving categorical predictors, the table of coefficients can be difficult to interpret. In particular, when the model includes predictors with more than two categories, we have multiple estimates and <em>p</em>-values, and <em>z-</em>statistics. This is doubly problematic. First, it can be hard to get your head around how to <a href="https://www.displayr.com/how-to-interpret-logistic-regression-coefficients">interpret</a> them. Second, sometimes some or all of the coefficients for a categorical predictor are not statistically significant, but for complicated reasons beyond the scope of this post it is possible to have none or some of the individual coefficients being significant, but for them all to be <em>jointly significant</em> (significant when assessed as a whole), and vice versa.</p><p>This problem is addressed by performing an <em>analysis of variance (ANOVA) </em>on the logistic regression. Sometimes these will be created as a separate table, as in the case of Displayr’s ANOVA table, shown below. In other cases the results will be integrated into the main table of coefficients (SPSS does this with its Wald tests). Typically, these will show either the results of a likelihood-ratio (LR) test or a Wald test.</p><p>The example below confirms that all the the predictors other than Monthly Charges are significant. We can also make some broad conclusions about relative importance by looking at the LR Chisq column, but when doing so keep in mind that with this statistic (and also with the Wald statistic shown by some other products, such as SPSS Statistics), that: (1) we cannot meaningfully compute ratios, so it is not the case that Tenure is almost twice as important as Contract; and, (2) the more categories in any of the predictors, the less valid these comparisons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1pvUmckU3oa-av-p.png" /></figure><h4>Other outputs</h4><p>The outputs described above are the standard outputs, and will typically lead to the identification of key problems. However, they are by no means exhaustive, and there are many other more technical outputs that can be used which can lead to conclusions not detectable in these outputs. This is one of the ugly sides of building predictive models: there is always something more that can be checked, so you never can be 100% sure if your model is as good as it can be…</p><p><a href="https://app.displayr.com/creator/Regression/Binary%20Logit"><strong>Create your own Logistic Regression</strong></a></p><p><strong>If you want to do logistic regression yourself, getting all the outputs shown in this post, try out the free version of Displayr by clicking the button above!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/how-to-interpret-logistic-regression-outputs/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6648a8b948d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Results from Tables as R Outputs]]></title>
            <link>https://medium.com/@displayr/extracting-results-from-tables-as-r-outputs-675eab494439?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/675eab494439</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Sun, 14 Oct 2018 02:59:43 GMT</pubDate>
            <atom:updated>2018-10-14T02:59:53.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Tables and all other objects in Displayr have names. In order to extract data from a table we need to know two things: its name and how many dimension it has. There are two ways you can see the name of a table. You can click on the expander to the left of the page name in the pages tree, which will show the names of all of the outputs on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*3g6Sb0oSCutk1bCJ.png" /></figure><p>Alternatively, you can click on the table and view its name in the Object Inspector (<strong>Properties &gt; GENERAL &gt; Name</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*t0MgL8mC0WtEKy4Z.png" /></figure><p>By default the name is constructed of three elements: the word table, the name of the variable sets used to construct the table (e.g., Age), and a number if there are multiple tables created from the same variable sets. You can change the name; it will automatically reset if the input data changes.</p><h4>Extracting data from a one dimensional table</h4><p>The age table shown above above is one-dimensional, which is to say it has a single column of numbers. To extract numbers from the table we need to create an R Output, which is an object that appears on the page and will store these numbers. This is done by clicking <strong>Insert &gt; R Output </strong>and then either typing in the name of the table or dragging it from the pages tree, and then <em>subscripting </em>the table. As an example, the code below extracts the value from table above of people aged 25 to 29.</p><p><a href="https://embedded.azureedge.net/75668/304113/1156c1e0-0059-426a-937f-33f6aa26e4e9.html?v=32562-d95422e4dd-969844451">https://embedded.azureedge.net/75668/304113/1156c1e0-0059-426a-937f-33f6aa26e4e9.html?v=32562-d95422e4dd-969844451</a></p><p>As 25 to 29 is the second category in the table, we can get the same result by typing table.Age[2].</p><p>WIth a table with a single number in it, we can reference the name of the row heading, as shown below. With a single number in the table, we can also just refer to the whole table itself and in most situations it will just be treated as just a single number (there are some edge cases where the label will be taken into account).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*eX4lK0jz_a_o2xvc.png" /></figure><p>There are some rare situations where a table like the one shown above will in fact have two dimensions. If this is the case you will see a message saying <strong>incorrect number of dimensions </strong>and will need to treat it as a two-dimensional table (discussed below).</p><h4>Extracting multiple values</h4><p>We can extract multiple values by listing which cells in the table to extract as shown below. Displayr also shows the corresponding row labels of the table. These will generally be ignored in any ensuing calculations.</p><p><a href="https://embedded.azureedge.net/75668/304113/95970480-1b9b-4c33-a3fb-ea6fafe06636.html?v=32562-d95422e4dd452791029">https://embedded.azureedge.net/75668/304113/95970480-1b9b-4c33-a3fb-ea6fafe06636.html?v=32562-d95422e4dd452791029</a></p><p><a href="https://embedded.azureedge.net/75668/304113/da34d953-820c-4168-a8e1-9508c95bc116.html?v=32562-d95422e4dd829025640">https://embedded.azureedge.net/75668/304113/da34d953-820c-4168-a8e1-9508c95bc116.html?v=32562-d95422e4dd829025640</a></p><p>Consecutive cells can be selected more efficiently using:</p><p><a href="https://embedded.azureedge.net/75668/304113/bdec2a22-30e5-42b4-b8fc-313f22a3ea5f.html?v=32562-d95422e4dd-1997149983">https://embedded.azureedge.net/75668/304113/bdec2a22-30e5-42b4-b8fc-313f22a3ea5f.html?v=32562-d95422e4dd-1997149983</a></p><p>We can also indicate which cells not to use via negative signs, as done here:</p><p><a href="https://embedded.azureedge.net/75668/304113/eb1c8fb6-8b64-4758-ad77-2cf517be399e.html?v=32562-d95422e4dd918354040">https://embedded.azureedge.net/75668/304113/eb1c8fb6-8b64-4758-ad77-2cf517be399e.html?v=32562-d95422e4dd918354040</a></p><p>Excluding cells is most commonly useful when we are excluding nets or totals, which tend to appear in the last cell in the table. This example excludes the last row, where NROW is a function that works out the last row of a table (i.e., NROW(table.Age) is 10):</p><p><a href="https://embedded.azureedge.net/75668/304113/c3d7c39b-c74e-4542-8ecb-d5b254fbc8bd.html?v=32562-d95422e4dd211968920">https://embedded.azureedge.net/75668/304113/c3d7c39b-c74e-4542-8ecb-d5b254fbc8bd.html?v=32562-d95422e4dd211968920</a></p><h4>Extracting results from two-dimensional tables</h4><p>The principles of extracting results from two-dimensional tables are the same as those for one-dimensional tables, except that we need to specify the rows and the columns. If you see an error of <strong>incorrect number of dimensions</strong>, this means that your table is not really two-dimensional, and you need to see the section below on higher dimensional tables.</p><p>In this section we will extract data from the table shown below, called table.Age.by.Gender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aTm83FBWJwmxCWEw.png" /></figure><p>To extract a single cell from the table, we enter both its row and column name, separated by a comma.</p><p><a href="https://embedded.azureedge.net/75668/304113/0dc0ad81-12e9-46fe-bafa-a54c9cfdf36b.html?v=32562-d95422e4dd-1934303775">https://embedded.azureedge.net/75668/304113/0dc0ad81-12e9-46fe-bafa-a54c9cfdf36b.html?v=32562-d95422e4dd-1934303775</a></p><p><a href="https://embedded.azureedge.net/75668/304113/2e686599-999e-41c8-ace5-97c3fd4e021e.html?v=32562-d95422e4dd-991037699">https://embedded.azureedge.net/75668/304113/2e686599-999e-41c8-ace5-97c3fd4e021e.html?v=32562-d95422e4dd-991037699</a></p><p>This example extracts rows two, three, and four, for the males column.</p><p><a href="https://embedded.azureedge.net/75668/304113/21ee05c8-f112-4e77-a0c3-8b2074170201.html?v=32562-d95422e4dd1308710958">https://embedded.azureedge.net/75668/304113/21ee05c8-f112-4e77-a0c3-8b2074170201.html?v=32562-d95422e4dd1308710958</a></p><p><a href="https://embedded.azureedge.net/75668/304113/dd0cd232-a5d1-4135-b53e-64812c0f0b2f.html?v=32562-d95422e4dd180892211">https://embedded.azureedge.net/75668/304113/dd0cd232-a5d1-4135-b53e-64812c0f0b2f.html?v=32562-d95422e4dd180892211</a></p><p>We can write this more efficiently by assigning the table a shorter name in the R code:</p><p><a href="https://embedded.azureedge.net/75668/304113/3b775b83-050c-493e-bc57-dab8b354ca60.html?v=32562-d95422e4dd40530838">https://embedded.azureedge.net/75668/304113/3b775b83-050c-493e-bc57-dab8b354ca60.html?v=32562-d95422e4dd40530838</a></p><p>In the example below we still have a crosstab of age by gender, but the count has also been added to the table (<strong>Object Inspector &gt; STATISTICS &gt; Cells: Count</strong>). This table now has three dimensions: age, gender, and the statistics. We will get an error of <strong>incorrect number of dimensions</strong> if we attempt to subscript it and ignore the third dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Na6Y75lYWrwRIXI.png" /></figure><p>If we add a comma, we get both statistics.</p><p><a href="https://embedded.azureedge.net/75668/304113/f4fa4e1a-c5ae-4fcb-8c07-89b29e37a0d2.html?v=32562-d95422e4dd47554795">https://embedded.azureedge.net/75668/304113/f4fa4e1a-c5ae-4fcb-8c07-89b29e37a0d2.html?v=32562-d95422e4dd47554795</a></p><p><a href="https://embedded.azureedge.net/75668/304113/e3c49e65-a1cd-4bc6-ba2b-c5e1aa311bc1.html?v=32562-d95422e4dd104821855">https://embedded.azureedge.net/75668/304113/e3c49e65-a1cd-4bc6-ba2b-c5e1aa311bc1.html?v=32562-d95422e4dd104821855</a></p><h4>Higher-dimensional tables (arrays)</h4><p>The table below has five dimensions. Such data is usually referred to an <em>array </em>in R.</p><p><a href="https://embedded.azureedge.net/75668/304113/6a6a331c-fdf4-4b41-8170-6bd61558d299.html?v=32562-d95422e4dd-181655167">https://embedded.azureedge.net/75668/304113/6a6a331c-fdf4-4b41-8170-6bd61558d299.html?v=32562-d95422e4dd-181655167</a></p><p><a href="https://embedded.azureedge.net/75668/304113/ed10b7dd-1cb9-479b-b72b-a394790ce123.html?v=32562-d95422e4dd141786604">https://embedded.azureedge.net/75668/304113/ed10b7dd-1cb9-479b-b72b-a394790ce123.html?v=32562-d95422e4dd141786604</a></p><p>WIth higher dimensional tables it can be a bit difficult to work out which labels need to go in which position in the square brackets. The best way to find this out is to use the dimnames function. It shows in double square brackets the different dimensions and their categories, as shown in the two examples below.</p><p><a href="https://embedded.azureedge.net/75668/304113/3755c264-d640-4fb4-a908-8b06f34cbbc1.html?v=32562-d95422e4dd-1442001937">https://embedded.azureedge.net/75668/304113/3755c264-d640-4fb4-a908-8b06f34cbbc1.html?v=32562-d95422e4dd-1442001937</a></p><p><a href="https://embedded.azureedge.net/75668/304113/cb3922e8-fc0a-4cd9-92e5-c27dd69774e4.html?v=32562-d95422e4dd-1335707466">https://embedded.azureedge.net/75668/304113/cb3922e8-fc0a-4cd9-92e5-c27dd69774e4.html?v=32562-d95422e4dd-1335707466</a></p><h4>Safety first: defensive programming</h4><p>A lot of people new to writing code decide to take the fast option and use code code like table.Age[2:3, -11], rather than table.Age[c(“25 to 29”, “29 to 34”, “35 to 39”), -NCOL(table.Age)], because it is much faster to type. It is possible that the input table may change in some way and the code ends up giving the wrong answer. This would occur, for example, if the 18 to 24 category was removed from the table, or if the age data was replaced with the income data in the table. By contrast, the more verbose table.Age[c(“25 to 29”, “29 to 34”, “35 to 39”), -NCOL(table.Age)] is a good example of defensive programming. If the 18 to 24 category were to be removed, it would still give the right answer, and if the age data was replaced by income it would return an error, allowing you to identify and rectify the problem.</p><p><em>Originally published at </em><a href="https://www.displayr.com/extracting-results-from-tables-as-r-outputs/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675eab494439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Model?]]></title>
            <link>https://medium.com/@displayr/what-is-a-model-7b85b537483f?source=rss-9a809f30fb0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b85b537483f</guid>
            <dc:creator><![CDATA[Displayr]]></dc:creator>
            <pubDate>Sat, 13 Oct 2018 16:10:04 GMT</pubDate>
            <atom:updated>2018-10-14T21:49:41.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*opkx5b2M3NKtSNMv.png" /></figure><h4>Physical models</h4><p>The technical meaning of the word “model” is identical to the understanding you had as a child. Consider a <em>model</em> of Copenhagen’s harbor, built out of Lego. This is a model in the same way as an equation can be a model: it is something designed to look like the real thing, but it is not actually the real thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*bbubnbuneornmTRs.png" /></figure><h4>Word models</h4><p>Many models exist as sentences. For example, the economic concept of the demand curve posits that:</p><p><em>Demand is a function of price.</em></p><h4>Graphical models</h4><p>Models can be combinations of images and words. A simple example is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*ghsbCTRCvcBQ3nRp.png" /></figure><p>A more complicated graphical model is the <em>means-end chain </em>shown below, which shows how preferences for specific features of wine-based soft drinks (shown at the bottom) “ladder” up to benefits desired, which in turn ladder up to values that are important to people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dAW8rf1TfJJmQTPp.png" /></figure><h4>Causal diagrams</h4><p><em>Causal diagrams </em>are a type of graphical model where arrows indicate what causes what. For example, the idea that demand for a good is a function of price is expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*xwQRFio02NeQ9Nqe.png" /></figure><p>A more complex model may specify the <em>mechanism </em>by which an input affects an outcome. For example, the <em>hierarchy of effects </em>model of advertising says that advertising influences sales by making more people aware, changing their attitude, prompting them to want to buy, and encouraging their final decision to purchase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*Zmqp6aiDHa2uca2Y.png" /></figure><h4>Equations</h4><p>For most areas of application, the ultimate model is one where a model can be expressed using mathematics, as in the following equation:</p><p>$Sales = 121 + 4.1 × $Advertising expenditure</p><p>Such models are the end-goal of most efforts at science as they are most precise, which makes them both more useful in practice and easier to check<em>. </em>This should not be inferred as meaning that all models should be expressed mathematically: when a model is expressed mathematically it is often harder to understand, which can lead to errors. For example, causal diagrams are often better for understanding causality than are equations (see Pearl, Judea (2009), Causality: Models, Reasoning and Inference: Cambridge University Press; 2nd Edition).</p><p><strong>Check out more of our handy </strong><a href="https://www.displayr.com/category/beginners-guide/what-is/"><strong>What Is…</strong></a><strong> guides!</strong></p><p><em>Originally published at </em><a href="https://www.displayr.com/what-is-a-model/"><em>Displayr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b85b537483f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>