<?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 Nataliia Rastoropova on Medium]]></title>
        <description><![CDATA[Stories by Nataliia Rastoropova on Medium]]></description>
        <link>https://medium.com/@nataliia.rastoropova?source=rss-360f48188f63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mcyEHQhiptN76I-S1JpyIg.jpeg</url>
            <title>Stories by Nataliia Rastoropova on Medium</title>
            <link>https://medium.com/@nataliia.rastoropova?source=rss-360f48188f63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:24:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nataliia.rastoropova/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[Central Limit Theorem Simulation with Python]]></title>
            <link>https://medium.com/data-science/central-limit-theorem-simulation-with-python-c80f8d3a6755?source=rss-360f48188f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80f8d3a6755</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <dc:creator><![CDATA[Nataliia Rastoropova]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 16:16:55 GMT</pubDate>
            <atom:updated>2020-02-27T07:08:30.463Z</atom:updated>
            <content:encoded><![CDATA[<h4>Empirical Verification of Central Limit Theorem through simulation with Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*541suYBoGt_8S07S" /><figcaption><a href="https://unsplash.com/photos/d5LSyfDoE9M">Source</a></figcaption></figure><p><em>What is one of the most important concepts in the field of statistics but often confuses aspiring data scientists? Yes, it’s the Central Limit Theorem.</em></p><blockquote>Let’s dive into the most important theorem in data science!</blockquote><p>It is highly impossible to collect the data of the entire population. Instead of doing that we can gather a subset of data from a population and use the statistics of that sample to conclude the population.</p><h3>What is the Law of Large Numbers?</h3><p><strong>The law of large numbers </strong>(<strong>LLN</strong>) is the theory that states that the mean of the sample distribution approaches to the mean of the population distribution as the size of the sample mean would grow. So, the law of large numbers is intuitively understandable that collecting more data leads to a more representative sample.</p><h3>What is the central limit theorem?</h3><p><strong>The Central Limit Theorem (CLT)</strong> is a theory that claims that the distribution of sample means calculated from re-sampling will tend to normal, as the size of the sample increases, regardless of the shape of the population distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*V1zCLq5mboTCfq2_.jpeg" /><figcaption><em>(</em><a href="https://medium.com/@birajparikh/what-is-central-limit-theorem-clt-db3679433dcb"><em>Source</em></a><em>)</em></figcaption></figure><p><em>The difference between those two theories is that the law of large numbers states something about a single sample mean whereas the central limit theorem states something about the distribution of the sample means.</em></p><h3>What rules that data in sample distribution have to follow?</h3><ol><li>Data in the distribution should be randomly selected.</li><li>Samples should be independent of each other.</li><li>The sample size should be sufficiently large. If the distribution of the population quite normal, a sample size of 30 is considered sufficient.</li></ol><h3>Why sample size would have to be at least 30?</h3><p>There is a large number of books that quote (around) this value, for example, Hogg and Tanis’ <a href="https://www.amazon.com/Probability-Statistical-Inference-Robert-Hogg/dp/0131464132">Probability and Statistical Inference (7e)</a> says:</p><blockquote>That is, X is approximately N(μ, σ2/n), and Y is approximately N(nμ, nσ2), when n is “sufficiently large,” where μ and σ2 are, respectively, the mean and the variance of the underlying distribution from which the sample arose. Generally, if n is greater than <strong>25 or 30</strong>, these approximations will be good.</blockquote><p>Many variables in nature have a distribution that’s very close to the normal curve. Looking at the t-table, you will see that the values ​​of t with 30 degrees of freedom are close to the values ​​of z. One reason for this is that t-distributions, such as the normal distribution, are symmetric and unimodal. Thus, we can conclude that the distribution of means samples with a sample size of 30 will also be normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*oQWZDCS6VspMtaN-nzGefQ.png" /><figcaption>t-table (<a href="https://www.dummies.com/education/math/statistics/how-to-use-the-t-table-to-solve-statistics-problems/">Source</a>)</figcaption></figure><p>If distribution of the population isn’t normal you might need to try sample size far large then 30. The further away the data in population is from being symmetric and unimodal, the more data you’ll need to kick in CLT.</p><p>So, the close your distribution to a normal distribution, fewer samples needed to invoke the CLT. In practice, I never rely on <em>n</em> = 30 and advise you to try a different sampling size.</p><h3>What conclusion follows from these two theorems?</h3><ol><li>The sampling distribution of means will be normal or close to normal.</li><li>The mean of the sampling distribution will be equal to the population’s mean distribution. Mathematically,</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/0*48zDsnT9_Qw2FOl-.png" /></figure><p>3. The standard error of sampling distribution is directly linked to the standard deviation of the original population. Mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/0*xgkrpWUYALB6-nYR.png" /></figure><p>4. If we increase the samples drawn from the population, the standard deviation of sample means will decrease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*Eh2tmd4xXuXMAnq9.png" /><figcaption><a href="https://www.whatissixsigma.net/central-limit-theorem/">Source</a></figcaption></figure><h3>What is the statistical significance of CLT?</h3><p>We have some distribution, data in which isn’t normally distributed, but instead of using this distribution, we would use the distribution of sample means. This allows us kind of to cheat and to say that we can use the normal distribution ubiquitously in statistical inference, although the underlying distributions aren’t normal.</p><ol><li>The central limit theorem used in <strong>hypothesis testing.</strong></li><li>The sample mean could be used to create a range of values known as <strong>a confidence interval</strong>. These methods assume that the population is normally distributed.</li><li>CLT used in an algorithm like <strong>Stochastic Gradient Descent. </strong>How that algorithm performed? We take a batch sampled from our training set and calculate the mean or sum of the loss over the batches. Thanks for CLT now we know that the resulting distribution of the loss estimates is going to be Gaussian.</li></ol><h3>Let’s provide empirical evidence of the Central Limit Theorem through simulation with Python!</h3><p>We will use a <a href="https://www.kaggle.com/devready/coffee-and-code"><strong>Kaggle</strong></a> dataset and <strong>Python statistics libraries </strong>like <strong>Numpy, Seaborn</strong>, <strong>Matplotlib and Pandas</strong>.</p><ol><li>Firstly we imported the required libraries and then used.read_csv() to read the dataset and store it as a DataFrame object in the variable df.</li><li>We used the .head(10) attribute to take a glance at the first 10 rows of data.</li><li>We displayed all columns and their data types with .info():</li><li>The .shape attribute needed to see its <strong>dimensionality</strong>. The result is a tuple containing the number of rows and columns.</li><li>Pandas <strong>describe()</strong> is used to view some basic statistical details like percentile, mean, std, etc. of a data frame.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346ac79973403da58f085ecda47563e1/href">https://medium.com/media/346ac79973403da58f085ecda47563e1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f21a1de7fbfcb8fa17c8e805c787d606/href">https://medium.com/media/f21a1de7fbfcb8fa17c8e805c787d606/href</a></iframe><p>For an illustration of the Central Limit Theorem for sampling, we will take the “CoffeeCupsPerDay” column. Let’s plot a histogram of the number of cups of coffee drunk by programmers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1595f0485a0ddf85a1a0ede15b5361e9/href">https://medium.com/media/1595f0485a0ddf85a1a0ede15b5361e9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Q7RaAxwf-C4qIEjV8sIQWw.png" /></figure><p>As we can see the distribution of coffee cups data that programmers drink per day is positively skewed and the mean of data distribution is = 2.89. But we want to analyze data that is approximately normally distributed.</p><p>Theoretically, as the size of each sample increase then the better the sample means will approximate a Gaussian distribution. Let’s draw sufficient samples of different sizes and compute their samples means. We will take sample size=10, 40, 60 and 80 of 300 samples from our distribution. Calculate the arithmetic mean and plot the mean of the sample 300 times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/281a0e51feb64a831b465d080528d94b/href">https://medium.com/media/281a0e51feb64a831b465d080528d94b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-yTnaUlBQTINYmbdGD3-A.png" /></figure><p>So, we played around by taking different sample sizes and increasing them step by step. Then we visualized distributions of samples means with different sample-sized for comparing their shape of distribution and means. Now, we know that we’ll get a very nice bell-shaped curve as the sample sizes increase.</p><p>We can tell from the shape of the distribution with sample size 80 that the distribution is Gaussian. The mean of the sampling distribution is equal to the population’s mean distribution and equal to 2.89.</p><p>Mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*z0JpaK6HCh8CJ17qDCOzpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*pASaMeagZdb4HvCspvwGgg.png" /></figure><p>We can observe that as the sample size N → Infinity, the standard deviation of the mean goes to zero. This means that the <strong>larger the size</strong> of our dataset the smaller <strong>standard error</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlQkQA-IRCy-Vrx6sTu4eQ.png" /></figure><p>Consequently, we can consider the sampling distributions is normal, so we could use these distributions for further analysis.</p><p><em>Thank you for reading! I hope this article gave you a basic understanding of The Central Limit Theorem. If you have any questions feel free to comment or write to me on Gmail </em><a href="http://rastoropova.nataliia@gmail.com/"><em>Nataliia Rastoropova</em></a><em>.</em></p><ul><li><a href="https://towardsdatascience.com/post-for-writers-2-ebd32d1fac21">Submitting Your Article — Checklist</a></li><li><a href="https://www.analyticsvidhya.com/blog/2019/05/statistics-101-introduction-central-limit-theorem/">Learn the Central Limit Theorem in R: A Step by Step Guide (Updated 2023)</a></li><li><a href="https://machinelearningmastery.com/statistics_for_machine_learning/">Statistical Methods for Machine Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80f8d3a6755" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/central-limit-theorem-simulation-with-python-c80f8d3a6755">Central Limit Theorem Simulation with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More coffee, more code, fewer bugs? Intro to Descriptive Statistics.]]></title>
            <link>https://medium.com/analytics-vidhya/more-coffee-more-code-fewer-bugs-intro-to-descriptive-statistics-4a533ba0115c?source=rss-360f48188f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a533ba0115c</guid>
            <category><![CDATA[descriptive-statistics]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nataliia Rastoropova]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 06:28:09 GMT</pubDate>
            <atom:updated>2020-02-26T13:50:19.775Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>More coffee, more code, fewer bugs? Intro to Descriptive Statistics</h3><h4>How to explain things better and make others understand descriptive statistics easily? I will explain all basic knowledge of descriptive statistics by examples, asking important questions and answering them.</h4><p>Data Science is all about making predictions, you can’t predict if you can’t understand the patterns in existing data. The analysis helps to understand, describe, show and summarize data in a meaningful way. We will use a <a href="https://www.kaggle.com/devready/coffee-and-code"><strong>Kaggle</strong></a> dataset and <strong>Python statistics libraries </strong>like <strong>Numpy, Seaborn</strong>, <strong>Matplotlib and Pandas</strong> to clarify the most common patterns of the dataset analyzation.</p><p><strong>Some words about the dataset.</strong> This short survey focused on programmers who drink coffee. The aims were to examine if the programmers consume coffee above the normal average level and if coffee consumed helps to write code.</p><blockquote>Descriptive statistics is not answering questions when it’s actually to raise them.</blockquote><blockquote>Let’s raise as many questions as we can!</blockquote><p>A <strong>population (N) </strong>is the entire group of everyone (or everything) you’re interested in. It includes all of the elements from a set of data.</p><blockquote>Example: the population is the dataset about coffee consumed by all programmers in the world.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gzKlDcFnCutqmdgRdNqGQ.jpeg" /><figcaption>The population of programmers who drink coffee.</figcaption></figure><p>A <strong>sample (n) </strong>is a smaller group selected from the population.</p><blockquote>Example: the sample is the subset of data about coffee consumed by programmers that took part in the survey.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwodTeF9m_GsKurO6ONsNw.jpeg" /><figcaption>Sample from the population of programmers who drink coffee.</figcaption></figure><blockquote><a href="https://towardsdatascience.com/what-is-data-8f94ae3a56b4">“The sample is the data you have and the population is the data you *wish* you had.</a>”</blockquote><p><strong>Population parameter (μ)</strong> is defined as any number computed for the entire population. Examples include the population mean and population standard deviation. However, you will not usually have data available for the entire population. Therefore, the parameter is <em>unknown</em> and <em>fixed</em>.</p><blockquote>Example: let’s assume that we have dataset of coffee consumed by all programmers in the world. If we had had that entire dataset we could calculate avarage parameter <strong>(μ)=Σ(x)/N = (5+4+3+0+5+6+1+3+2+1+1+ +1+2+1+0+0+1+3+0+1+5+3+4+2+5+2+2+2+1+0) / 30 = 2.2</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFn79hkBjABTSj-PeqUhVA.png" /><figcaption>The number of cups of coffee drunk by programmers in the world per day.</figcaption></figure><p><strong>A sample statistic (x̄) </strong>is defined as any number computed from your sample data. Examples include the sample average, median, sample standard deviation, and percentiles.</p><blockquote>Example: let’s calculate from a subset the average number of cups of coffee that programmers drink per day. Sample statistic <strong>(x̄)=Σ(x)/n = (5+2+0+1+5+3+2+1+2+1+0+0+0+1) / 14 = 1.64</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTUjJrJYRfWEITXfIHLGYQ.jpeg" /><figcaption>The number of cups of coffee drunk by programmers that took part in the survey per day.</figcaption></figure><p>As you can see, the <strong>population parameter</strong> differs from a <strong>sample statistic</strong>. That difference called <strong>sampling error.</strong> A <strong>sampling error</strong> is a statistical error that occurs when an analyst does not select a sample that represents the entire population of data. <strong><em>(μ-x̄)=2.2–1.64=0.56.</em></strong></p><h4>We can make educated guesses about population parameters, using sample statistics, but we probably won’t be 100% accurate.</h4><blockquote>What will make the sample statistic closer to the population parameter?</blockquote><h4>Answer:</h4><ol><li>A bigger sample will better approximate the population parameter.</li><li>A sample has to be random.</li><li>A sample has to be an unbiased representation of a group.</li></ol><blockquote>What does it mean, that our sample has to be a random and unbiased representation of a group?</blockquote><p><strong><em>It’s mean that each member of the subset has an equal probability of being chosen.</em></strong></p><blockquote><em>Example of randomness:</em></blockquote><blockquote>“Perhaps the best typical example that we can give of the scientific meaning of <strong><em>*Random Distribution* </em></strong>is afforded by the arrangement of the drops of rain in a shower. No one can give a guess whereabouts at any instant a drop will fall. But we know that if we put out a sheet of paper it will gradually become uniformly spotted over; and that if we were to mark out any two equal areas on the paper these would gradually tend to be struck equally often.”</blockquote><blockquote>- John Venn, Logic of chance, 1888</blockquote><h3>Types of Variable</h3><p><strong>An independent variable </strong>(experimental or predictor) is a variable that is being manipulated in an experiment in order to observe the effect on a dependent variable.</p><blockquote>Example: in our scientific experiment independent variable is a count of cups of coffee that programmers drink per day.</blockquote><p><strong>A dependent variable </strong>(outcome)<strong> </strong>is a variable being tested and measured in a scientific experiment.</p><blockquote>Example: in our scientific experiment dependent variable is a count of hours that programmers work per day.</blockquote><h3>Relationship visualization</h3><p>A scatterplot is made to study the relationship between 2 variables. Thus it is often accompanied by a correlation coefficient calculation, that usually tries to measure the linear relationship.</p><blockquote>Example: let’s investigate if there is some correlation between independent variable (coffee cups per day) and dependent variable (coding hours).</blockquote><pre>import pandas as pd<br>import seaborn as sns<br>import numpy as np<br>import matplotlib.pyplot as plot</pre><pre># Declare size for pictures<br>pd.set_option(&#39;display.width&#39;, 1000)<br>pd.set_option(&#39;display.max_columns&#39;, 20)</pre><pre># Data preparation<br>df = pd.read_csv(&#39;C:../DataSet/CoffeeAndCodeLT2018.csv&#39;)</pre><pre>def look_at_data(dataset):<br>    print(dataset.head(10))<br>    print(dataset.info())<br>    print(dataset.shape)<br>    print(dataset.describe())<br>    print(dataset.columns)</pre><pre>look_at_data(df)</pre><pre>df.plot.scatter(x=&#39;CoffeeCupsPerDay&#39;, y=&#39;CodingHours&#39;)</pre><pre>plot.show(block=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*tV27D5VHt35d3gpPkbjMZw.png" /></figure><blockquote>Example: as you can see there is <strong>NO</strong> any correlation between variables.</blockquote><blockquote>Could we conclude that the count of cups of coffee was drunk doesn’t affect on count of coding hours?</blockquote><h4>Answer: NO, we couldn’t.</h4><p>But we could say that the number of cups of coffee tends do not affect the number of coding hours. Because we can’t be <strong>100% accurate </strong>in our assumption that based on sample statistics.</p><blockquote>Example: if those variables had correlated, could we say that the number of cups of coffee tends to affect the number of coding hours? <strong>NO, we couldn’t. Because of:</strong></blockquote><blockquote>Correlation does not prove causation.</blockquote><h4>Study methods</h4><p>When people read about a research study, they may not pay attention to how the study was designed. We do studies to gather information and draw conclusions. The type of conclusion we draw depends on the study method used:</p><p>In an <strong>observational study</strong><em>,</em> we measure or survey members of a sample without trying to affect them.</p><blockquote>Observational study =&gt; Show relationship</blockquote><blockquote>Example: a survey that we provided is an observational study. We interviewed programmers about coffee consumed during coding.</blockquote><p>In a <strong>controlled experiment</strong><em>,</em> we assign people or things to groups and apply some treatment to one of the groups, while the other group does not receive the treatment.</p><blockquote>Controlled experience =&gt; Show causation</blockquote><blockquote>Example: if we had two groups of programmers, those who drank coffee while coding, while others did not, it would have been a controlled experiment. And the experiment was conducted in the same room, part of a day or took into account another factor that can make an influence on the survey results.</blockquote><blockquote>What makes it difficult to make causal statements from data from observational studies?</blockquote><h4>Answer: extraneous (or lurking variable)</h4><p>A <strong>lurking </strong>variable it’s factors that could influence the relationship between two or more variables. That’s why it should be controlled in an experiment before we can make a confident causal statement.</p><blockquote>Example: in our survey took part programmers only from one country, so data could be biased. Also, some of the responses could be untruthful and some of the respondents could understand questions in the wrong way. We didn’t ask a question in what part of a day they usually drink coffee, but that factor could make influence the survey results.</blockquote><blockquote>In an experiment, the researcher manipulates the independent variable, measures change in the dependent variable and seeks to control lurking variables.</blockquote><h4>Data visualization</h4><blockquote>Why we should visualize data?</blockquote><p><strong>Answer:</strong> because just having the data table, it’s difficult to make quick conclusions. It’s could help us to see patterns, describe data and make decisions.</p><p>Instead of drawing conclusions off of the table with a multitude of unorganized data we could calculate<strong> Frequency, Relative Frequency Percentage.</strong></p><p><strong>Frequency </strong>is the number of times a given datum occurs in a data set.</p><blockquote>Example: how many males took part in survay? How many females prone to drink coffee during coding?</blockquote><pre>In:<br>print(df[&#39;Gender&#39;].value_counts())</pre><pre>Out:<br>Male      74<br>Female    26</pre><p><strong>Relative Frequency </strong>is the fraction of times an answer occurs. It is also often expressed as a <strong>percentage</strong>, you should multiply a relative frequency by 100.</p><blockquote>Example: what is the proportion of females programmers who took part in the survey? What is the proportion of males programmers who took part in the survey?</blockquote><pre>In:<br>print(df[&#39;Gender&#39;].value_counts(normalize=True))</pre><pre>Out:<br>Male      0.74<br>Female    0.26</pre><pre>In:<br>print(df[&#39;Gender&#39;].value_counts(normalize=True)*100)</pre><pre>Out:<br>Male      74.0<br>Female    26.0</pre><blockquote>All proportions are always between or equal to 0 and 1.</blockquote><blockquote>For any frequence table, the relative frequencies should add to 1.</blockquote><h4>Bar graph of frequences</h4><p>A <strong>bar chart</strong> used to compare the <strong>frequencies</strong> for a category or characteristic with another category or characteristic.</p><blockquote>Example: what proportion of programmers who participated in the survey believe that drinking coffee helps fix bugs?</blockquote><pre>sns.countplot(df[&#39;CoffeeSolveBugs&#39;])<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OrO7NarTz60oJ3BdJoEwaQ.png" /></figure><p><strong>Frequency distribution</strong>, in statistics, a <a href="https://www.britannica.com/science/graph-mathematics">graph</a> or data set organized to show the frequency of occurrence of each possible outcome of a repeatable event observed many times.</p><p>A <strong>frequency histogram</strong> is a graphical version of a frequency distribution where the width and position of rectangles are used to indicate the various classes, with the heights of those rectangles indicating the frequency with which data fell into the associated class, as the example below suggests.</p><blockquote>Example: the distribution of coffee cups data that programmers drink per day.</blockquote><pre>fig, ax = plot.subplots()<br>ax.hist(df[&#39;CoffeeCupsPerDay&#39;], bins=8, color=&#39;c&#39;, edgecolor=&#39;k&#39;, alpha=0.65)<br>ax.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FjBoRwGt1uK61T6zmroIOw.png" /></figure><h4>Bin size</h4><p>To visualizing data with a histogram we have to divide the entire range of values into a series of intervals — and then count how many values fall into each interval. Each interval is 1 bin. <strong>Bin size</strong> equals a number of bins in the histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wF7I2-DoDvai55lQhfmwbA.png" /></figure><blockquote>Example: bin size of the distribution of coffee cups data is 8.</blockquote><blockquote>Why when we visualize data with histogram, as we make the bin size bigger, the frequency gets larger?</blockquote><p><strong>Answer:</strong> as we make the bin size bigger, more values will fall inside that bin.</p><h4>Bin that is too wide can hide important details about the distribution while bin that is too narrow can cause a lot of noise and hide important information about the distribution as well.</h4><h4>What is Central Tendency?</h4><p><strong>Central Tendency </strong>refers to the idea that there is a single value that can describe a whole set of data and represent the middle or center of its distribution.</p><h3><strong>Measures of Central Tendency</strong></h3><p>The most common measures of central tendency are the arithmetic <strong>mean</strong>, the <strong>median </strong>and the <strong>mode</strong>.</p><p><strong>Mean </strong>is the numerical average of all values.</p><blockquote><strong>Σ(x)/n</strong></blockquote><blockquote>Example: what is the average value of coffee cups<strong> </strong>that programmers drink per day?</blockquote><pre>fig, ax = plot.subplots()<br>ax.hist(df[&#39;CoffeeCupsPerDay&#39;], bins=8, color=&#39;c&#39;, edgecolor=&#39;k&#39;, alpha=0.65)<br>ax.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)<br>plot.axvline(df[&#39;CoffeeCupsPerDay&#39;].mean(), color=&#39;k&#39;, linestyle=&#39;dashed&#39;, linewidth=1)<br>min_ylim, max_ylim = plot.ylim()<br>plot.text(df[&#39;CoffeeCupsPerDay&#39;].mean()*1.1, max_ylim*0.9, &#39;Mean: {:.2f}&#39;.format(df[&#39;CoffeeCupsPerDay&#39;].mean()))<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*w9PflXN9MjhwocZgUHF31w.png" /></figure><p><strong>A median </strong>is a value that directly in the middle of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*iw6BBWcIWANSxz8mwOqVXg.jpeg" /></figure><blockquote>Example: how many cups of coffee do most programmers drink per day?</blockquote><pre>fig, ax = plot.subplots()<br>ax.hist(df[&#39;CoffeeCupsPerDay&#39;], bins=8, color=&#39;c&#39;, edgecolor=&#39;k&#39;, alpha=0.65)<br>ax.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)<br>plot.axvline(df[&#39;CoffeeCupsPerDay&#39;].median(), color=&#39;k&#39;, linestyle=&#39;dashed&#39;, linewidth=1)<br>min_ylim, max_ylim = plot.ylim()<br>plot.text(df[&#39;CoffeeCupsPerDay&#39;].median()*1.1, max_ylim*0.9, &#39;Mean: {:.2f}&#39;.format(df[&#39;CoffeeCupsPerDay&#39;].median()))<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zvoaTZCx0YVrCibphfIEIg.png" /></figure><p><strong>A mode</strong> is the most frequent value at the dataset.</p><blockquote>Example: how many cups of coffee frequently most programmers drink per day?</blockquote><pre>fig, ax = plot.subplots()<br>ax.hist(df[&#39;CoffeeCupsPerDay&#39;], bins=8, color=&#39;c&#39;, edgecolor=&#39;k&#39;, alpha=0.65)<br>ax.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)<br>plot.axvline(df[&#39;CoffeeCupsPerDay&#39;].mode()[0], color=&#39;k&#39;, linestyle=&#39;dashed&#39;, linewidth=1)<br>min_ylim, max_ylim = plot.ylim()<br>plot.text(df[&#39;CoffeeCupsPerDay&#39;].mode()[0]*1.1, max_ylim*0.9, &#39;Moda: {:.2f}&#39;.format(df[&#39;CoffeeCupsPerDay&#39;].mode()[0]))<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ympD8PXtFdaA6AqVwsIxtQ.png" /></figure><p>If two values appeared at the same time and more than the rest of the values then the data set is <strong>bimodal</strong>. If three values appeared at the same time and more than the rest of the values then the data set is <strong>trimodal</strong> and for n modes, that data set is <strong>multimodal</strong>. If a distribution is <strong>uniformed </strong>it has <strong>no mode.</strong></p><blockquote>The mean and mode are highly sensitive to outliers. The mean and mode can be misleading when we have outliers in distribution.</blockquote><h3>Measures of Variability</h3><p>The measures of central tendency aren’t sufficient to describe data. You’ll also need the <strong>measures of variability</strong> that quantify the spread of data points.</p><blockquote>How we could quantify spread outness or consistency of distribution?</blockquote><p><strong>Answer: </strong>calculate the range of distribution.</p><h4><strong>Range</strong></h4><p><strong>A range </strong>is a difference between the maximum value and the minimum value observed.</p><pre>r=df[&#39;CoffeeCupsPerDay&#39;].max()- df[&#39;CoffeeCupsPerDay&#39;].min()<br>print(&#39;Range: &#39;,r)</pre><blockquote>Example: range of the distribution of coffee cups data is 8 – 1=7.</blockquote><h4><strong>Quartiles</strong></h4><p><strong>Quartiles </strong>are the points in the data set that divides the data set into four equal parts. Q1, Q2, and Q3 are the first, second and third quartile of the data set.</p><ol><li>Q1 is the point where 25% of the distribution is below that point, and 75% of the data is above that point.</li><li>50% of the data points lie below Q2 and 50% lie above it. Q2 is nothing but Median.</li><li>Q3 is the point where 75% of the distribution is below that point, and 25% of the data is above that point.</li></ol><p><strong>Interquartile range (IQR)</strong> is the distance between Q1 and Q3 quartile and gives us the range of the middle 50% of our data.</p><blockquote>Example: <strong>IQR</strong>= Q3-Q1 = 4-2 = 2</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*w--SB4gbYy7OWcTT9Qqeew.png" /></figure><pre>fig, ax = plot.subplots()<br>ax.boxplot(df[&#39;CoffeeCupsPerDay&#39;], vert=False, showmeans=True, meanline=True, patch_artist=True,<br>           medianprops={&#39;linewidth&#39;: 2, &#39;color&#39;: &#39;purple&#39;},<br>           meanprops={&#39;linewidth&#39;: 2, &#39;color&#39;: &#39;red&#39;})<br>ax.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>ax.set_ylabel(&#39;Frequency&#39;)<br>plot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XH5dWym0r_xOfxSjWqfUvA.png" /></figure><blockquote>Exsamle:</blockquote><blockquote><strong>The mean</strong> is the red dashed line.</blockquote><blockquote><strong>The median</strong> is the purple line.</blockquote><blockquote><strong>The first quartile</strong> is the left edge of the blue rectangle.</blockquote><blockquote><strong>The third quartile</strong> is the right edge of the blue rectangle.</blockquote><blockquote><strong>The interquartile range</strong> is the length of the blue rectangle.</blockquote><blockquote><strong>The range</strong> contains everything from left to right.</blockquote><blockquote><strong>The outliers</strong> are the dot to the right.</blockquote><h4><strong>Outlier</strong></h4><p>An <strong>outlier</strong> is a data point that differs significantly from the majority of the data taken from a sample or population. There are many possible causes of outliers: the natural variation in data, change in the behavior of the observed system, errors in data collection. A value is considered an <strong>outlier </strong>if it <strong>&lt; Q1 – 1,5 * IQR</strong> or<strong> &gt; Q1 + 1,5 * IQR</strong></p><blockquote>How to deal with outliers?</blockquote><p><strong>Answer:</strong> statisticians usually cut of tails (data before Q1 and data after Q3) and consider the data values in the middle.</p><h4><strong>Absolute Deviation from Mean</strong></h4><p><strong>Absolute Deviation from Mean — </strong>describe the variation in the dataset<strong> </strong>by finding the average distance between each data value and the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*ZZ6kVl5De-7c6cROLzTpvA.png" /></figure><pre>print(df[&#39;CoffeeCupsPerDay&#39;].mad())</pre><blockquote>Example: mean absolute deviation of the distribution of coffee cups data that programmers drink per day = 1.21</blockquote><h4><strong>Variance</strong></h4><p><strong>Variance </strong>measures how far are data points spread out from the mean. A high variance indicates that data points are spread widely and a small variance indicates that the data points are closer to the mean of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*wVIBemS_rzzzrtZDaG8kGg.png" /></figure><pre>print(df[&#39;CoffeeCupsPerDay&#39;].var())</pre><blockquote>Example: standart varience of the distribution of coffee cups data that programmers drink per day = 2.6039393939393936</blockquote><h4><strong>Standard deviation</strong></h4><p><strong>Standard deviation </strong>is the<strong> </strong>square root of Variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*bF3DigwqlEqkMWAci23t8w.png" /></figure><pre>print(df[&#39;CoffeeCupsPerDay&#39;].std())</pre><blockquote>Example: standart deviation of the distribution of coffee cups data that programmers drink per day = 1.613672641504278</blockquote><p>The <strong>standard deviation </strong>allows us to reach some conclusions about specific scores in our distribution:</p><ul><li>approximately 68% of the scores in the sample fall within one standard deviation of the mean</li><li>approximately 95% of the scores in the sample fall within two standard deviations of the mean</li><li>approximately 99% of the scores in the sample fall within three standard deviations of the mean</li></ul><h4><strong>Skewness</strong></h4><p><strong>Skewness </strong>is a measurement of the symmetry of a distribution. A good measurement for the skewness of a distribution is Pearson’s skewness coefficient that provides a quick estimation of the symmetry of a distribution.</p><p>The most commonly used method of calculating skewness is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*T8i7lE2iR-gXRUHAxZYKTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*XF_erDuQDD7F_oIP.jpg" /><figcaption><a href="https://en.wikipedia.org/wiki/Skewness">Source</a></figcaption></figure><pre>fig = sns.distplot(df[&#39;CoffeeCupsPerDay&#39;], hist=True, kde=True,<br>             bins=8, color = &#39;c&#39;,<br>             hist_kws={&#39;edgecolor&#39;:&#39;black&#39;},<br>             kde_kws={&#39;linewidth&#39;: 4})<br>fig.set_xlabel(&#39;CoffeeCupsPerDay&#39;)<br>fig.set_ylabel(&#39;Frequency&#39;)<br>plot.show()<br>print(df[&#39;CoffeeCupsPerDay&#39;].skew())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*eSLaxqKa38GzFszyfx26hw.png" /></figure><blockquote>Example: the distribution of coffee cups data that programmers drink per day is positively skewed. Unbiased skew coeficient over requested axis = 1.2564210906444842</blockquote><blockquote>If the skewness is zero, the distribution is symmetrical. If it is negative, the distribution is Negatively Skewed and if it is positive, it is Positively Skewed.</blockquote><h4><strong>Kurtosis</strong></h4><p><strong>Kurtosis </strong>is a measure of whether the data are heavy-tailed (profusion of outliers) or light-tailed (lack of outliers) relative to a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*UYT7VYlI3JPPmXaA.jpg" /><figcaption><a href="https://financetrain.com/interpretation-of-skewness-kurtosis-coskewness-cokurtosis/">Source</a></figcaption></figure><h3>Theoretical Normal Distribution</h3><p>All statistical tests require normally distributed data, but this doesn’t usually happen. <strong>Real-life data rarely, if ever, follow a perfectly normal distribution</strong>. A normal Distribution is given if your data is symmetrical, bell-shaped, centered and unimodal.</p><blockquote>The <strong>mean</strong>, <strong>median</strong>, and <strong>mode</strong> of a <strong>normal distribution</strong> are equal. The area under the <strong>normal curve</strong> is equal to 1. A normal distribution is <strong>perfectly symmetrical</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BSNnxvk45g0GUscd.png" /><figcaption>A normal distribution (<a href="https://towardsdatascience.com/intro-to-descriptive-statistics-and-probability-for-data-science-8effec826488">Source</a>)</figcaption></figure><p>In the next medium post, we will discuss Central Limit Theorem and Z-score.</p><p><em>I welcome feedback and constructive criticism and can be reached on Gmail </em><a href="https://medium.com/u/360f48188f63"><em>Nataliia Rastoropova</em></a><em>.</em></p><ul><li><a href="https://classroom.udacity.com/courses/ud827">Udacity</a></li><li><a href="https://www.kaggle.com/devready/coffee-and-code">Coffee and Code</a></li><li><a href="https://towardsdatascience.com/descriptive-statistics-f2beeaf7a8df">Descriptive Statistics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a533ba0115c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/more-coffee-more-code-fewer-bugs-intro-to-descriptive-statistics-4a533ba0115c">More coffee, more code, fewer bugs? Intro to Descriptive Statistics.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-step guide for  predicting Wine Quality using Scikit-Learn]]></title>
            <link>https://medium.com/analytics-vidhya/step-by-step-guide-for-predicting-wine-quality-using-scikit-learn-de5869f8f91a?source=rss-360f48188f63------2</link>
            <guid isPermaLink="false">https://medium.com/p/de5869f8f91a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Nataliia Rastoropova]]></dc:creator>
            <pubDate>Fri, 17 May 2019 18:53:55 GMT</pubDate>
            <atom:updated>2020-07-28T18:43:16.874Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Step-by-step guide for predicting Wine Preferences using Scikit-Learn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FqqFJcwgu8dQ4z7Qc5G8vQ.gif" /></figure><p>In <em>case you are new at Machine Learning and it’s hair-raising to write Machine Learning project just dive into the data science pipeline with this blog-post. This blog-post covers the basic Machine Learning process in Python step-by-step.</em></p><p><strong>Basic steps of a data science pipeline:</strong></p><ol><li>Frame the problem and look at the big picture.</li><li>Get the data.</li><li>Explore the data to gain insights.</li><li>Prepare the data to better expose the underlying data patterns to Machine Learning algorithms.</li><li>Explore many different models and short-list the best ones.</li><li>Fine-tune your models and combine them into a great solution.</li><li>Present your solution.</li><li>Launch, monitor, and maintain your system.</li></ol><blockquote>Feel free to adapt this pipeline to your needs!</blockquote><h4>1. Frame the problem and look at the big picture.</h4><p>Firstly, we need to define the objective in business terms. For our work is to predict human wine taste preferences that are based on easily available analytical tests at the certification step. We expect to get an accuracy score of more than 90%. Predicted value could be used for designing new types of wine, defining pricing policy or supporting decision making in advisory systems.</p><p>During problem framing, we defined that our system would be using batch learning techniques. It would be an expensive and unnecessary task if we had gathered more data and provided controlled research of wine ranking based on physicochemical properties.</p><p>Therefore the system will be trained and then launched into production and run without learning anymore. It just will apply what it has learned. This will generally take time and computing resources.</p><p>Also, we could try two kinds of approaches:</p><ul><li>build an instance-based learning system by comparing new data points to known data points.</li><li>build a model-based learning system by detecting patterns in the training data and build a predictive model, much like scientists do.</li></ul><blockquote><strong>Let’s make assumptions.</strong></blockquote><blockquote>The null hypothesis (<em>H0</em>) is that <em>none</em> of the variance in the quality ranking is explained by physicochemical properties. The alternate hypothesis (<em>H1</em>) is that physicochemical properties contribution to the variance in the quality ranking and make a wine ‘good’ or vice verse ‘bad’.</blockquote><h4>2. Get the data</h4><p>We will use a real data set related to red Vinho Verde wine samples, from the north of Portugal. This dataset is available from the UCI machine learning repository, <a href="https://archive.ics.uci.edu/ml/datasets/wine+quality.">https://archive.ics.uci.edu/ml/datasets/wine+quality.</a><em> </em>This dataset can be viewed as classification or regression tasks.</p><p><strong><em>Input variables (based on physicochemical tests):</em></strong><br><em>1 fixed acidity;<br>2 volatile acidity;<br>3 citric acid;<br>4 residual sugar; <br>5 chlorides; <br>6 free sulfur dioxide; <br>7 total sulfur dioxide; <br>8 density; <br>9 pH; <br>10 sulphates; <br>11 alcohol.</em></p><p><strong><em>Output variable (based on sensory data): </em></strong><em><br>12 quality (score between 0 and 10).</em></p><p>Let’s get the data and convert them to a format of a data frame for making manipulation with their easier. Data investigation is an interesting and addictive task. Take a look at your data, check the dimensionality and type of them.</p><p>In [1]:</p><pre># Load in the red wine data from the UCI ML website.<br>df = pd.read_csv(&#39;http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv&#39;,sep=&#39;;&#39;)</pre><pre># Take a look<br>print(df.head(10))<br># Data dimensionality (rows, colums)<br>print(df.shape)<br># Data distributing<br>df.info()</pre><p>Out [1]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c3321676242a8e10811e0cbbde6b456/href">https://medium.com/media/4c3321676242a8e10811e0cbbde6b456/href</a></iframe><p>Before data investigation you should have been done with one of the most important steps is <strong>data splitting. </strong>The data has been split into two groups: training set <em>80%</em>, test set<em> 20%</em>. The training set should be used to build your machine learning models. The test set should be used to see how well your model performs on unseen data.</p><p>In [2]:</p><pre># Now seperate the dataset as response variable and feature variabes<br>X = df.drop(&#39;quality&#39;, axis=1)<br>y = df[&#39;quality&#39;]</pre><pre># Train and Test splitting of data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=50)</pre><pre># Applying Standard scaling to get optimized result<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.fit_transform(X_test)</pre><blockquote>No data snooping!</blockquote><h4>3. Explore the data to gain insights</h4><p>So far we have only taken a quick glance at the data to get a general understanding of the kind of data we are manipulating. Now we would be exploring data using a test set.</p><p>It would be interesting to take a look at the basic statistical characteristics of each numerical feature. The count, mean, min, and max rows are self-explanatory. The std row shows the standard deviation (which measures how dispersed the values are). The 25%, 50%, and 75% of rows show the corresponding percentiles.</p><p>In [3]:</p><pre># Statistical characteristics of each numerical feature<br>print(df.describe())</pre><p>Out [3]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff485d41ca9d274efc5b8fd5656e309a/href">https://medium.com/media/ff485d41ca9d274efc5b8fd5656e309a/href</a></iframe><p>Visualizing data is crucial for recognizing underlying patterns to exploit in the model. When the data visualizing properly it’s clear to see trends and patterns, the correlation between variables, because our brains are very good at spotting patterns on pictures. Let’s play around with different types of data visualization, parameters to make the patterns stand out.</p><p>Using the following plots we may understand data distribution for separate attributes; <strong>for example, data distribution for attribute “alcohol” is positively skewed, for attribute “<em>density</em>” data quite normally distributed. Take attention to the wine quality data distribution. It’s a bimodal distribution and there are more wines with average quality than wines with ‘good’ or ‘bad’ quality.</strong></p><p>In [4]:</p><pre># Histograms<br>df.hist(bins=10,figsize=(6, 5))<br>plt.show()</pre><pre># Density<br>df.plot(kind=&#39;density&#39;, subplots=True, layout=(4,3), sharex=False)<br>plt.show()</pre><p>Out [4]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnCsFbYSQep-Jrf5jBNXcQ.png" /><figcaption>Histogram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjwmwfjyY4I_MTRydFTJcA.png" /><figcaption>Density</figcaption></figure><p>Another way exploring data is an incredibly handy tool pivot table. A pivot table is a summary of your data, packaged in a chart that lets you report on and explore trends based on your information. Pivot tables are particularly useful if you have long rows or columns that hold values you need to track the sums of and easily compare to one another. So, our pivot table describes the median value each feature for each score of quality. Now we can follow trends, for example, the highest value for ‘sulphates’ tend the highest ‘quality’ score. But we can’t draw our conclusion based on correlation.</p><blockquote>Correlation does not cause causation.</blockquote><p>In [5]:</p><pre># Create pivot_table<br>colum_names = [&#39;fixed acidity&#39;, &#39;volatile acidity&#39;, &#39;citric acid&#39;, &#39;residual sugar&#39;, &#39;chlorides&#39;, &#39;free sulfur dioxide&#39;, &#39;total sulfur dioxide&#39;, &#39;density&#39;, &#39;pH&#39;, &#39;sulphates&#39;, &#39;alcohol&#39;]<br>df_pivot_table = df.pivot_table(colum_names,<br>               [&#39;quality&#39;], aggfunc=&#39;median&#39;)<br>print(df_pivot_table)</pre><p>Out [5]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4918c91d5fd71d696e77fd4baa53e5b/href">https://medium.com/media/d4918c91d5fd71d696e77fd4baa53e5b/href</a></iframe><p>For understanding how much each attribute correlates with the quality score of wine compute the standard correlation coefficient (also called Pearson’s r) between every pair of attributes.</p><p>In [6]:</p><pre>corr_matrix = df.corr()<br>print(corr_matrix[&quot;quality&quot;].sort_values(ascending=False))</pre><p>Out [5]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb5e878c296b0fe5696d86b7ff42a68/href">https://medium.com/media/bbb5e878c296b0fe5696d86b7ff42a68/href</a></iframe><p>The correlation coefficient ranges from –1 to 1. When it is close to 1, it means that there is a strong positive correlation; for example, <strong>the ‘quality’ value tends to go up when the ‘alcohol’ goes up</strong>. When the coefficient is close to –1, it means that there is a strong negative correlation; <strong>you can see a small negative correlation between the ‘volatile acidity’ and the ‘quality’ value</strong>. Finally, coefficients close to zero mean that there is no linear correlation.</p><p>You could see more detailed information about data correlation using the correlation matrix. The correlation matrix gives us information about how the two variables interact, both the direction and magnitude.</p><p>In [7]:</p><pre>colum_names = [&#39;fixed acidity&#39;, &#39;volatile acidity&#39;, &#39;citric acid&#39;, &#39;residual sugar&#39;, &#39;chlorides&#39;, &#39;free sulfur dioxide&#39;, &#39;total sulfur dioxide&#39;, &#39;density&#39;, &#39;pH&#39;, &#39;sulphates&#39;, &#39;alcohol&#39;, &#39;quality&#39;]<br># Correlation matrix<br>correlations = df.corr()<br># Plot figsize<br>fig, ax = plt.subplots(figsize=(10, 10))<br># Generate Color Map<br>colormap = sns.diverging_palette(220, 10, as_cmap=True)<br># Generate Heat Map, allow annotations and place floats in map<br>sns.heatmap(correlations, cmap=colormap, annot=True, fmt=&quot;.2f&quot;)<br>ax.set_xticklabels(<br>    colum_names,<br>    rotation=45,<br>    horizontalalignment=&#39;right&#39;<br>);<br>ax.set_yticklabels(colum_names);<br>plt.show()</pre><p>Out [7]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMwys0nXPQhg5ozVN8ZnwQ.png" /></figure><p>You could visualize the scatterplot matrix for the better understanding relationship between a pair of variables. It plots every numerical attribute against every other.</p><p>In[8]:</p><pre># Scatterplot Matrix<br>sm = scatter_matrix(df, figsize=(6, 6), diagonal=&#39;kde&#39;)<br>#Change label rotation<br>[s.xaxis.label.set_rotation(40) for s in sm.reshape(-1)]<br>[s.yaxis.label.set_rotation(0) for s in sm.reshape(-1)]<br>#May need to offset label when rotating to prevent overlap of figure<br>[s.get_yaxis().set_label_coords(-0.6,0.5) for s in sm.reshape(-1)]<br>#Hide all ticks<br>[s.set_xticks(()) for s in sm.reshape(-1)]<br>[s.set_yticks(()) for s in sm.reshape(-1)]<br>plt.show()</pre><p>Out[8]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHEo9XT7pLunU0KKfbbA0w.png" /></figure><p>Take attention to the correlation between attributes ‘fixed acidity’ and ‘density’. The correlation coefficient for them is 0.67 (you could find value at the correlation matrix) and looking at corresponding for them scatterplot we can see the positive linear correlation between attributes. You can also clearly see the upward trend and the points are not too dispersed between those attributes. In that way, you could analyze other attributes.</p><blockquote>One last thing you may want to do before actually preparing the data for Machine Learning algorithms is to try out various attribute combinations.</blockquote><h4>4. Prepare the data to better expose the underlying data patterns to Machine Learning algorithms</h4><p>It’s time to prepare the data for our Machine Learning algorithms. In our dataset there aren’t any missing values, outliers, attributes that provide no useful information for the task. So, we could conclude that our data set is quite clean. Therefore, we won’t do any grueling data preparation, but some stuff will be needed to do. Human wine preferences scores varied from 3 to 8, so it’s straightforward to categorize answers into ‘bad’ or ‘good’ quality of wines. This allows us to practice with hyperparameter tuning on e.g. decision tree algorithms. Visualizing the graph of the number of values for each category, we could see that there are far many bad answers than good ones. Of course, machine learning algorithms operate digital values, so we assign for categorizes corresponding discrete values 0 or 1.</p><p>In[9]:</p><pre># Dividing wine as good and bad by giving the limit for the quality<br>bins = (2, 6, 8)<br>group_names = [&#39;bad&#39;, &#39;good&#39;]<br>df[&#39;quality&#39;] = pd.cut(df[&#39;quality&#39;], bins = bins, labels = group_names)</pre><pre># Now lets assign a labels to our quality variable<br>label_quality = LabelEncoder()<br># Bad becomes 0 and good becomes 1<br>df[&#39;quality&#39;] = label_quality.fit_transform(df[&#39;quality&#39;])<br>print(df[&#39;quality&#39;].value_counts())</pre><pre>sns.countplot(df[&#39;quality&#39;])<br>plt.show()</pre><p>Out[9]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9IPdJlEszRF4IGH0BeSgKA.png" /></figure><h4>5. Explore many different models and short-list the best ones</h4><p>Evaluating a Machine Learning model can be quite tricky. Usually model evaluated performance based on an error metric. Nevertheless, this method is not very reliable as the accuracy obtained for one test set can be very different to the accuracy obtained for a different test set.</p><p>In the example below 8 different algorithms are compared:</p><ol><li>Support Vector Classifier</li><li>Stochastic Gradient Decent Classifier</li><li>Random Forest Classifier</li><li>Decision Tree Classifier</li><li>Gaussian Naive Bayes</li><li>K-Neighbors Classifier</li><li>Ada Boost Classifier</li><li>Logistic Regression</li></ol><p>The key to a fair comparison of machine learning algorithms is ensuring that each algorithm is evaluated in the same way on the same data. <em>K-fold Cross Validation(CV) </em>provides a solution to this problem by dividing the data into folds and ensuring that each fold is used as a testing set at some point.</p><p>In[10]:</p><pre># prepare configuration for cross validation test harness<br>seed = 7<br># prepare models<br>models = []<br>models.append((&#39;SupportVectorClassifier&#39;, SVC()))<br>models.append((&#39;StochasticGradientDecentC&#39;, SGDClassifier()))<br>models.append((&#39;RandomForestClassifier&#39;, RandomForestClassifier()))<br>models.append((&#39;DecisionTreeClassifier&#39;, DecisionTreeClassifier()))<br>models.append((&#39;GaussianNB&#39;, GaussianNB()))<br>models.append((&#39;KNeighborsClassifier&#39;, KNeighborsClassifier()))<br>models.append((&#39;AdaBoostClassifier&#39;, AdaBoostClassifier()))<br>models.append((&#39;LogisticRegression&#39;, LogisticRegression()))</pre><pre># evaluate each model in turn<br>results = []<br>names = []<br>scoring = &#39;accuracy&#39;<br>for name, model in models:<br>   kfold = model_selection.KFold(n_splits=10, random_state=seed)<br>   cv_results = model_selection.cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)<br>   results.append(cv_results)<br>   names.append(name)<br>   msg = &quot;%s: %f (%f)&quot; % (name, cv_results.mean(), cv_results.std())<br>   print(msg)<br># boxplot algorithm comparison<br>fig = plt.figure()<br>fig.suptitle(&#39;Algorithm Comparison&#39;)<br>ax = fig.add_subplot(111)<br>plt.boxplot(results)<br>ax.set_xticklabels(names)<br>plt.show()</pre><p>Out[10]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a253d1189738124b7e5d7808fe77d62/href">https://medium.com/media/0a253d1189738124b7e5d7808fe77d62/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZbUrOLrRLmX2S7IMJN2iQ.png" /></figure><h4>6.Fine-tune your models and combine them into a great solution</h4><p>There are several factors that can help you determine which algorithm performs best. One such factor is the performance on cross-validation set and another factor is the choice of parameters for an algorithm.</p><p>Let’s fine-tune some Machine Learning algorithms. The first algorithm that we trained and then evaluated was Support Vector Classifier and the mean value for model prediction was equal<em> 0.873364</em>. What is the most harmonious way to choose hyper-parameters to your model? It is trying to guess or looping over parameters and then run all the combinations of parameters? There is one more advantageous way to use Grid Search CV.</p><p>In[11]:</p><pre>def svc_param_selection(X, y, nfolds):<br>    param = {<br>        &#39;C&#39;: [0.1, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4],<br>        &#39;kernel&#39;: [&#39;linear&#39;, &#39;rbf&#39;],<br>        &#39;gamma&#39;: [0.1, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4]<br>    }<br>    grid_search = GridSearchCV(svc, param_grid=param, scoring=&#39;accuracy&#39;, cv=nfolds)<br>    grid_search.fit(X,  y)<br>    return grid_search.best_params_</pre><pre>print(svc_param_selection(X_train, y_train,10))</pre><p>Out[11]:</p><pre>{&#39;C&#39;: 1.3, &#39;gamma&#39;: 1.3, &#39;kernel&#39;: &#39;rbf&#39;}</pre><p>Let’s run our SVC again with the best parameters.</p><p>In[12]:</p><pre>svc = SVC(C = 1.3, gamma =  1.3, kernel= &#39;rbf&#39;)<br>svc.fit(X_train, y_train)<br>pred_svc = svc.predict(X_test)<br>print(&#39;Confusion matrix&#39;)<br>print(confusion_matrix(y_test, pred_svc))print(&#39;Classification report&#39;)<br>print(classification_report(y_test, pred_svc2))<br>print(&#39;Accuracy score&#39;,accuracy_score(y_test, pred_svc2))</pre><p>Out[12]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214883a4817ae798f5982b73b2d31064/href">https://medium.com/media/214883a4817ae798f5982b73b2d31064/href</a></iframe><p>So, after choosing parameters for an algorithm accuracy score for predicting wine preference is 93%.</p><p>Now let’s try to fine-tune another algorithm AdaBoost, with an accuracy score of 86%, using cross-validation.</p><p>In[13]:</p><pre>ada_classifier = AdaBoostClassifier(n_estimators=100)<br>ada_classifier.fit(X_train, y_train)<br>pred_ada = ada_classifier.predict(X_test)<br><br># Cross-validation<br>scores = cross_val_score(ada_classifier,X_test,y_test, cv=5)<br>print(&#39;Accuracy score&#39;,scores.mean())</pre><p>Out[13]:</p><pre>Accuracy score 0.903</pre><p>Another absorbing thing that we could analyze is feature importance for Machine Learning Algorithms.</p><pre>importance=ada_classifier.feature_importances_<br><br>std = np.std([tree.feature_importances_ for tree in ada_classifier.estimators_],<br>             axis=0)<br>indices = np.argsort(importance)<br><br># Plot the feature importances of the forest<br>plt.figure()<br>plt.title(&quot;Feature importances&quot;)<br>plt.barh(range(X.shape[1]), importance[indices],<br>       color=&quot;b&quot;,  align=&quot;center&quot;)<br><br>plt.yticks(range(X.shape[1]), colum_names)<br>plt.ylim([0, X.shape[1]])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*idiuaRj7vjs4HjD67NoLXw.png" /></figure><h4>7. Present your solution</h4><p>Let’s make some conclusions based on the pipeline that we have done. Our data set is quite clean and representative. We categorize target value into discrete values that correspond ‘bad or ‘good’ quality of wines.</p><p>Getting inside the data set we found an interesting correlation between features ‘alcohol’ and ‘quality of wine’, ‘fixed acidity’ and ‘density’ and another one. After analyzing feature importance for Machine Learning Algorithms we could conclude that tuning features like ‘alcohol’, ‘sulphates’ and ‘pH’ may make wine scores higher or lower. Based on this information would be profitable to change your tune and play around with the physicochemical properties of wine. Because it could make impact on human preferences.</p><p>Through comparison analyze that we provided we could highlight Machine Learning algorithms like <em>Support Vector Classifier</em> and <em>Random Forest Classifier. </em>Box plots of those algorithm’s accuracy distribution quite symmetrical, without outliers. Adjacent box plot values are close together that corresponds to the high density of accuracy scores.</p><p>By the way, without tuning Machine Learning algorithms we can’t achieve average accuracy scores more than 90 % for prediction wine preference. We fine-tuned <em>Support Vector Classifier </em>using <em>Grid Search CV </em>and achieve <strong>accuracy score 93%. </strong>The goal had achieved.</p><h4>8. Launch, monitor, and maintain your system</h4><p>Now your solution is ready for production! This system uses batch learning technique and won&#39;t train on fresh data. Therefore, it doesn&#39;t tend to “rot” as data evolves over time. But if your model regularly trained on fresh data you need to write monitoring code to check your system’s live performance at regular intervals and trigger alerts when it drops. In that case, you could catch not only sudden breakage but also performance degradation.</p><blockquote><em>A full Jupyter Notebook of code for the project can be located </em><a href="https://gist.github.com/NataliiaRastoropova/1d861775c47516d99e8dcb444eaa7049"><em>here</em></a><em>.</em></blockquote><blockquote>Thank you for reading! I hope this article gave you a basic understanding of data science pipeline. If you have any questions or find a mistake feel free to comment or write to me shkarupa.nataliia@gmail.com.</blockquote><p><em>References:</em></p><p><a href="https://www.amazon.com/Hands-Machine-Learning-Scikit-Learn-TensorFlow/dp/1491962291/ref=sr_1_4">‘Hands on Machine Learning with Scikit-Learn and Tensorflow</a>’</p><ul><li><a href="https://www.kaggle.com/uciml/red-wine-quality-cortez-et-al-2009">Red Wine Quality</a></li><li><a href="https://dictionary.cambridge.org/ru/%D1%81%D0%BB%D0%BE%D0%B2%D0%B0%D1%80%D1%8C/%D0%B0%D0%BD%D0%B3%D0%BB%D0%B8%D0%B9%D1%81%D0%BA%D0%B8%D0%B9/absorbing?topic=exciting-and-interesting">Определение ABSORBING в кембриджском словаре английского языка</a></li><li><a href="https://medium.com/datadriveninvestor/k-fold-cross-validation-6b8518070833">K-Fold Cross Validation</a></li><li><a href="https://machinelearningmastery.com/compare-machine-learning-algorithms-python-scikit-learn/">How To Compare Machine Learning Algorithms in Python with scikit-learn - Machine Learning Mastery</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de5869f8f91a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/step-by-step-guide-for-predicting-wine-quality-using-scikit-learn-de5869f8f91a">Step-by-step guide for  predicting Wine Quality using Scikit-Learn</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>