<?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 Rowan Curry on Medium]]></title>
        <description><![CDATA[Stories by Rowan Curry on Medium]]></description>
        <link>https://medium.com/@curryrowan?source=rss-416f2c39f98b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yo2AIn-qhAtpC7J14ODdkw.jpeg</url>
            <title>Stories by Rowan Curry on Medium</title>
            <link>https://medium.com/@curryrowan?source=rss-416f2c39f98b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:36:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@curryrowan/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[Distributions for Data Science: Bernoulli!]]></title>
            <link>https://medium.com/@curryrowan/distributions-for-data-science-bernoulli-39c57ea93d81?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c57ea93d81</guid>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Sun, 09 Jan 2022 03:05:09 GMT</pubDate>
            <atom:updated>2022-01-09T03:05:09.127Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part one of a seven part series defining, explaining, and simulating statistical distributions crucial to the field of data science.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*zqoWi4LQk5mkI8xgzgkv5g.jpeg" /><figcaption>Jakob Bernoulli (image thanks to Wikipedia)</figcaption></figure><p>Thanks to the guy to my left, Swiss mathematician Jakob Bernoulli, we have the <strong>Bernoulli Distribution</strong>. Jakob Bernoulli comes from a dynasty of mathematicians — the Bernoulli family of Basel, Switzerland produced eight mathematically gifted individuals during the early modern period. And all eight of those scholars contributed substantially to the development of mathematics and physics — talk about sibling rivalry!</p><p>This distribution provides the framework for many other important distributions — for example, Bernoulli trials set the stage for the Binomial Distribution, which in turn sets the foundation of any binary classification model.</p><h3>The Bernoulli Distribution</h3><p>The Bernoulli Distribution is a <strong>discrete distribution</strong>. These distributions consist of countable, non-negative integers. This means that the values the Bernoulli Distribution can assume are <em>finite</em>.</p><p>The assumptions we need in order to build this distribution are:</p><ol><li>Only one Bernoulli trial is performed.</li><li>There are only two possible outcomes for the single Bernoulli trial.</li></ol><p>Consider a coin toss. In this example, we can define a “success” as getting heads, and a “failure” as getting tails. By doing this, our coin toss becomes a Bernoulli trial with a 50% probability of success.</p><p>From this example, and from our assumptions, we can build our <strong>probability mass function (PMF)</strong>. For a random variable X that follows a Bernoulli distribution, the PMF below gives the probability that X is equal to a certain value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*lyfMpcMILWlhSg99nEWEfw.png" /><figcaption>Bernoulli PMF (image is my own)</figcaption></figure><p>From the PMF, we can calculate the expected value and variance of a random variable X that depends on the numerical value of x. Let’s assume that x = 1 when we have a “success”, and that x = 0 when we have a “failure”. Then we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ioQyCt5jfZZ7PNytZkLCMw.png" /><figcaption>Expected Value of the Bernoulli Distribution (image is my own)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arzOrGm7acBwRJAQB8re7A.png" /><figcaption>Variance of the Bernoulli Distribution (image is my own)</figcaption></figure><h3>Bernoulli Simulation</h3><p>Simulating a Bernoulli trial in Python is pretty straightforward. We’ll use numpy to build a function that simulates a Bernoulli trial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPJCYGT4uWixbCKzkBeljg.png" /><figcaption>Bernoulli trial simulation code (image is my own)</figcaption></figure><p>Then, we’ll plug in some probabilities! Here’s an outcome of a Bernoulli trial with equal probabilities of success and failure, just like with our coin toss example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*7t0mpdPjQKzGwjXTzj2osA.png" /><figcaption>Bernoulli trial simulation code, equal probabilities (image is my own)</figcaption></figure><p>We can also try it with differing probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*b8tIt212R66mSB8p5GdGVg.png" /><figcaption>Bernoulli trial simulation code, differing probabilities (image is my own)</figcaption></figure><p>And that’s a wrap! Stay tuned for the second installation in the seven part series: the Binomial Distribution!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c57ea93d81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdaBoost: Explained!]]></title>
            <link>https://medium.com/@curryrowan/adaboost-explained-92408a6713da?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/92408a6713da</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 21:13:33 GMT</pubDate>
            <atom:updated>2022-01-02T21:13:33.610Z</atom:updated>
            <content:encoded><![CDATA[<p>The following article takes you through an intuitive explanation of the AdaBoost algorithm! AdaBoost is a Boosting algorithm based on Random Forests. <em>If you’re unfamiliar with Boosting and/or Random Forests, I would recommend reviewing the following articles before proceeding:</em></p><ul><li><a href="https://medium.com/@curryrowan/the-complete-guide-to-random-forests-part-1-427c9cba8336">The Complete Guide to Random Forests: Part 1</a></li><li><a href="https://medium.com/@curryrowan/the-three-bs-bootstrapping-bagging-boosting-43df4b372a6a">The Three Bs: Boostrapping, Bagging, and Boosting!</a></li></ul><p>Let’s begin!</p><h3>Deforestation! Oh no!</h3><p>If you’re already familiar with Random Forests, you’ll recall that a Random Forest is full of many different Decision Trees. AdaBoost is built using a similar concept, but instead of trees, the algorithm uses <em>stumps</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*vr2eKI_auK0E7nrmz1gIqQ.png" /><figcaption>stump visualization (picture courtesy of Google)</figcaption></figure><p>A <em>stump</em> is a decision tree consisting of a root node + leaf nodes. And that’s it!</p><p>Upon first glance, a forest of stumps doesn’t seem like it would end up being an accurate classification methodology. And it’s completely correct that a single stump doesn’t do a great job of classifying samples. It’s also true that a ton of independent stumps combined probably wouldn’t do a great job of classifying a sample. That’s why AdaBoost combines stump structures with a concept called <em>Boosting</em>.</p><h3>The Boost in AdaBoost!</h3><p>This article assumes you’re already familiar with the concept of Boosting. As a quick reminder, <em>Boosting is an ensemble learning technique where each model is built sequentially by iterating over the previous model</em>.</p><p>In the forest of stumps that makes up AdaBoost, each stump has a different amount of say in the final classification decision for each sample. This is different from the Random Forest algorithm, where each tree has an equal vote.</p><p>In AdaBoost, order is important. The errors that the first stump makes influences how the second stump is made, and so on and so forth, until as many errors as possible have been taken into account.</p><p>Let’s start building the first stump of a simplified, made up classification problem to better understand how this works.</p><h3>Building Our First Stump</h3><p>We’ll use our own weather data to simulate the AdaBoost algorithm. In this mini made-up dataset, the target variable is RainTomorrow, and has two possible values, “Yes”, and “No”. The goal of our classification problem is to figure out if it will rain the next day based on temperature, humidity, and whether or not it rained the day on the day in question.</p><p>The first step of the algorithm is to assign each sample an equal weight. Since there are four samples in our simplified example, each sample will be assigned the weight 1/4. After the first stump is made, the weights will change in order to guide how the next stump is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJu-Qm6QdrY5-VMPU8p-lA.png" /><figcaption>Sample Weather Data (image is my own)</figcaption></figure><p>Then, we find the variable that does the best job classifying the samples using the <a href="https://medium.com/analytics-steps/understanding-the-gini-index-and-information-gain-in-decision-trees-ab4720518ba8">GINI Index</a>. At this step, we can ignore the weights, since they’re currently all the same.</p><p>Let’s assume that Humidity had the highest GINI Index, and choose it for the root node of our first sample. Say that it correctly classified every sample except for the one highlighted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQ_jf4hAi8gWp1JXpddREQ.png" /><figcaption>Highlighted Sample Weather Data (image is my own)</figcaption></figure><p>In order to determine how much say this stump has in our final classification, we’ll need to calculate <strong>Total Error</strong> and <strong>Amount of Say</strong>.</p><p>Let’s start with total error. The <em>Total Error</em> for a stump is the sum of the weights associated with the <em>incorrectly</em> classified samples. Here, the total error is 1/4.</p><p>It’s important to note that because all of the Sample Weights add up to 1, Total Error will always be between 0 (for a perfect stump) and 1 (for a horrible stump).</p><p>Next, we use the Total Error to calculate the <em>Amount of Say</em> a stump has in final classification. This is calculated using the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*qr59J2lcx4JszX2bduPUig.png" /><figcaption>Amount of Say Equation, formula (image is my own)</figcaption></figure><p>To better understand how this equation determines amount of say, we’ll visualize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOot4aBe4ywcFOo8t1IwrQ.jpeg" /><figcaption>Amount of Say Equation, visualization (image is my own)</figcaption></figure><p>After looking at the visualization above, we can see that when a stump does a good job, and the total error is small, then the Amount of Say is a relatively large, positive value. And when a stump does a terrible job, and the Total Error is close to 1 (meaning the stump consistently gives you the opposite answer for classification), then the Amount of Say will be a large, negative value.</p><p>Furthermore, when a stump is no better at classifying than random guessing, such as flipping a coin, then the Amount of Say will be 0. <em>Note</em>: if the Total Error is 1 or 0, then the Amount of Say equation is undefined.</p><p>We can calculate our Amount of Say using our Total Error of 1/4. This comes out to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*4YvRJbSbNi51wdi2j1LDog.png" /><figcaption>Amount of Say Calculated for example (image is my own)</figcaption></figure><p>Now we have our Total Error and our Amount of Say, but we need to incorporate them into our algorithm so that our next stump takes the errors of our current stump into account. We’ll do this by using Total Error and Amount of Say to calculate new sample weights.</p><h3>Calculating New Sample Weights</h3><p>The main idea behind calculating new sample weights is that whichever samples the first stump misclassifies get assigned an increased weight before the next stump is built. This means that when the algorithm goes to make the second tree, it’ll know which samples are most important to get right this time around.</p><p>Let’s calculate our new weights. For calculating new sample weights, we’ll need two separate equations. First, the formula for <em>increasing</em> the sample weight for the sample that was <em>incorrectly</em> classified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*igG32W8CwCrZ0kgPrT5i7Q.png" /><figcaption>New Sample Weight for incorrectly classified sample, formula (image is my own)</figcaption></figure><p>We can once again visualize this to help us better understand how our equation works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN9RSghScSbkGo1umycXxw.jpeg" /><figcaption>New Sample Weight for incorrectly classified samples, visualization (image is my own)</figcaption></figure><p>As you can see, when the Amount of Say is relatively large (i.e. the last stump did a good job of classifying samples) then we scale the previous sample weight with a large number. This makes the new sample weight much larger than the old one.</p><p>And when the amount of say is relatively low, then the previous sample weight is scaled by a relatively small number. This means that the new sample weight will only be slightly larger than the old one.</p><p>Let’s calculate our new sample weight for our misclassified sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*0HsY5IZa3OoajohXbkic-Q.png" /><figcaption>New Sample Weight for incorrectly classified sample, calculated (image is my own)</figcaption></figure><p>Our second formula is for <em>decreasing</em> the sample weights for the samples that were <em>correctly</em> classified. The formula is provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*PmDdU8mVqtjw_xTra7emrA.png" /><figcaption>New Sample Weight for correctly classified sample, formula (image is my own)</figcaption></figure><p>Let’s visualize this equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MnAtEZnijE6uIIS8YzkQA.jpeg" /><figcaption>New Sample Weight for correctly classified sample, visualization (image is my own)</figcaption></figure><p>When the amount of say is relatively large, we scale the sample weight by a value very close to zero. This makes the new sample weight very small.</p><p>If the amount of say for the last stump is relatively small, then we scale the sample weight by a value close to 1. This makes the new sample weight only a little smaller than the old one.</p><p>Let’s calculate our new sample weights for our three correctly classified samples. Note that this value is less than 0.25, which was the value of the first sample weight for these samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*HbXlKmpLAyGE6n-Fd1PjsQ.png" /><figcaption>New Sample Weight for correctly classified sample, calculated (image is my own)</figcaption></figure><p>Now that we have our new sample weights, we can put them into our data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4fjHDHpD3pIURXtPpJjhw.png" /><figcaption>Sample Weather Data with New Sample Weights (image is my own)</figcaption></figure><p>There’s one more step we have to complete before moving on. We have to normalize the new sample weights. As a reminder, this means adjusting each sample weight so that all four sample weights add up to 1. This can be done by dividing each sample weight by the sum of all new sample weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uy691-p3gM7DglroOpr7A.png" /><figcaption>Sample Weather Data with New Sample Weights, normalized (image is my own)</figcaption></figure><p>And finally, we no longer have any need for our first sample weights. So, our new sample weights become our current sample weights!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfhOiAW-GO_Y7tfRMFPfkg.png" /><figcaption>Sample Weather Data for second stump (image is my own)</figcaption></figure><p>Now that we have our sample weather data with sample weights based on the first stump, we can build our next stump. (And so on, and so forth! This is AdaBoost!).</p><h3>Setting Up Our Second Stump</h3><p>To build our second stump, we have two options.</p><ol><li>We can calculate a weighted Gini Index so that whichever variable does a good job of classifying previously misclassified samples gets chosen as the root of the second stump.</li><li>We can make a new collection of samples that contains duplicate copies of the samples with the largest sample weights. This is done by making a new, empty dataset. Then, for each row in the new, empty dataset, we would pick a random number between 0 and 1 and see where that number falls when we use the sample weights like a distribution. Then, we would fill the row accordingly. We would continue this process until all rows in the new collection of samples are filled.</li></ol><p>Once the method for setting up the second stump is chosen, this methodology will be used for all remaining stumps.</p><h3>Deciding Final Classification</h3><p>You may be asking yourself — once all stumps have performed classification, how does this forest of stumps decide on final classification for each sample? Here’s how it works for one sample. We’ll assume the target variable had two possible answers, just like our sample data — “Yes” and “No”.</p><p>First, we add up the amount of say for all stumps that classified “Yes”. Then, we do the same for all stumps that classified “No”. Whichever sum is greater wins as the ultimate classification of the sample.</p><p>This process is performed for all samples in the test dataset. Once this process is completed, so is the AdaBoost classification.</p><p>And that’s a wrap! If you liked my writing style and explanation techniques, check out these other articles:</p><ul><li><a href="https://medium.com/@curryrowan/understanding-simpsons-paradox-d97c0a5e68be">Understanding Simpson’s Paradox</a></li><li><a href="https://medium.com/@curryrowan/gradient-descent-explained-c3eaa2566c27">Gradient Descent: Explained!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92408a6713da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Random Forests: Part 2]]></title>
            <link>https://medium.com/@curryrowan/the-complete-guide-to-random-forests-part-2-934eabf35534?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/934eabf35534</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 19:55:24 GMT</pubDate>
            <atom:updated>2021-12-21T19:55:24.211Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The following article builds on </em><a href="https://medium.com/@curryrowan/the-complete-guide-to-random-forests-part-1-427c9cba8336"><em>The Complete Guide to Random Forests: Part 1</em></a><em>. If you’re unfamiliar with Ensemble Learning, Decision Trees, and/or Random Forests, I highly recommend clicking the link and reading that article first.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*MkeRi6EMvvZvUpHmQU0dWg.png" /><figcaption>Random Forests visualization thanks to <a href="https://ai-pool.com/a/s/random-forests-understanding">Hyacinth Ampandu</a></figcaption></figure><p>Random Forests are a supervised ensemble learning technique consisting of many Decision Trees. The algorithm uses bagging and feature randomness when building each individual tree to try and create an uncorrelated forest of trees whose prediction by committee is more accurate than that of any individual trees. In a classification problem, each tree votes and the most popular class is chosen as the final result.</p><p>This article will teach you how to build a Random Forests Model with the <strong>RandomForestClassifier </strong>module from <a href="https://scikit-learn.org/stable/">scikit-learn</a>.</p><p><em>The following tutorial only covers simple data preparation (splitting the dataset) before moving on to build the Random Forest Model. If you’re interested in data preprocessing steps, such as imputing missing values and performing encoding, you can access full code documentation and commented explanations through this </em><a href="https://www.kaggle.com/rowancurry/random-forests-90-5-accuracy?scriptVersionId=82938158"><em>Kaggle Notebook</em></a><em>.</em></p><h3>Objective</h3><p>The dataset used for this example is the <a href="https://www.kaggle.com/jsphyg/weather-dataset-rattle-package">Rain in Australia</a> dataset put together by Kaggle user <a href="https://www.kaggle.com/jsphyg">Joe Young</a>. The purpose of this dataset is to train classification models on the target variable <strong>RainTomorrow</strong> with the goal of determining whether it will rain the next day or not. This variable has a value of <em>Yes</em> if the rainfall for that day exceeded 1 mm and <em>No</em> otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Y7LR5G22LKoS2bNXcofPmA.png" /><figcaption>Countplot of Target Variable <strong>RainTomorrow</strong></figcaption></figure><p>Based on the plot to the left, we can see that there is an imbalance of data — most days out of the year, it does not rain. However, this imbalance is not cause for immediate concern because it accurately reflects the nature of weather. Also, data imbalances were addressed in preprocessing using the SMOTE technique.</p><h3>Data Preparation</h3><p>We’ll start by splitting the processed data into training and test datasets. Don’t forget to import “train_test_split” from sklearn.model_selection!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8d8hH7keJnitHUolV8KiZw.png" /></figure><p>Our proportions are 70% training and 30% test.</p><h3>Building the Model</h3><p>Next, we’ll build the model. This portion of the code uses the RandomForestClassifier from sklearn.ensemble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8IwfExglSxizyvg8573Kg.png" /></figure><p>Here we have the luxury of using 200 trees (as defined by n_estimators), which is one of the reasons our accuracy rate has a relatively high degree of correctness.</p><p>However, the Random Forest Model can be slow in generating predictions due to the sheer number of decision trees. This is because whenever a prediction is made, all the trees in the forest have to make a prediction for the same given input and then perform voting on it.</p><p>For this specific report, that’s totally fine, our dataset is small. But for large datasets that need to be processed quickly, a different algorithm or a smaller number of trees would need to be used.</p><p>Next, we’ll make our predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOOZPhMe668eoGxc-NVaGw.png" /></figure><p>Then, we’ll check our model’s accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmHLiuiTmzoG9whzN_63Ow.png" /></figure><p>As you can see, our model has an accuracy of about 90.5%, which isn’t bad — but let’s see if we can improve it.</p><h3>Random Forest Feature Importance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mVM_yOk7aGv4LuTIBhL_w.png" /></figure><p>The Random Forest module from scikit-learn has a really handy attribute called “feature importances”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*t_fP18AhnWXgaXDyiPR-dA.png" /></figure><p>We used this in our code above to investigate which features are helping us determine days when it will rain, and which will not (you’ll need to make sure you’ve imported pandas to use this method).</p><p>You can see our output for this code to the right.</p><p><em>Feature Importance</em> refers to various techniques used to calculate a score for all the input features of a model. The scores simply represent the “importance” of each feature.</p><p>Feature Importance is valuable for a variety of reasons. First, it helps you better understand the data that’s going into your model by showing you the relationship between the features and the target variable.</p><p>Second, in some cases it helps you improve your model’s performance through feature selection, which we’ll perform in the next section.</p><p>And finally, it helps you interpret your model. By calculating scores for each contributing feature, you’re able to more confidently communicate actionable insights to coworkers and stakeholders.</p><p>All of this is great, but it’s not super intuitive to interpret a list of numbers. Let’s look at the plot of feature importance for this first Random Forest Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*DwGibSOjYCbCQSw3VvhmHA.png" /><figcaption>Countplot of Feature Importance for first Random Forest Model</figcaption></figure><h3>Building the Model with Feature Selection</h3><p>Next, we’ll build a second Random Forest Model that runs on only the features deemed important once Feature Importance was analyzed. Since <strong>WindDir9am</strong>, <strong>year</strong>, and<strong> RainToday </strong>all had Feature Importance scores of under 0.02, we’ll drop them from the model and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQEvHXNgRJyhy97kK_LN7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYHxBZR4n8Q8RwbN-hE_sg.png" /></figure><p>Then, we’ll build a second Random Forest Model using the selected features and make predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwsCHVLLGqwhMi4MwOmPAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mHsMcv5Jsd7hFLga-_KdA.png" /></figure><p>And our accuracy rate is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLuxCAR3VZDYkIS-hBF_2Q.png" /></figure><p>We can see that accuracy goes down slightly. Thus we can conclude that while each feature has a differing level of helpfulness when it comes to determining whether it will rain tomorrow in Australia, it’s still necessary to include ALL features in order to achieve the highest possible degree of accuracy in this specific instance.</p><p>That’s a wrap! Thanks for reading- if you liked my tutorial-writing style, check out these other articles tacking similar lessons:</p><ul><li><a href="https://medium.com/@curryrowan/simple-quick-web-apps-in-r-6841fa58f8d9">Simple &amp; Quick Web Apps in R</a></li><li><a href="https://medium.com/@curryrowan/simplified-logistic-regression-classification-with-categorical-variables-in-python-1ce50c4b137">Simplified Logistic Regression: Classification With Categorical Variables in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=934eabf35534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Simpson’s Paradox]]></title>
            <link>https://medium.com/@curryrowan/understanding-simpsons-paradox-d97c0a5e68be?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d97c0a5e68be</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 21:06:33 GMT</pubDate>
            <atom:updated>2021-12-20T21:06:33.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC1Z5Y7o19LibX2Dulv9LQ.png" /><figcaption>simplified visualization of Simpson’s Paradox thanks to <a href="https://en.wikipedia.org/wiki/Simpson%27s_paradox">Wikipedia</a></figcaption></figure><p>As someone working with data — whether you’re a Data Scientist, a Data Analyst, or a Statistician — it’s essential to make sure that the conclusions you draw are well-founded. This is where Simpson’s Paradox comes in.</p><p>Before diving into the definition of Simpson’s Paradox, let’s consider the following famous example.</p><p>In 1973, a report revealed that UC Berkeley’s graduate school had accepted 44% of their male applicants, and only 35% of their female applicants. Gender discrimination seems like it would be a straightforward, clear-cut conclusion to come to after looking at this data, right?</p><p>Wrong! The school, fearing legal action, commissioned a statistician to investigate. The statistician decided to subdivide applicants based on whether they applied to the natural sciences departments or the social sciences departments. They found that in the natural sciences, 80% of women and 46% of men were admitted, while in social science, 20% of women and 4% of men were admitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2P8GA0TqBVHgunicHbOww.png" /><figcaption>Data Table thanks to The Graduate Division, University of California, Berkeley</figcaption></figure><p>The statistician determined, based on this dataset, that men were more likely to apply to the natural sciences and women were more likely to apply to the social sciences. Since the social sciences had a lower acceptance rate than the natural sciences, when the variable department was ignored, data analysis suggested a misguided conclusion. When the variable was accounted for, the statistician realized that the opposite of what the university feared was true: women were more likely to be accepted to graduate school.</p><p>The statistician concluded that both gender and admissions related to a third variable, previously unaccounted for: department. This is Simpson’s Paradox.</p><h3>Defining Simpson’s Paradox</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiY2mn7Cv92QF3C5Yg0-ew.png" /><figcaption>picture thanks to <a href="https://paulvanderlaken.com/2017/09/27/simpsons-paradox-two-hr-examples-with-r-code/">Paul V</a></figcaption></figure><p>Before diving into Simpson’s Paradox, we’ll define the term <em>paradox</em>. According to Websters,</p><blockquote>a paradox is a seemingly absurd or self-contradictory statement or proposition that when investigated or explained may prove to be well founded or true .</blockquote><p>Simpson’s Paradox, sometimes called the Yule-Simpson effect, is an <em>association paradox</em>. Association paradoxes can occur between continuous and categorical variables. For example: gender (categorical) and acceptance rate (numerical).</p><p>Furthermore, Simpson’s Paradox is a special sub-type of association paradox called a <em>reversal paradox</em>. Reversal paradoxes are when marginal and partial associations between two variables have different signs. For example: according to the initial false conclusion, if the variable gender is equal to female, the acceptance rate was expected to be lower than for the value male. We can consider this a negative correlation.</p><p>On the other hand, according to the correct conclusion, if the variable gender is equal to female, the acceptance rate was actually higher than for the value male. We can consider this to be a positive correlation. Thus, the <em>marginal and partial associations between two variables have different signs</em>.</p><p>Now that we understand what an association paradox and a reversal paradox are, we can define Simpson’s Paradox:</p><blockquote>Simpson’s Paradox is an effect that occurs when the marginal association between two categorical variables is qualitatively different from the partial associations between the same two variables after controlling for one or more other variables.</blockquote><p>More simply put: Simpson’s Paradox describes a situation in which a trend or relationship that is observed within multiple groups disappears or reverses when the groups are combined.</p><p>This disappearance or reversal is due to the existence of a <em>confounding variable</em>. A confounding variable is a variable that is correlated with both the dependent variable and the independent variable. Our confounding variable in the UC Berkeley example was department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhRM73JHGv6UqeDV1TYLcQ.png" /><figcaption>Image thanks to <a href="https://www.statology.org/confounding-variable/">Zach</a> from Statology</figcaption></figure><p>Let’s consider another example to better understand what a confounding variable is. When investigating the causal relationship between smoking and death rate, age is a confounding variable. This is because as age increases, the death rate also increases, and the smoking rate decreases. If the statisticians investigating this causal relationship fail to control the variable age, they’ll run into Simpson’s Paradox.</p><p>And that’s a wrap! Hopefully this article helped explain why hidden variables could be lurking in your data. If you enjoyed this piece on Simpson’s Paradox and are interested in reading more, check out the following articles.</p><ul><li><a href="https://medium.com/@curryrowan/the-three-bs-bootstrapping-bagging-boosting-43df4b372a6a">The Three Bs: Bootstrapping, Bagging, &amp; Boosting!</a></li><li><a href="https://medium.com/@curryrowan/simple-quick-web-apps-in-r-6841fa58f8d9">Simple &amp; Quick Web Apps in R</a></li><li><a href="https://medium.com/@curryrowan/simplified-logistic-regression-classification-with-categorical-variables-in-python-1ce50c4b137">Simplified Logistic Regression: Classification With Categorical Variables in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d97c0a5e68be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Three Bs: Bootstrapping, Bagging, & Boosting!]]></title>
            <link>https://medium.com/@curryrowan/the-three-bs-bootstrapping-bagging-boosting-43df4b372a6a?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/43df4b372a6a</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 20:03:58 GMT</pubDate>
            <atom:updated>2021-12-16T20:03:58.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*euZfz1OhnXJPnMFgbKwPww.jpeg" /></figure><p>Many important ensemble learning algorithms are based off of the Three Bs. Understanding these fundamental Machine Learning concepts is essential to using ensemble learning techniques successfully.</p><p>If you’ve never encountered ensemble learning before, I suggest quickly checking out this <a href="https://medium.com/@curryrowan/427c9cba8336">resource</a>.</p><p>The following article will take you through a short and sweet (and comprehensive!) explanation of these concepts.</p><h3>BOOTSTRAPPING!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*YYom-NKDaZ-B7RB_891DgQ.png" /></figure><p>Bootstrapping is a simple concept used as a building block for more advanced algorithms, such as <a href="https://towardsdatascience.com/understanding-adaboost-2f94f22d5bfe">AdaBoost</a> and <a href="https://machinelearningmastery.com/gentle-introduction-xgboost-applied-machine-learning/">XGBoost</a>.</p><p>Bootstrapping refers to <em>bootstrap sampling</em>. This is a resampling method that uses random sampling <em>with replacement</em>. “With replacement” means that it’s possible for an observation that was already chosen to be chosen again.</p><p>Bootstrapping has more applications than building algorithms. Under the assumption that the sample is representative of the population, bootstrap sampling can be conducted to provide an estimate of the sampling distribution of a sample statistic.</p><p>This application of bootstrap sampling can be super helpful when you’re dealing with a sampling distribution that’s not large enough to assume that the sampling distribution is normally distributed, but you need to estimate the parameters of a population.</p><h3>BAGGING!</h3><p>Bagging, which is short for <em>bootstrap aggregating</em>, builds off of bootstrapping. Bootstrap aggregating describes the process by which multiple models of the same learning algorithm are trained with bootstrapped samples of the original data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdYepJvb4Yj1NnuBp2d5Uw.png" /></figure><h3>BOOSTING!</h3><p>Boosting is Bagging 2.0. In this process, each individual model is built sequentially by iterating over the previous model. This means that data points that are falsely classified by the previous model are emphasized in the following model. Understandably, this increases the overall accuracy of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99qe8RUmPsT_OFkbsw5hHA.jpeg" /></figure><p>And there you have it! A quick and clear explanation of the three Bs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43df4b372a6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Random Forests: Part 1]]></title>
            <link>https://medium.com/@curryrowan/the-complete-guide-to-random-forests-part-1-427c9cba8336?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/427c9cba8336</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 19:35:06 GMT</pubDate>
            <atom:updated>2021-12-16T19:35:06.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohrCc7WLsN6VxrKPGOnu_w.jpeg" /><figcaption>photo thanks to <a href="https://unsplash.com/@michaelbenz">Michael Benz</a></figcaption></figure><p>I hear the term “Random Forest” and immediately in my minds eye I’m walking through a redwood grove, smelling salty coastal air and inhaling the rich scents of a forest. However, Random Forests themselves are not quite as romantic as skipping through a redwood forest drenched in Bay Area fog.</p><p>Random Forests are a supervised, ensemble learning algorithm based on Decision Trees. If any of those terms are unfamiliar to you, don’t panic! This article, the first in a series of two, will take you through a simple, clear, and thorough explanation of all concepts involved in the making of Random Forests.</p><h4>WHAT IS ENSEMBLE LEARNING?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UpMaRrS9z71LaQgN_coxbA.png" /></figure><p><em>Ensemble learning</em> is a method where multiple machine learning algorithms are used at the same time. This strategy helps achieve a higher predictive performance than if you were to use an individual algorithm by itself. The reason this approach works so well is quite intuitive. Consider the following example:</p><p>Each student in a standard-size classroom is given the same tricky math problem, and each student is told to solve the math problem individually. Some students finish right away, some students take a really long time, and each solution turned in has varying degrees of correctness.</p><p>Now, consider the same situation, but the students are required to work together to solve the problem. The combined brainpower of a whole room of people most likely results in a well-thought out solution with a high degree of correctness.</p><p>Ensemble learning works in the same way. By combining the “brainpower” of multiple algorithms, we’re much more likely to build an effective and trustworthy model.</p><h4>WHAT ARE THE TREES THAT MAKE UP THE FOREST?</h4><p>Random Forests consist of a large number of individual decision trees that operate as an <em>ensemble</em>. Let’s dive further into the structure of an individual decision tree, so we can better understand the way Random Forests operate.</p><p>In the simplest possible terms: a <em>Decision Tree</em> asks a “question”, and then classifies the “person” based on their answer. Let’s consider the image below. This is an example of a simple Decision Tree that helps you decide what you should do with your day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*E-DtYJBHD1XWeH2uEssPLw.jpeg" /><figcaption>photo courtesy of <a href="https://medium.com/@lorrli">Lorraine Li</a></figcaption></figure><p>The very top of the tree, where the question “Work to do?” has been placed, is called the <em>root node</em>. If a person answers yes to this question, the tree takes them to the shaded box that says “Stay in”. Since this box has lines traveling toward it, but not away from it, it’s called a <em>leaf node</em>, and denotes one of the five possible destinations for data traveling through this Decision Tree. All of the shaded boxes in this example are leaf nodes.</p><p>If a person answers no, they don’t have any work to do, then the tree directs them to a second question, “Outlook”, asking about the current weather. This second question is called an <em>internal node</em>. Internal nodes have lines traveling toward them and away from them. All non-shaded boxes in the above example are internal nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*gl6G0xovOGkz67YKSYcFQw.png" /></figure><p>To the right, we can see a decision tree example that includes both binary and numerical data at each internal node. We can begin to imagine how large, complex decision trees might look for large, complex data sets.</p><p>You might be wondering how each conditional statement is assigned to its corresponding internal node. We’ll start by discussing how to determine which conditional statement should live at the top of the tree (in the root node).</p><p>This is determined by looking at how well each possible conditional statement predicts the necessary variable, and then calculating the <em>impurity</em> for that outcome. If a conditional statement does not perfectly predict a label, it’s considered “impure”. We then calculate the relative impurities to determine which conditional statement has the least amount of incorrect results.</p><p>There are many ways to calculate impurity for decision trees, such as Gini Impurity, information gain, and gain ratio.If you’re interested in learning more about different ways to calculate impurity scores, check out this <a href="https://www.bogotobogo.com/python/scikit-learn/scikt_machine_learning_Decision_Tree_Learning_Informatioin_Gain_IG_Impurity_Entropy_Gini_Classification_Error.php#:~:text=There%20are%20three%20commonly%20used,Gini%20index%2C%20and%20Classification%20Error.">article</a>.</p><p>After the root node has been chosen, the Decision Tree algorithm works its way down the tree using the same methodology for internal nodes until they each end in a leaf node.</p><p>And there you have it, Decision Trees!</p><h4>AND NOW … THE MOMENT YOU’VE BEEN WAITING FOR … THE RANDOM FOREST ALGORITHM!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*MkeRi6EMvvZvUpHmQU0dWg.png" /></figure><p>As stated previously, Random Forests are a supervised, ensemble learning algorithm based on Decision Trees. The Random Forest algorithm consists of many decision trees, and it uses bagging and feature randomness when building each individual tree. This creates an uncorrelated forest of trees whose prediction by committee is more accurate than that of any individual trees.</p><p>Bagging, which is short for <em>bootstrap aggregating</em>, is the process by which multiple models of the same learning algorithm are trained with bootstrapped samples of the original data set. The <em>bootstrap sampling</em> method is a resampling method that uses random sampling with replacement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*F5jHRWCpYqGhaPWCusfJhQ.png" /></figure><p>In a classification problem where Random Forest is used, each tree “votes” and the most popular class is chosen as the final result. In a regression problem where Random Forest is used, the average of all the tree outputs is considered to be the final result.</p><p>The steps of the Random Forest algorithm for classification can be described as follows.</p><ol><li>Select random samples from the dataset using <em>bootstrap aggregating</em>.</li><li>Construct a Decision Tree for each sample, and save the prediction results from each tree.</li><li>Calculate a vote for each predicted result.</li><li>Determine which predicted result has the most votes. This becomes your final prediction.</li></ol><p>While Random Forests are a highly accurate method due to the sheer number of Decision Trees involved in the algorithm, they can be slow in generating results for the exact same reason. Also, the model can be difficult to interpret when compared to a single Decision Tree.</p><p>However, Random Forests are still a better choice of algorithm (most of the time) due to their computational power, adeptness at handling missing values, and usefulness when it comes to relative feature importance.</p><p>And there you have it! Random Forests. Stay tuned for Part 2, where we’ll build our own classification model using the Random Forest algorithm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427c9cba8336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple & Quick Web Apps in R]]></title>
            <link>https://medium.com/@curryrowan/simple-quick-web-apps-in-r-6841fa58f8d9?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6841fa58f8d9</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r-shiny]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 20:05:19 GMT</pubDate>
            <atom:updated>2021-12-01T20:05:19.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*VfvMROpWuTRKdgom0TuIpg.png" /></figure><p><a href="https://shiny.rstudio.com/">R Shiny</a> is an R package that allows you to build interactive web apps through R. It doesn’t require any previous knowledge of UI, which is ideal for people who lack front-end backgrounds. Shiny allows you to publish web apps on a webpage, or you can embed your R Shiny apps in an R Markdown document.</p><p>In this article, we’ll learn how to build a simple time series R Shiny web app.</p><p>This tutorial is based off of a web app I created using R Shiny, which you can find <a href="https://rowancurry.shinyapps.io/book-time-series/">here</a>. This app uses data from the <a href="https://www.kaggle.com/jealousleopard/goodreadsbooks">2019 Goodreads Dataset</a>.</p><p>First, we’ll need to review the <em>basic structure of an R Shiny App</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*CIVbzX5b1IEyeugbCHL4cw.png" /></figure><p>There are three components of an R Shiny App:</p><ol><li>a <strong>user interface</strong> object</li><li>a <strong>server</strong> function</li><li>a call to the <strong>shinyApp</strong> function</li></ol><p>The user interface (ui) object determines the layout of your app. Here, you’re able to manipulate the appearance of your app.</p><p>The server function communicates the instructions needed to build your app. For example, if your goal was to present a histogram, the code needed to create that plot would go here.</p><p>The call to the shinyApp function takes the ui object and the server function and combines them to create the Shiny app object.</p><p>Now we’ll begin to build our example app. If you’d like a more in depth look at R Shiny before continuing, R Studio has a great tutorial you can find <a href="https://shiny.rstudio.com/tutorial/">here</a>.</p><h4>Step 1: Setting Your Directory</h4><p>Every Shiny app has the same structure. This structure consists of an app.R file that contains the ui object and the server function. You can create your own file by copying the code in the “basic structure of an R Shiny App” section, or you can choose the “Shiny Web App…” option under “new file” in R Studio.</p><p>You’ll want to make sure that your Shiny app has its own directory. This is recommended because you run the Shiny app by passing the name of the directory to the function <strong>runApp</strong>. For example, my directory is called “book-time-series”, so when I want to run my app, my code will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*MmQuOJrrqKWJcUOHZLHZMA.png" /></figure><p>Once you have your app.R file set up in its own unique directory, you’re ready to move on.</p><h4>Step 2: Importing and Cleaning Your Data</h4><p>Now, we’ll import our data. You can download the dataset we’ll be using through the link in the introduction, or by clicking <a href="https://www.kaggle.com/jealousleopard/goodreadsbooks">here</a>.</p><p>When you need to use a dataset for your Shiny app, you store the dataset in the same directory as app.R by creating a subdirectory called “data” and storing your dataset in that subdirectory.</p><p>Once you’ve done this, you’ll be able to access your data in app.R.</p><p>We’ll need the following libraries for our app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*6lU8NV2KmY02GW7R0t6LPQ.png" /></figure><p>Then we’ll need to open the data at the beginning of our app.R file. This is also where you’ll do any necessary data cleaning and preprocessing.</p><p>As you can see below, we’re uploading the data into app.R, as well as doing some preliminary data cleaning (dropping null values, transforming column types from factor to float).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Trk7iq6n2GY1ZFwC6617Cg.png" /></figure><p>Next, we’ll need to do some data preprocessing. If you followed the link earlier to the project we’ll be building, you’ll know that we’re building a time series app. And after looking at the data, you probably noticed that the column “publication_date” was in the form dd/mm/yyyy.</p><p>In the following section of code, we’ll isolate the years and build a few tibbles that will help us create the plots we want for the Shiny app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FD12E-h0nlCdeB8Ll3UvZA.png" /></figure><h4>Step 3: Building Your UI Function</h4><p>Now that we have the necessary data, we can begin building our UI object.</p><p>The function <strong>fluidPage</strong> is used by Shiny to create a display that can automatically resize to the dimensions of the user’s browser window. You then add elements to fluidPage to build your Shiny app.</p><p>We’ll use <strong>titlePanel</strong> and <strong>sidebarLayout</strong>. These two elements create the standard Shiny app: a basic Shiny app with a sidebar.</p><p>The element sidebarLayout takes the argument <strong>sidebarPanel</strong>, which is where you provide the user with any necessary information and input options; and <strong>mainPanel</strong>, which is where you tell your Shiny app what the center-stage output of your app will be (in our case, a time series app).</p><p>Here is our code for the UI object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chyxUqWug1668opwL5xaiQ.png" /></figure><p>As you can see, in our sidebarPanel argument we pass the argument <strong>helpText</strong>, which lets the user know what our Shiny App is doing. We also pass the argument <strong>selectInput</strong>, which creates a drop down menu of the different dependent variables the user can choose. We add a label to this argument that lets the user know what will happen when they select a dependent variable from the drop down menu, and we choose a default dependent variable to display when the app first opens.</p><p>In our mainPanel argument, we pass the function <strong>plotOutput</strong> with the argument “plot”. This will help us build our server function.</p><h4>Step 4: Building Your Server Function</h4><p>Next, we’ll build our server function. Our function takes two arguments, <strong>input</strong> and <strong>output</strong>.</p><p>We defined our input as “var” and our output as “plot” when designing our ui function. As you can see in the following code example, these definitions are important for building our server function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bWoGJNnYZRgBl6SpCmv0w.png" /></figure><p>As you can see above, we define the ggplot arguments that differ according to which dependent variable is chosen. Then we plot our time series graph.</p><h4>Step 5: Running Your R Shiny App!</h4><p>Our last addition to our app.R file: the shinyApp function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*rAG4QN8Z3smKq-CZuWnICw.png" /></figure><p>Finally, it’s time to deploy your R Shiny app! Yay!</p><p>Use the code provided in “Step 1: Setting Your Directory” to run your app. Your output should look something like this for each dependent variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwqoDyrg49KGe81u0WizJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7tmbiIN1xa6oUl4Kh-51g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3tkNtP4hmDFfQJPEX4lCg.png" /></figure><p>And there you have it! Your first R Shiny Web App!</p><p>If you’d like to publish your app on shinyapps.io, check out <a href="https://statsandr.com/blog/how-to-publish-shiny-app-example-with-shinyapps-io/">this great resource</a> I used for figuring out how to publish my own app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6841fa58f8d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Closer Look at Outliers]]></title>
            <link>https://medium.com/@curryrowan/a-closer-look-at-outliers-58f553ebab2d?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/58f553ebab2d</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 01:40:57 GMT</pubDate>
            <atom:updated>2021-11-23T01:40:57.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhulspMXKeHBI85nuRJmJA.png" /><figcaption>picture thanks to <a href="https://medium.com/@sergiosantoyo.92">Sergio Santoyo</a></figcaption></figure><p>It’s always hard figuring out when to include outliers in analysis and when to drop them. This article aims to make this aspect of data analysis much simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*soyo2_VCMgu0Kd6Gwspzrw.png" /><figcaption>picture thanks to <a href="https://blog4ritika.medium.com/">Ritika Singh</a></figcaption></figure><p>First, we’ll remind ourselves of the definition of an outlier. An outlier is a value that appears to be far removed and divergent from a set pattern in a sample. Outliers can be caused by events such as data entry errors, sampling problems, and natural variation.</p><p>In this case, outliers increase variability in our data, which means that removing outliers would have a positive impact on your data analysis. However, sometimes outliers are not caused by the events listed above, and can be informative about the subject area. When this happens, you might want to keep them around to understand why they occur, and if they might happen again.</p><p>For a more in-depth look at the causes of outliers, the impact of outliers, and methods to identify outliers, check out <a href="https://medium.com/analytics-vidhya/its-all-about-outliers-cbe172aa1309">this article</a>.</p><p>We’ll continue our closer look at outliers by examining an example of data analysis with outliers in R. For this example, I’ll be pulling from a project I posted on Kaggle that performs exploratory data analysis on the 2019 Goodreads dataset. For full code documentation, check out my project <a href="https://www.kaggle.com/rowancurry/eda-on-goodreads-dataset">here</a>.</p><p>I chose Exploratory Data Analysis (EDA) as a way to look more closely at outliers because of EDA’s relationship to predictive modeling. In short: by understanding the structure of your data before performing analysis, you set yourself up for success.</p><p>We’ll start by looking at <strong>a case where outlier analysis is needed</strong>. In this first case, we’ll examine the top five authors with the greatest number of total reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZBtZn6ZaPDcj6P-TbJHqg.png" /></figure><p>We can already see that there are some very famous names on this list: J.K. Rowling (Harry Potter), J.R.R. Tolkien (Lord of the Rings), Stephenie Meyer (Twilight), etc.</p><p>The information concerning these very famous authors is important when we’re comparing famous authors to each other, but it’s equally important to acknowledge that most authors are not and never will be this famous. This means that if we want valuable information about books in general, outlier analysis may be necessary in this instance.</p><p>To perform outlier analysis, we’ll use <a href="https://www.statisticshowto.com/probability-and-statistics/interquartile-range/">IQR</a> methodology:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5FF3e--hCG0qc7LFHGr1Q.png" /></figure><p>We can already see that the high cutoff of 11862 is much lower than the total number of reviews for the famous authors we looked at before. Let’s take another look at our analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyLiSK3H9efXs957M7MIUg.png" /></figure><p>Here we go! Now, we’ll be able to understand relationships between books with a similar audience size much more easily.</p><p>Next, we’ll examine <strong>an example of outliers best left alone</strong>. First, we’ll look at the plot output for the total number of reviews per year from 1900 to 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpxAc0U2QddSVQJrZAgc0w.png" /></figure><p>As we can see, total reviews remained on a dramatic increase through the dot com boom (access to the internet — everyone becomes a critic) all the way up into the early 2000s. Then, in 2008 (recession hits!) the number of reviews quickly plummet, as perhaps people find themselves with less time to read and fewer resources that allow access to books and reviewing systems. There is clearly lots of valuable information in this graph.</p><p>Now let’s examine the plot output after outlier analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3HzIBtbtkAXkQO-wPAlew.png" /></figure><p>We can see that the plot has the same overall structure, but without many of the potentially informative geographic peaks and dips that the plot with outliers had. This is a solid way to determine that outliers will indeed be an important part of analysis concerning total number of reviews over the years.</p><p>And there we have it, a closer look at outliers. I hope this article helped you to think more deeply about outliers and their relevancy to your own data analysis methodology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58f553ebab2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent: Explained!]]></title>
            <link>https://medium.com/@curryrowan/gradient-descent-explained-c3eaa2566c27?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3eaa2566c27</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science-training]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 20:30:19 GMT</pubDate>
            <atom:updated>2021-11-19T20:30:19.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tr43WwL0B3oRKG5FqzlpNw.jpeg" /></figure><p>Gradient descent is a popular and effective optimization strategy used when training data-based models. Gradient descent’s popularity is due to the fact that it can be combined with any algorithm. Read on to learn more!</p><p>Before we get into gradient descent as an optimization strategy, we’ll need to review what a gradient is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*feeECJqEk6rdc7JhxoCjCw.gif" /><figcaption>gradient vectors of the surface of cos(x)sin(y)</figcaption></figure><p>You might remember the term gradient from calculus as describing the slope of a function. For our purposes, the definition is essentially the same.</p><p>A <strong>gradient</strong> simply measures the change in all weights with regard to the change in error. This means that the lower the gradient, the flatter the slope, and the slower a model learns. The opposite is also true: the higher the gradient, the steeper the slope, and the faster a model will learn.</p><p>Now we can define <strong>gradient descent</strong>. This optimization algorithm finds the values of a function’s parameters that minimize the cost function. The cost function is simply the method of evaluation chosen to communicate the performance of an algorithm. For a more in depth look at cost functions, check out this <a href="https://www.analyticsvidhya.com/blog/2021/02/cost-function-is-no-rocket-science/">article</a>.</p><p>Gradient descent finds these optimal parameters by determining the local minimum of a differentiable function through an iterative process. The following equation describes gradient descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Vw9XCMby7dgEXr2Cn7dHBQ.png" /><figcaption>Gradient Descent: A Simplified Equation</figcaption></figure><p>In this equation:</p><ol><li><strong>b</strong> describes the next iteration</li><li><strong>a</strong> describes the current iteration: gradient descent starts with random values of a and b and then keeps updating these values based on the first-order partial derivatives</li><li>the minus sign describes the minimization aspect of gradient descent</li><li><strong>𝛾</strong> describes the learning rate, which will be discussed more in depth further on in the article</li><li>the gradient term describes the direction of steepest descent</li></ol><p>The <strong>learning rate</strong>, which is determined by the builder of the model, defines how large (or small) the iterative steps gradient descent takes in the direction of the local minimum will be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*An4tZEyQAYgPAZl396JzWg.png" /><figcaption>learning rate visualizations thanks to <a href="https://www.jeremyjordan.me/nn-learning-rate/">Jeremy Jordan</a></figcaption></figure><p>Determining an adequate learning rate is important. If the steps are too large, gradient descent may never reach the local minimum, as displayed above. If the steps are too small, gradient descent will eventually reach the local minimum but it will take much too long to get there.</p><p>You can check if your learning rate is doing well by plotting the number of iterations on the x-axis and the value of your cost function on the y-axis as the optimization runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*X5QbtfhszYNBSV6DZzbT7A.jpeg" /><figcaption>learning rate visualization thanks to <a href="https://towardsdatascience.com/https-medium-com-dashingaditya-rakhecha-understanding-learning-rate-dd5da26bb6de">Aditya Rakhecha</a></figcaption></figure><p>This is an excellent way to immediately spot how appropriate your learning rate is. If gradient descent is behaving in an effective way, the cost function will decrease after every iteration. When the cost function stops decreasing, we say that gradient descent has <em>converged</em>.</p><p>While there are some algorithms that can automatically tell you when convergence has occurred, they require you to define a convergence threshold beforehand, which is immensely difficult to predict. For this reason, plots like the one above are your best bet for examining the performance of your gradient descent optimization, as well as for figuring out when it has converged.</p><p>There are three different types of gradient descent:</p><ol><li><strong>Batch Gradient Descent</strong>: This is classical gradient descent, also referred to as “vanilla” gradient descent. This method calculates the error of each example within the training dataset, but only updates the model after all training samples have been evaluated. This whole process is one cycle (training epoch). While this process is computationally efficient (it produces a stable convergence and a stable error gradient), this efficiency sometimes leads to a state of convergence that isn’t the absolute best a model can do.</li><li><strong>Stochastic Gradient Descent (SGD)</strong>: This method of gradient descent calculates the error of each training observation individually. SGD uses each observation to estimate the gradient, and then takes a step in that direction. While each individual observation provides a poor estimate of the true gradient, if there is enough randomness, the parameters will converge to an adequate global estimate. SGD also works very well for large datasets: since it only considers one observation at a time, it can handle extremely large datasets that don’t fit in memory.</li><li><strong>Mini Batch Gradient Descent</strong>: This method of gradient descent is the best of both worlds. It splits the training dataset into small batch sizes and updates gradient descent for each of these batches. This creates a balance between the efficiency of batch gradient descent and the power of SGD. This is the go-to algorithm when training a neural network, as well as the most common type of gradient descent associated with deep learning.</li></ol><p>So there we have it! Gradient Descent, explained. Stay tuned for an article (from me) on how to implement gradient descent — and in the meantime, check out these great resources:</p><p><a href="https://towardsdatascience.com/implement-gradient-descent-in-python-9b93ed7108d1">Implementing Gradient Descent in Python</a></p><p><a href="https://machinelearningmastery.com/gradient-descent-optimization-from-scratch/">Implementing Gradient Descent Optimization from Scratch</a></p><p><a href="https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931">Linear Regression using Gradient Descent</a></p><p><a href="https://towardsdatascience.com/a-step-by-step-implementation-of-gradient-descent-and-backpropagation-d58bda486110">A Step-by-Step Implementation of Gradient Descent and Backpropagation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3eaa2566c27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplified Logistic Regression: Classification With Categorical Variables in Python]]></title>
            <link>https://medium.com/@curryrowan/simplified-logistic-regression-classification-with-categorical-variables-in-python-1ce50c4b137?source=rss-416f2c39f98b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce50c4b137</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Rowan Curry]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 21:45:23 GMT</pubDate>
            <atom:updated>2021-10-25T21:45:23.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgAlWcV-GwhipVkDwATUoA.jpeg" /></figure><p>Logistic Regression is an algorithm that performs <strong>binary classification</strong> by modeling a dependent variable (Y) in terms of one or more independent variables (X). In other words, it’s a generalized model that predicts the probability that an event will occur. Specifically, Logistic Regression uses regular linear regression to model the ‘logit’ function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxSl-5t5h3qC_sGqPJq7FA.png" /></figure><p>This function returns output between 0 and 1 for all possible values of X. A visual representation of the <strong>Logistic (Sigmoid) Function</strong> follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*-T9ykgInQzpk7SmqdtZu4g.png" /><figcaption>The Sigmoid Function</figcaption></figure><p>In order to implement the Logistic Regression function, the “LogisticRegression” function from the sklearn will be used.</p><h4>Evaluating Model Performance</h4><p>After building the Logistic Regression model, we’ll evaluate the model’s performance on a test dataset using a<strong> Confusion Matrix</strong>. This is a helpful performance measurement for when model output can be two or more classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*5uZwIsfCUt0Rb9LYJ53yKQ.jpeg" /><figcaption>Confusion Matrix</figcaption></figure><p><strong>TP</strong> stands for <strong>True Positive</strong>. This occurs when you predict a positive result and your prediction is correct. <strong>TN</strong> stands for <strong>True Negative</strong>, which occurs when you predict a negative result and your prediction is correct.</p><p><strong>FN </strong>stands for <strong>False Negative</strong>. This occurs when you predict a negative result and the actual value is positive. <strong>FP</strong> stands for <strong>False Positive</strong>, which occurs when you predict a positive result but the actual value is negative.</p><p>This Confusion Matrix will be used to evaluate our Logistic Regression model by explaining the model in terms of Recall, Precision, Sensitivity (f1-score), and Support.</p><p><strong>Recall</strong> describes how many positive classes we predicted correctly. It’s calculated using the equation TP/(TP + FN).</p><p><strong>Precision</strong> describes how many classes were actually positive out of all of the classes we predicted as positive. It can be found using the formula TP/(TP + FP).</p><p>The <strong>f1-score</strong>, or <strong>Sensitivity</strong>, describes the balance between Recall and Precision. This metric will alert any potential imbalances in model performance. It can be summarized as the percent of positive predictions that were correct. It’s calculated using the equation 2*(Precision*Recall)/(Precision + Recall).</p><p><strong>Support</strong> is the number of samples of the true response that lie in that class. Support won’t change between models. Instead, it describes the evaluation process.</p><p>In order to evaluate the model’s performance using a Confusion Matrix, the “classification_report” function from sklearn will be used.</p><h4>Dataset &amp; Variable Descriptions</h4><p>The <a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing">Portuguese Bank Marketing Data Set</a> from the UCI Machine Learning Repository will be used to build the Logistic Regression Model. This data describes the results of direct marketing campaigns for a Portuguese banking institution. For this model, the bank-full.csv file will be used.</p><p>There are seventeen input variables: examples include age, job, marital status, month, etc. There is one output variable which describes whether or not the customer agreed to subscribe to a long term deposit. This binary output variable has two possible values: “yes” and “no”. More information about each variable can be found through the link above.</p><h4>Preliminary Data Visualizations &amp; Data Cleaning</h4><p>The project begins by importing all libraries needed for data preprocessing, data visualization, and for building and evaluating the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPYmvUi_dXMr5P5oM8SZvQ.png" /></figure><p>We’ll start by opening the file and checking our data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEKKIyWKKFQ3TnW4r8KVCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvB24coRkQ_X2yc2yElP7w.png" /></figure><p>Next we’ll check our dataset for null values using seaborn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdvIuzPnyXFnldniyigp9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEwnZlK69xCzxNkwFQhIFg.png" /></figure><p>Luckily for us, there are no null values. This makes the data cleaning process very simple.</p><p>Next, we’ll visually explore the data before building our model. It’s always a good idea to play around with data before using it to build a model. This can provide important information about the data that will become essential later when you begin attempting to improve the classification rate of your model.</p><p>We’ll start with a visualization of our output variable. Remember, this variable describes how many people agreed to subscribe to a long-term deposit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zK24RxLQbW1WykoAtT57g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-UYh-xKI7_2sDQOC-bPBA.png" /></figure><p>We can see that the number of people who refused far outweighs the number of people who said yes. This is important to remember as we start thinking about how to build our model.</p><p>We’ll do a couple more visualizations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCUgfzakOpSdIK_rQkPM6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2R8f4F4-vM1OfQoij_SXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2OsMWtJOrsqupXZ7p48VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ48COxbdedCviRhp9UJIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2PVI93kq-rqko6a_KuIOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pj0iFpcA--OFkwiBWjHEMw.png" /></figure><p>We can see from the countplot of the output variable and housing status of customers that whether or not a customer has permanent housing may have an impact on the likelihood of a yes. From the next plot, we can make an educated guess that age will not have a significant impact on a customer’s decision. For the countplot of the output variable according to whether or not a customer has defaulted on a loan, we can see that there is not a large enough population of customers who did default on a loan to help the model predict a customer’s decision.</p><p>These are just a few of the visualizations that can (and should) be done to explore the data.</p><h4>Data Preparation: Converting Categorical Features</h4><p>At this stage, we need to change the categorical variables to a format that our Linear Regression model will understand. We can do this by converting categorical features to dummy variables. First, we’ll double-check which features are categorical:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*964TKBCefW9xPQx3Qe2sVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOCvFNUfTwZe1L_sQcHDrw.png" /></figure><p>Now, we’ll convert all “non-null object” columns to dummy variables using the following process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIDhTj-narFjLgrsAZd-MA.png" /></figure><p>Now, we can see the new columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ0hED17PskYard53M56WA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqhy3Foqjdp5jrWRJPPMZg.png" /></figure><p>Finally, we need to convert our labels and drop any nonsense/unhelpful columns. Notice that in the df.drop() stage of the code above we dropped the ‘default’ column since we concluded during preliminary visualizations that it did not provide enough information to be helpful to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDqfR0XbkbmGNxTd-Ph2Gg.png" /></figure><h4>Data Preparation: Train, Test, Split</h4><p>We will now split our data into training data sets and test data sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6RbRLBk3bRoO2tWr9kZ1Q.png" /></figure><h4>Building the Model</h4><p>Now that we have our training and test data sets, we can train our model and make predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QmfR1eJAHq37LWzh8SMsQ.png" /></figure><p>As you can see, the argument “class_weight = ‘balanced’” was passed to the model. This is due to what we noticed in our very first data visualization — that the number of people who refused to subscribe to a long term deposit was much larger than the number of people who agreed.</p><h4>Model Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPPHOS24KgRBNRNjodmsXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTSRGGfa5AwTGP8CpA3AgA.png" /></figure><p>We can see that our model has a 97% precision rate for customer refusals and a 39% precision rate for customer agreements. This is no doubt a result of our data imbalance.</p><p>To go into a deeper analysis of this classification report, reference the definitions in the “Evaluating Model Performance” section of the introduction.</p><h4>Feature Importance</h4><p>To better understand the performance of our model, we can investigate each individual feature. To do so, we’ll start by getting each individual feature’s coefficient score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMrv9euEYBFtp79wLG7OIQ.png" /></figure><p>And then plot each feature’s score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7m-C24a0dI3UCvAnldTJyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*rkf-hVlLgokw6RaL5r6A9Q.png" /></figure><p>Scores marked with a zero coefficient, or very near zero coefficient, indicate that the model found those features unimportant and essentially removed them from the model. Positive scores indicate a feature that predicts class 1 (“yes”). Negative scores indicate a feature that predicts class 2 (“no”).</p><p>We can see that the features age, balance, day, and pdays have been marked as unimportant by the model.</p><p>This article outlines a simplified Logistic Regression classification algorithm. If you’re interested in fine-tuning the model in order to get a higher classification rate, I encourage you to play around with <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">function parameters</a>, as well as with the data preparation process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce50c4b137" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>